咱以前主要用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)