python实现图片的无损压缩
时间: 2023-06-29 11:04:23 浏览: 251
Python中有很多库可以实现图片的无损压缩,常用的有Pillow和OpenCV。
以下是使用Pillow库进行无损压缩的示例代码:
```python
from PIL import Image
# 打开原始图片
img = Image.open("original_image.jpg")
# 保存压缩后的图片,quality参数为压缩质量,范围为0-100,数值越高质量越好
img.save("compressed_image.jpg", quality=80)
```
以下是使用OpenCV库进行无损压缩的示例代码:
```python
import cv2
# 读取原始图片
img = cv2.imread("original_image.jpg", cv2.IMREAD_UNCHANGED)
# 保存压缩后的图片,参数为压缩质量,范围为0-100,数值越高质量越好
cv2.imwrite("compressed_image.jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 80])
```
无论使用哪个库进行压缩,都需要注意压缩后的图片文件大小和压缩质量的平衡,一般可以通过不断调整quality参数来寻找最佳的平衡点。
相关问题
python无损压缩图片
你可以使用Pillow库来对图片进行无损压缩。以下是一个简单的例子:
```python
from PIL import Image
# 打开图片
image = Image.open("example.jpg")
# 无损压缩并保存
image.save("example_compressed.jpg", optimize=True, quality=95)
```
在上面的例子中,我们打开了一张名为"example.jpg"的图片,并使用`optimize=True`和`quality=95`参数进行了无损压缩,最后将压缩后的图片保存为"example_compressed.jpg"。你可以根据自己的需求调整`quality`参数来控制压缩质量,范围为0-100。越高的值意味着更高的质量和更大的文件大小。
python 实现图像的无损压缩代码
图像的无损压缩可以使用PNG格式实现,PNG使用了无损压缩算法,能够保证图像质量不受影响,下面是一个Python实现的示例代码:
```python
from PIL import Image
def compress_image(infile, outfile):
try:
with Image.open(infile) as im:
# 使用PNG格式保存图片
im.save(outfile, "PNG")
print("图片压缩成功!")
except Exception as e:
print("图片压缩失败!", e)
if __name__ == '__main__':
infile = "test.jpg"
outfile = "test_compressed.png"
compress_image(infile, outfile)
```
这个例子使用了Pillow库,首先打开要压缩的图片,然后使用PNG格式保存图片,保存后的图片就是经过无损压缩的。你可以将`test.jpg`替换成你想要压缩的图片路径,将`test_compressed.png`替换成你想要保存的压缩后的图片路径。