智能压缩图片的python代码

咱以前主要用c++,java,js,这几年觉得python和go比之前的语言用起来更方便,像是处理图片呀,这样的工作,用python确实很省事,要是做数学计算,求解微分方程组,或者是在工作中做个微服务,用go是相当强大,打算以后以这两个语言为主了

这里分享一段智能压缩图片的代码,如果是gif文件,无论后缀名是否正确,都能自动识别,不需要压缩,jpg类型的文件如果比较大,就进行压缩,如果是png/bmp就总是压缩

# coding=utf-8
#自动压缩非gif的图片
#image_resizer.py
import os,sys,time,re,shutil,math
from PIL import Image

exp=re.compile(r'.+\.(jpe?g|png|gif|bmp)$',re.I)
jpgexp=re.compile(r'.+\.(jpe?g)$',re.I)
if not os.path.exists('x'):
	os.makedirs('x')
for fname in os.listdir('.'):
	if os.path.isdir(fname) or not exp.match( fname.lower()):#.endswith
		continue
	print(fname)
	try:
		img_type=open(fname,'rb').read(3).decode()		
		if img_type =="GIF" and not fname.endswith("gif"):
			#shutil.move(fname,fname+'.gif')
			os.rename(fname,fname+'.gif')
			continue
	except Exception as e:
		print(e)
		pass
	if fname.endswith(".gif"):
		continue
	if(os.stat(fname).st_size	<3e5):	#300kb
		continue
	img=Image.open(fname)	
	(w,h)=img.size 
	if jpgexp.match(fname) and not w*h>5e6 :#(w>2e3 and h>2e3):
		continue
	print(fname,'doing')
	x=min(5e6/(w*h),1	)
	data=img.convert('RGB')	.resize((int(w*x),int(h*x)))
	data.save(fname+'_resized_pic.jpg')
	#os.remove(fname)
	shutil.move(fname,'x/'+fname)
	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值