python图片压缩与打包

等比例压缩图片。图片的宽或高有一条超过标准长度(宽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()

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值