写个图片压缩。Python代码实现
时间: 2023-06-05 12:07:45 浏览: 59
好的,下面是 Python 代码实现:
```python
from PIL import Image
def compress_image(input_path, output_path, quality):
with Image.open(input_path) as img:
img.save(output_path, optimize=True, quality=quality)
```
其中,`input_path` 是原始图片的路径,`output_path` 是输出图片的路径,`quality` 是压缩质量,范围是 1-95。一般来说,30-60 左右的质量就可以得到比较好的压缩效果了。
相关问题
python图片压缩代码
当然,我可以帮你提供一个简单的Python图片压缩代码示例。你可以使用Pillow库来实现图片压缩。以下是一个基本的代码示例:
```python
from PIL import Image
def compress_image(input_image_path, output_image_path, max_size):
image = Image.open(input_image_path)
image.thumbnail((max_size, max_size))
image.save(output_image_path)
# 示例:将input.jpg压缩为output.jpg,最大尺寸为800x800像素
compress_image("input.jpg", "output.jpg", 800)
```
在上面的示例中,`compress_image`函数接受三个参数:输入图片路径、输出图片路径和最大尺寸(以像素为单位)。该函数会打开输入图片,按照给定的最大尺寸等比例压缩图片,并将压缩后的图片保存到输出路径。
你可以根据自己的需求修改`compress_image`函数的参数和调用方式。希望对你有所帮助!
用python写一个灰度图片压缩和解压缩的代码
可以的,以下是一个简单的灰度图片压缩和解压缩的代码示例:
压缩代码:
```python
import numpy as np
import cv2
def compress_image(img_path, compressed_path):
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
h, w = img.shape
img_flat = img.flatten()
img_diff = np.diff(img_flat)
compressed = np.concatenate(([img_flat[]], img_diff))
np.save(compressed_path, compressed)
return h, w
```
解压缩代码:
```python
import numpy as np
import cv2
def decompress_image(compressed_path, h, w, img_path):
compressed = np.load(compressed_path)
img_flat = np.cumsum(compressed)
img = img_flat.reshape((h, w)).astype(np.uint8)
cv2.imwrite(img_path, img)
```
以上代码使用了numpy和OpenCV库,可以实现对灰度图片的压缩和解压缩。