用Python快速批量压缩图片© getcodify.com

用Python快速批量压缩图片

用Python快速批量压缩图片

## Structure ### 1 Arguments
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-i','-I','--input') #输入文件
parser.add_argument('-o','-O','--output',default = "OUT") #输出文件
parser.add_argument('-r','-R','--ratio', type = int,default = 2) #resize ratio
parser.add_argument('-w','-W','--width',default = "NA") #resize by width
parser.add_argument('-t','-T','--height',default = "NA") #resize by Height

##获取参数
args = parser.parse_args()
INPUT = args.input
OUTPUT = args.output
R_img = args.ratio
W_img = args.width
H_img = args.height

2 File/Director Judgement

import os

def FD_judge(path):
result = ""
if "*" in path:
result = "Files"
elif os.path.isdir(path):
result = "Directory"
elif os.path.isfile(path):
result = "File"
else:
result = "path is incorrect"
return result


print(FD_judge(INPUT))
Typ_in = FD_judge(INPUT)

3 Resize Determine

import PIL.Image as Image

def Calc_WH(w,h,W_img,H_img,R_img):
if W_img != "NA" and H_img == "NA": #Resize by Width
print('Resize by Width')
R = w/ int(W_img)
w=int(w/R)
h=int(h/R)
elif H_img != "NA" and W_img == "NA": #Resize by Height
print("Resize by Height")
R = h/ int(H_img)
w=int(w/R)
h=int(h/R)
elif H_img != "NA" and W_img != "NA": #Resize by Width and Height
print('Resize by Width and Height')
w=int(W_img)
h=int(H_img)
else:
print("Resize by ratio, R="+str(R_img))
w=int(w/R_img)
h=int(h/R_img)
return w,h

4 Resize function

def Resize(path,W_img,H_img,R_img):
Img=Image.open(path)
w,h=Img.size
w,h=Calc_WH(w,h,W_img,H_img,R_img)
Img_out=Img.resize((w,h),Image.ANTIALIAS)
return Img_out


5 logic

if Typ_in=="File" and OUTPUT == "OUT":
OUTPUT = "Re_" + INPUT
elif Typ_in=="File" and OUTPUT != "OUT":
OUTPUT = OUTPUT
else:
if not os.path.exists(OUTPUT):
os.makedirs(OUTPUT)
OUTPUT = OUTPUT +"/"

test result:

Ns99MR.png

Result

Single file

Reading img infor With package “imagemagick”. If you doesn’t have this lib, for debian, please execute:
**sudo apt install ****imagemagick

Running with default argument

../test.py -i 1.png
##Outfile: Re_1.png

identify 1.png Re_1.png

## 1.png PNG 2666x1827 2666x1827+0+0 8-bit sRGB 295921B 0.000u 0:00.010
## Re_1.png PNG 1333x913 1333x913+0+0 8-bit sRGB 203679B 0.000u 0:00.000

../test.py -i 1.png -o my.png
##Outfile: my.png

identify 1.png my.png
##1.png PNG 2666x1827 2666x1827+0+0 8-bit sRGB 295921B 0.000u 0:00.000
##my.png PNG 1333x913 1333x913+0+0 8-bit sRGB 203679B 0.000u 0:00.000

Resize by width

../test.py -i 1.png -w 300

identify 1.png Re_1.png
##1.png PNG 2666x1827 2666x1827+0+0 8-bit sRGB 295921B 0.000u 0:00.000
##Re_1.png PNG 300x205 300x205+0+0 8-bit sRGB 27338B 0.000u 0:00.000

Resize by Height

../test.py -i 1.png -t 300

identify 1.png Re_1.png
##1.png PNG 2666x1827 2666x1827+0+0 8-bit sRGB 295921B 0.000u 0:00.000
##Re_1.png PNG 437x300 437x300+0+0 8-bit sRGB 44276B 0.000u 0:00.000

Resize by Ratio

../test.py -i 1.png -r 10

identify 1.png Re_1.png
##1.png PNG 2666x1827 2666x1827+0+0 8-bit sRGB 295921B 0.000u 0:00.000
##Re_1.png PNG 266x182 266x182+0+0 8-bit sRGB 23398B 0.000u 0:00.000

Resize by Height and Width

../test.py -i 1.png  -t 200 -w 10

##1.png PNG 2666x1827 2666x1827+0+0 8-bit sRGB 295921B 0.000u 0:00.000
##Re_1.png PNG 10x200 10x200+0+0 8-bit sRGB 2186B 0.000u 0:00.000

Resize Multiple files

Resize multiple file

../test.py -i "*.png"

All result will be printed to “OUT” director.

../test.py -i OUT -o test -w 100

reading all pictures from OUT directory, and all result where out put to test file

update

2020/2/9
Adding arguments

parser.add_argument('-inf','-INF','--infor',default = "None")    #resize by Height

INFORM = args.infor

Def functions:

def Resize_loop():
if Typ_in == "File":
Result = Resize(INPUT,W_img,H_img,R_img)
Result.save(OUTPUT, quality=Quality)
elif Typ_in == "Files":
List = os.popen("ls "+INPUT).read().split('\n')[:-1]
for i in List:
Result = Resize(i,W_img,H_img,R_img)
Result.save(OUTPUT + i.split('/')[-1], quality=Quality)
elif Typ_in == "Directory":
List = os.popen("ls "+INPUT+"/*").read().split('\n')[:-1]
for i in List:
Result = Resize(i,W_img,H_img,R_img)
Result.save(OUTPUT+i.split('/')[-1], quality=Quality)

def IMG_inf(INPUT):
Space = size_format(getsize(INPUT))
Img = Image.open(INPUT)
Name = Img.filename
Format = Img.format_description
Mode = Img.mode

try:
Bit = "bit:" + str(Img.bits)
except:
Bit = "bit:NA"
try:
Dpi = "dpi:" + 'x'.join([str(x) for x in Img.info['dpi']])
except:
Dpi = "dpi: NA"
Size = "size:" + 'x'.join([str(x) for x in Img.size])
Result = Name +"\t"+" ".join([Space, Size, Dpi, Format,Mode,Bit])
return Result

Logic:

if INFORM == "None": # Resize
Typ_in = FD_judge(INPUT)
print(Typ_in)
OUTPUT = OUT_fig(INPUT,OUTPUT)
Resize_loop()
else: # img information
Typ_in = FD_judge(INPUT)
if Typ_in == "File":
print(IMG_inf(INPUT))
elif Typ_in == "Files":
#List = os.popen("ls "+INPUT).read().split('\n')[:-1]
List = os.popen("ls "+INPUT).read().split('\n\n')[0].split('\n')[:-1]
for i in List:
print(IMG_inf(i))
elif Typ_in == "Directory":
List = os.popen("ls "+INPUT+"/*").read().split('\n\n')[0].split('\n')[:-1]
for i in List:
print(IMG_inf(i))

Usage:

Imresize.py -i "*" -inf 1

output:
NspOaT.png

Details:

Name Size Width&height DPI format mode Bit
bash.jpg 16.8KB size:800x450 dpi: NA JPEG (ISO 10918) RGB bit:8
Author

Karobben

Posted on

2020-10-25

Updated on

2024-01-11

Licensed under

Comments