如何将图像缩小到1MB? [英] How to scale down an image to 1MB?

查看:59
本文介绍了如何将图像缩小到1MB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种基于python的解决方案,如果该图像大于1MB,则可以缩小图像(img< = 1MB),如果该图像已经小于1MB,则可以保留原始图像.

I am looking for a python based solution where I can scale down an image (img<=1MB) if it is bigger than 1MB or keep the original if it's already under 1MB.

例如

  • img1;大小= 1.2MB->缩小到1MB
  • img2;大小= 0.9MB->保持原样.
  • img2;大小= 1.0MB->保持原样.

到现在为止,我已经介绍了按给定比例缩小图像的方法.

Till now I have come to this which scales down an image with a given percentage.

import cv2

img = cv2.imread('img.jpg')
scale_percent = 0.4

new_width = int(img.shape[1]*scale_percent)
new_height = int(img.shape[0]*scale_percent)
dimension = (new_width, new_height)

resized = cv2.resize(img, dimension, interpolation = cv2.INTER_LINEAR)

print(resized.shape)
cv2.imwrite('img_resized.jpg', resized)

推荐答案

通常,图像的大小受以下因素影响:

In general the size of an image is affected by:

  • 宽度 w 和高度 h ;
  • 频道数 n ;
  • 数据类型 t ;
  • 的大小
  • 数据压缩.

如果没有压缩(例如.bmp图像中的 ),则图像的 S0 大小(以字节为单位)由以下公式给出:

If there is no compression (e.g., in .bmp images) the size S0 (in bytes) of the image is given by:

S0 = w * h * n * t

考虑到缩放变换只能影响变量 w h ,即尺寸按尺寸缩放的图像的尺寸 S1 因素 s

Considered that a scaling transform can only affect the variables w and h, the size S1 of an image whose dimensions are scaled by a factor s is

S1 = (s*w) * (s*h) * n * t

由于 S1 =(s * s)* S0 ,因此将大小 S1 限制为小于或等于1 MB,因此 s 应该选择为(s * s)* S0 <= 1 ,因此 s< = sqrt(1/S0).为了不放大已经小于1MB的图像,应该对公式进行如下修改:

Since S1 = (s*s) * S0, to constrain the size S1 to be less or equal to 1 MB, s should be chosen so that (s*s) * S0 <= 1, hence s <= sqrt(1/S0). In order not to upscale the images that already have a size smaller than 1MB, the formula should me modified as follows:

s = max{sqrt(1/S0), 1}

对于压缩图像,大小的显式确定要复杂得多,但是确定比例因子 s 的规则应该是一个很好的近似值.

For compressed images the explicit determination of the size is more complicated, but the rule for the determination the scale factor s should be a good approximation.

这篇关于如何将图像缩小到1MB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆