.png)
最近在研究怎么对图片资源进行无损压缩,网上也找了一些资料。总而言之,收获不少,所以想对最近的学习做个总结。
无损压缩其实是相对而言的,目的是为了减小图片资源的内存大小但又不影响图片的显示质量。下面我将介绍两种批量压缩图片的方法,方法一是使用python和Pillow模块对图片进行压缩,这个方法对jpeg格式的图片有非常高的压缩效率,但该方法不太适合对png图片进行压缩。另一个方式是使用Python和Selenium模块操纵Squoosh批量压缩图片。
Pillow是Python上一个功能非常强大的图形处理库,若本地还没安装,可以通过指令:pip install Pillow安装。使用Pillow进行压缩的策略大致总结为三个:1、优化flag,2、渐进式JPEG,3、JPEG动态质量。
我们先用Python写一个简单的保存图片的例子:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | fromPIL importImagefromio importStringIOimportdynamic_qualityim =Image.open("photo.jpg")print(im.format,im.size,im.mode)new_photo =im.copy()new_photo.thumbnail(im.size,resample=Image.ANTIALIAS)save_args ={'format':im.format}ifim.format=='JPEG':    save_args['quality'].value=85new_photo.save("copy_photo.jpg",**save_args) | 
开启optimize设置,这是以CPU耗时为代价节省额外的文件大小,由于本质没变,对图片质量没有丝毫影响。
| 1 2 3 4 5 | ...ifim.format=='JPEG':    save_args['quality'].value=85    save_args['optimize']=True... | 
当我们将一张图片保存为 JPEG 时,你可以从下面的选项中选择不同的类型:
渐进式的选项可以在 Pillow 中轻松的启用 (progressive=True)。渐进式文件的被打包时会有一个小幅的压缩。
| 1 2 3 4 5 6 | ...ifim.format=='JPEG':    save_args['quality'].value=85    save_args['optimize']=True    save_args['progressive=True']=True... | 
最广为人知的减小 JPEG 文件大小的方法就是设置 quality。很多应用保存 JPEG 时都会设置一个特定的质量数值。
质量其实是个很抽象的概念。实际上,一张 JPEG 图片的每个颜色通道都有不同的质量。质量等级从 0 到 100 在不同的颜色通道上都对应不同的量化表,同时也决定了有多少信息会丢失。
在信号域量化是 JPEG 编码中失去信息的第一个步骤。
我们可以动态地为每一张图片设置最优的质量等级,在质量和文件大小之间找到一个平衡点。我们有以下两种方法可以做到这点:
Bottom-up: 这些算法是在 8x8 像素块级别上处理图片来生成调优量化表的。它们会同时计算理论质量丢失量和和人眼视觉信息丢失量。
Top-down: 这些算法是将一整张图片和它原版进行对比,然后检测出丢失了多少信息。通过不断地用不同的质量参数生成候选图片,然后选择丢失量最小的那一张。
我们选择第二种方法:使用二分法在不同的质量等级下生成候选图片,然后使用 pyssim 计算它的结构相似矩阵 (SSIM) 来评估每张候选图片损失的质量,直到这个值达到非静态可配置的阈值为止。这个方法让我们可以有选择地降低文件大小(和文件质量),但是只适用于那些即使降低质量用户也察觉不到的图片。
下面是计算动态质量的代码dynamic_quality.py:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | importPIL.Imagefrommath importlogfromSSIM_PIL importcompare_ssimdefget_ssim_at_quality(photo, quality):    """Return the ssim for this JPEG image saved at the specified quality"""    ssim_photo ="tmp.jpg"    # optimize is omitted here as it doesn't affect    # quality but requires additional memory and cpu    photo.save(ssim_photo, format="JPEG", quality=quality, progressive=True)    ssim_score =compare_ssim(photo, PIL.Image.open(ssim_photo))    returnssim_scoredef_ssim_iteration_count(lo, hi):    """Return the depth of the binary search tree for this range"""    iflo >=hi:        return0    else:        returnint(log(hi -lo, 2)) +1defjpeg_dynamic_quality(original_photo):    """Return an integer representing the quality that this JPEG image should be    saved at to attain the quality threshold specified for this photo class.    Args:        original_photo - a prepared PIL JPEG image (only JPEG is supported)    """    ssim_goal =0.95    hi =85    lo =80    # working on a smaller size image doesn't give worse results but is faster    # changing this value requires updating the calculated thresholds    photo =original_photo.resize((400, 400))    # if not _should_use_dynamic_quality():    #     default_ssim = get_ssim_at_quality(photo, hi)    #     return hi, default_ssim    # 95 is the highest useful value for JPEG. Higher values cause different behavior    # Used to establish the image's intrinsic ssim without encoder artifacts    normalized_ssim =get_ssim_at_quality(photo, 95)    selected_quality =selected_ssim =None    # loop bisection. ssim function increases monotonically so this will converge    fori inrange(_ssim_iteration_count(lo, hi)):        curr_quality =(lo +hi) //2        curr_ssim =get_ssim_at_quality(photo, curr_quality)        ssim_ratio =curr_ssim /normalized_ssim        ifssim_ratio >=ssim_goal:            # continue to check whether a lower quality level also exceeds the goal            selected_quality =curr_quality            selected_ssim =curr_ssim            hi =curr_quality        else:            lo =curr_quality    ifselected_quality:        returnselected_quality, selected_ssim    else:        default_ssim =get_ssim_at_quality(photo, hi)        returnhi, default_ssim | 
然后在下面的代码中引用计算动态质量的方法:
| 1 2 3 4 5 6 | ...ifim.format=='JPEG':    save_args['quality'],value=dynamic_quality.jpeg_dynamic_quality(im)    save_args['optimize']=True    save_args['progressive']=True... | 
Squoosh 是谷歌发布的一款开源的图片在线压缩服务(伪),虽然需要用浏览器打开,但其实是一个整合了许多命令行工具的前端界面,调用的是本地的计算资源,所以只要打开过Squoosh一次,之后都会秒开,并且离线使用。不过最大的缺点就是不可以批量处理,如果我们要处理大量的图片资源,一张张地进行压缩处理将会消耗大量的人力成本和时间成本,这明显是不能接受的。我们要解决的问题就是写一个脚本来模拟浏览器的操作,使我们的双手得到解放。
这是 Squoosh 的主界面,Select an Image 其实是一个输入框,那我们直接用 Selenium 把本地图片的路径输入进去就行了:

输入图片路径之后就会默认压缩成 75% 质量的 MozJPEG,我觉得无论是压缩比和质量都很不错,所以就没有改,等待页面加载完成之后就直接下载:

我们可以认为出现 "..% smaller" 就算是压缩完成,这时候直接点击右边的下载按钮即可。
代码:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | fromselenium importwebdriverfromselenium.webdriver.common.by importByfromselenium.webdriver.support.wait importWebDriverWaitfromselenium.webdriver.support importexpected_conditions as ECfromselenium.webdriver.support.ui importSelectimportosimportredriver =webdriver.Chrome('C:/Users/admin/AppData/Local/Google/Chrome/Application/chromedriver.exe')# 列出目录下所有的图片,存在 images 这个列表中images =os.listdir('C:/Users/admin/Pictures/Saved Pictures')# 处理所有图片fori inrange(len(images)):    # 构建图片路径    path ='C:/Users/admin/Pictures/Saved Pictures/'+images[i]    # 尝试处理所有图片    try:        # 打开 Squoosh        driver.get('https://squoosh.app')        # 找到输入框        input_box =driver.find_element_by_xpath('.//input[@class="_2zg9i"]')        # 输入图片路径        input_box.send_keys(path)        #设置图片格式        select1 =Select(driver.find_elements_by_css_selector('select')[-1])        ifre.match('.*.png',images[i]):            select1.select_by_value("png")        ifre.match('.*.jpg',images[i]):            select1.select_by_value("mozjpeg")        # 等待出现 'smaller'字样,10秒不出现则视为处理失败        locator =(By.XPATH, './/span[@class="_1eNmr _1U8bE"][last()]')        WebDriverWait(driver, 25).until(EC.text_to_be_present_in_element(locator, 'smaller'))        # 找到下载按钮        button =driver.find_elements_by_xpath('.//a[@title="Download"]')[-1]        # 点击下载按钮        button.click()    # 输出处理失败的图片路径    except:        print('*'*30)        print('Error: '+path +' failed!')        print('*'*30)        continue | 
到此这篇关于如何使用python对图片进行批量压缩的文章就介绍到这了,更多相关python图片批量压缩内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!