Python图片压缩处理

yizhihongxing

前言

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

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

决定用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)

 

最后

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

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

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python图片压缩处理 - Python技术站

(0)
上一篇 2023年4月2日
下一篇 2023年4月2日

相关文章

  • Python+AI给老照片上色

    前言 哈喽,大家好。有没有谁跟我一样喜欢老照片的朋友,老照片总是让人感觉有一种情怀,可能这就是怀念吧。有一次无意中看到 了很久很久以前的照片都是黑白的,当时很想给照片添加点颜色,但是不知道怎么搞。今天,我终于发现了怎么去解决这个问 题,想了想,我决定得把这个分享给大家…   今天我们分享用NoGAN的图像增强技术给老照片着色。效果如下: 原图 上色后 NoG…

    Python开发 2023年4月2日
    00
  • 如何使用 Python 实现彩票自由(大乐透)

    前言 有没有小伙伴喜欢买股票的,我自己是不会玩的,不是不想玩,是真的挽不回,只能玩比较简单一点的刮刮乐。虽然我不会买股 票,但是用python分析股票还是简简单单的… 全国有很多彩民,其中购买最多的彩种分别是体彩大乐透和福彩双色球;虽然中大奖的概率极低,但是彩民纷至沓来,一方面抱 着一份中奖的希望,另一方面想为公益事业贡献自己的一份薄力 本篇文章将介绍 Py…

    Python开发 2023年4月2日
    00
  • 用Python制作销售数据可视化看板,展示分析一步到位

    前言 在数据时代,销售数据分析的重要性已无需赘言。 只有对销售数据的准确分析我们才有可能找准数据变动(增长或下滑)的原因。 然后解决问题、发现新的增长点才会成为可能! 今天就给大家介绍一个用Python制作销售数据大屏的方法。 主要使用Python的Streamlit库、Plotly库、Pandas库进行搭建。 其中Pandas处理数据,Plotly制作可视…

    Python开发 2023年4月2日
    00
  • 上班用Python采集热搜榜,堪称摸鱼神器

    前言 不知道大家在工作无聊时,有没有一种冲动:总想掏出手机,看看微博热搜在讨论什么有趣的话题,但又不方便直接打开微博浏 览,今天就和大家分享一个有趣的小爬虫,定时采集微博热搜榜&热评,下面让我们来看看具体的实现方法。 页面分析 热搜页 热榜首页:https://s.weibo.com/top/summary?cate=realtimehot   热榜…

    Python开发 2023年4月2日
    00
  • Python迭代对象、迭代器与生成器

    关系图 1.可迭代对象(iterable) 一个具备__iter__()方法的对象,就是一个可迭代对象,但是要成为一个正常的可迭代对象那么就需要遵循协议。这个方法必须返 回一个迭代器。 可迭代协议: 含__iter__()方法。且可迭代对象中的__iter__()方法返回的是一个对应的迭代器。(如list对应的迭代器就是 list_iterator) 以下代…

    Python开发 2023年4月2日
    00
  • 5个节约生命的Python小技巧

    前言 Python是一种强大且易上手的语言,语法简洁优雅,不像Java那么繁琐废话,并且有一些特殊的函数或语法可以让代码变得更加 简短精悍。根据我的经验,下面介绍常用的5个Python小技巧: •字符串操作 •列表推导 •lambda 及 map() 函数 •if、elif和else单行表达式 •zip()函数 1.字符串操作 ###python#### p…

    Python开发 2023年4月2日
    00
  • 教你用python爬取美女照片,未成年不能学

    又到每天Python小技巧分享的时候了,今天给大家分享的是怎么样去爬取清纯小姐姐照片(没有人会拒绝美女吧,小声说),这篇文章好像有点刺激,未成年的小伙伴就不要进来了。快来看看这些清纯的小姐姐的容颜,话不多说,上教程。 先来看看效果图 不好意思,图片有点辣眼睛,被拦截了,还没有还给我….. import re import requests import …

    Python开发 2023年4月2日
    00
  • 5 行 Python 代码就能让你的电脑永不息屏,这波逼必须装到…

    前言 首先,必须得承认Python 是一门优雅、易入门的编程语言。往往用很少量的代码,就能帮助你完成一件很漂亮的事儿。这也是我 使用python多年的心里话。比起那些难、麻烦的的软件,python圆了我的程序梦. 最开始学习 Python,不需要太过复杂。只要玩儿的开心就行,慢慢培养兴趣,等你上手后,你会学习的更有信心。 今天我们就来玩玩儿,5 行代码能做啥…

    Python开发 2023年4月2日
    00
合作推广
合作推广
分享本页
返回顶部