在Linux系统中,可以使用libwebp
库来压缩图片
-
首先确保已经安装了
libwebp
库。如果尚未安装,请使用以下命令安装:对于Debian/Ubuntu系统:
sudo apt-get install libwebp-dev
对于CentOS/RHEL系统:
sudo yum install libwebp-devel
对于Fedora系统:
sudo dnf install libwebp-devel
-
使用
libwebp
的cwebp
命令行工具压缩图片。cwebp
可以将JPEG、PNG等格式的图片转换为WebP格式,并具有压缩选项。以下是一些常用的cwebp
选项:-q
:设置输出图片的质量,范围为0(最差质量,最小文件大小)到100(最佳质量,最大文件大小)。-o
:指定输出文件的名称和路径。-s
:启用缩放功能,可以减小图片尺寸。-alpha
:保留图片的透明度信息。
示例:将名为
input.jpg
的图片压缩为WebP格式,质量为80,输出文件名为output.webp
:cwebp -q 80 input.jpg -o output.webp
-
如果需要编写程序来批量压缩图片,可以使用
libwebp
的API。以下是一个使用C语言的简单示例:#include
#include int main() { int width = 800; int height = 600; uint8_t *image_data = https://www.yisu.com/ask/malloc(width * height * 4);> 0) { FILE *output_file = fopen("output.webp", "wb"); fwrite(encoded_data, 1, encoded_size, output_file); fclose(output_file); free(encoded_data); printf("Image compressed successfully!\n"); } else { printf("Error compressing image!\n"); } free(image_data); return 0; } 编译并运行此程序:
gcc -o compress_image compress_image.c -lwebp ./compress_image
这将读取名为
input.jpg
的图片,将其压缩为WebP格式,质量为80,并将输出文件保存为output.webp
。