等比例压缩图片。图片的宽或高有一条超过标准长度(宽800,高600)时,对图片进行等比例压缩,然后将压缩后的图片保存在本地。
from PIL import Image
def myOrigin(filename, standard_width=800, standard_height=600):
image = Image.open(filename)
width, height = image.size
if width <= standard_width and height <= standard_height:
print(filename, 'is OK.')
return
if width / standard_width * standard_height > height:
cur_height = height / (width / standard_width)
cur_width = standard_width
else:
cur_width = width / (height / standard_height)
cur_height = standard_height
new_im = image.resize((int(cur_width), int(cur_height)), Image.ANTIALIAS)
new_im.save("origin.jpg")
new_im.close()
图片复制。复制后保存到本地,复制后生成的图片的分辨率跟原图的分辨率一致,但是两个图片文件的大小不一致,不知道python具体做了什么。
def myCopy(filename):
image = Image.open(filename)
im = image.copy()
print("type = %s" % type(image))
print("type = %s" % type(im))
im.save("myCopy.jpg")
按自己设置的宽高生成一张图片。
def myResize(filename, width, height):
image = Image.open(filename)
image_resize = image.resize((width, height), Image.ANTIALIAS)
image_resize.save("C:\\Users\\AdminWin10\\" + 'resize-' + filename)
image_resize.close()
文件打包。函数write()的第一个参数为要打包的文件的路径,第二个参数为在压缩包里这个打包的文件的名字。
def myZip():
zip_file = "C:\\Users\\AdminWin10\\Desktop\\image\\file.zip"
zpf = zipfile.ZipFile(zip_file, "w")
location_file = "C:\\Users\\AdminWin10\\Desktop\\image\\3.jpg"
file_name = "my3.jpg"
thumb_full_file = "C:\\Users\\AdminWin10\\Desktop\\image\\4.jpg"
thumb_name = "my4.jpg"
zpf.write(location_file, file_name)
zpf.write(thumb_full_file, thumb_name)
zpf.close()