百木园-与人分享,
就是让自己快乐。

Python图片压缩处理

前言

不知道有没有人跟我有一样的烦恼,有时候图片太大了占内存很烦,本来手机内存也就那么点,放一个图片稍微大一点的,都不

能放一个成百上千张,这不是很烦嘛。于是,这又让我来灵感了,既然图片给了我难题,那么我就来接受这样的挑战。所以,我

决定用python来试试可不可以压缩图片,不是不知道,一试就成功了,那么好的东西怎么能一个人独享呢,当然要分享出来给大

家呀~~~

python学习交流Q群:906715085###
dynamic_quality.py
import PIL.Image
from math import log
from SSIM_PIL import compare_ssim
# pip install SSIM-PIL
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

def get_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))    
return ssim_score

def _ssim_iteration_count(lo, hi):    
\"\"\"
Return the depth of the binary search tree for this range
\"\"\"    
if lo >= hi:        
return 0    
else:        
return int(log(hi - lo, 2)) + 1

def jpeg_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.9 #the original value is 0.95    
hi = 35 #the original value is 85    
lo = 30 #the original value is 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((200, 200))
# 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, 10)    
selected_quality = selected_ssim = None
# loop bisection. ssim function increases monotonically so this will converge    for i in range(_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
if ssim_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
if selected_quality:        
return selected_quality, selected_ssim    
else:        
default_ssim = get_ssim_at_quality(photo, hi)        
return hi, default_ssim

 

test.py

from PIL 
import Image
from dynamic_quality import *
def compress(filename,originpath,targetpath):    
name = filename.rstrip(\'.png\').rstrip(\'.jpg\')    
im = Image.open(originpath+filename)    
# print(im.format,im.size,im.mode)    
im = im.convert(\'RGB\')    
im.format = \"JPEG\"    
new_photo = im.copy()    
new_photo.thumbnail(im.size,resample=Image.ANTIALIAS)    
save_args = {\'format\':im.format}    
# print(save_args)    
# if im.format==\'JPEG\':    
# save_args[\'quality\']=20    save_args[\'quality\'],value=jpeg_dynamic_quality(im)    save_args[\'optimize\']=True    
save_args[\'progressive=True\']=True    
# print(\"JPEG Quality Changed\")    
# elif im.format==\'PNG\':    
#     save_args[\'format\']=\'JPEG\'    
#     save_args[\'quality\']=5    
#     print(\"PNG Quality Changed\")    new_photo.save(targetpath+name+\".jpg\",**save_args)
if __name__ == \'__main__\':   
 import os   
 originpath = \"D:\\\\images\\\\img\\\\\"    
 # 需要压缩图片路径    targetpath = \"D:\\\\images\\\\dangdang_image\\\\\"   
 # 压缩完图片路径    for root, dirs, files in os.walk(originpath):        
 for file in files:            
 compress(file,originpath,targetpath)

 

最后

今天教大家的图片压缩到这里就结束了,喜欢的小伙伴记得点赞收藏。你不支持我,怎么能第一时间找到我,关于这篇文章有不

懂的地方可以评论留言哟!!我看到都会第一时间回复的,这一篇到这里就有翻过去了,下一章见啦~~
在这里插入图片描述


来源:https://www.cnblogs.com/1234567FENG/p/16386867.html
本站部分图文来源于网络,如有侵权请联系删除。

未经允许不得转载:百木园 » Python图片压缩处理

相关推荐

  • 暂无文章