python压缩图片

直接上代码了

#coding = utf-8
import cv2
import os
import math

def get_doc_size(path):
    try:
        size = os.path.getsize(path)
        return get_mb_size(size)
    except Exception as err:
        print(err)

def get_mb_size(bytes):
    bytes = float(bytes)
    mb = bytes / 1024 / 1024
    return mb


def delete_file(path):
    if file_exist(path):
        os.remove(path)
    else:
        print('no such file:%s' % path)


def file_exist(path):
    return os.path.exists(path)


def resize_rate(path, resize_path, fx, fy):
    image = read_image(path)
    im_resize = cv2.resize(image, None, fx=fx, fy=fy)
    delete_file(resize_path)
    save_image(resize_path, im_resize)


def save_image(path, image):
    cv2.imwrite(path, image)


def read_image(path):
    return cv2.imread(path)


path = "C:/Users/zhengyu/Desktop/test.jpg" #被压缩图片的绝对路径
resize_path = "C:/Users/zhengyu/Desktop/test_re.jpg"  #压缩图片的存储位置,记住给压缩图片命名,3.jpg就是压缩后图片的名字
size = get_doc_size(path)
print(round(size,2),"MB") #原始的size
delete_file(resize_path)
filesize = 0.8   #压缩比例

while size > filesize:
    rate = math.ceil((size / filesize) * 10) / 10 + 0.1
    rate = math.sqrt(rate)

    rate = 1.0 / rate
    if file_exist(resize_path):
        resize_rate(resize_path, resize_path, rate, rate)
    else:
        resize_rate(path, resize_path, rate, rate)
    size = get_doc_size(resize_path)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值