编程用的图片怎么压缩

时间:2025-01-26 16:25:47 网络游戏

使用Pillow库

Pillow是PIL库的升级版,功能更强大,可以方便地压缩图片。以下是一个使用Pillow库进行图片压缩的Python脚本示例:

```python

from PIL import Image

import os

def compress_image(infile, outfile, max_size=800):

img = Image.open(infile)

w, h = img.size

if max(w, h) > max_size:

if w > h:

new_w = max_size

new_h = int(h * max_size / w)

else:

new_h = max_size

new_w = int(w * max_size / h)

img = img.resize((new_w, new_h))

img.save(outfile, quality=65, optimize=True)

```

在这个示例中,`quality`参数取值范围是1-95,数值越小压缩率越高,但图片质量也会降低。65是一个不错的平衡点。

使用Windows自带的画图工具

这是一个简单快捷的方法,适合图片量不大的情况。打开图片后直接另存为所需的图片格式,会发现文件大小减小了很多,且质量损失不大。

使用TinyPNG工具

TinyPNG是一个在线压缩图片的网站,支持PNG和JPG格式的图片,可以同时上传20张图片,每张最大不能超过5M。这个工具压缩效果理想,尤其适合PNG格式的图片。

使用腾讯的智图

腾讯的智图也是一个在线压缩图片的网站,支持压缩PNG、JPG和WebP格式的图片。它还可以导出WebP格式的图片,效果测试下来还算可以。

使用GD库函数

在PHP中,可以使用GD库函数进行图片压缩。以下是一个使用GD库函数压缩图片的示例代码:

```php

<?php

function compress_image($source, $destination, $quality) {

$info = getimagesize($source);

if ($info['mime'] == 'image/jpeg') {

$image = imagecreatefromjpeg($source);

imagejpeg($image, $destination, $quality);

} elseif ($info['mime'] == 'image/gif') {

$image = imagecreatefromgif($source);

imagegif($image, $destination);

} elseif ($info['mime'] == 'image/png') {

$image = imagecreatefrompng($source);

imagepng($image, $destination, 9 - ($quality / 10));

}

imagedestroy($image);

}

$source = 'input.jpg';

$destination = 'output.jpg';

$quality = 75;

compress_image($source, $destination, $quality);

?>

```

在这个示例中,`quality`参数取值范围是0-100,数值越大压缩率越低,图片质量越高。75是一个常用的平衡点。

使用Thumbnailator库

Thumbnailator是一个用于处理图像的Java库,可以方便地进行图片压缩和缩放。以下是一个使用Thumbnailator进行图片压缩的Java示例代码:

```java

import net.coobird.thumbnailator.Thumbnails;

import java.io.File;

public class ImageCompressor {

public static void main(String[] args) throws IOException {

File input = new File("input.jpg");

File output = new File("output.jpg");

Thumbnails.of(input)

.scale(0.5)

.outputQuality(0.75)

.toFile(output);

}

}

```

在这个示例中,`outputQuality`参数取值范围是0.0-1.0,数值越大压缩率越低,图片质量越高。0.75是一个常用的平衡点。

这些方法各有优缺点,可以根据具体需求和场景选择合适的方法进行图片压缩。