在 Node.js 中处理图像:Sharp 库

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

用于在 Node.js 中处理图像的 Sharp 库



在现代 Web 开发中,服务器端图像处理是一项至关重要的任务。Node.js 凭借其事件驱动架构,能够很好地胜任这项任务。在众多图像处理库中,Sharp 占据着特殊地位——它是一个高性能的开源模块,用 C++ 编写,并使用 libvips 库。



什么是 Sharp?



Sharp 是一个用于快速图像处理的 Node.js 模块。它支持 JPEG、PNG、WebP、AVIF、TIFF 和 GIF 格式。主要功能包括调整大小、裁剪、旋转、色彩校正、添加水印以及格式之间的转换。由于使用了 libvips,Sharp 的运行速度比同类库(例如 ImageMagick 或 GraphicsMagick)快 4-5 倍。



安装



通过 npm 进行安装。请确保系统中已安装 C++ 编译器(gcc 或 clang)和 libvips(在某些操作系统上需要预先安装)。



npm install sharp


安装后,您可以将模块导入到您的项目中:



const sharp = require('sharp');


基本图像操作



1. 调整大小 (resize)



最常见的任务是缩小或放大图像。Sharp 允许您指定宽度、高度或同时指定两者。如果只指定一个参数,另一个参数将按比例计算。



const sharp = require('sharp');

async function resizeImage() { try { await sharp('input.jpg') .resize(300, 200) // 宽度 300px,高度 200px .toFile('output-resized.jpg'); console.log('图像已调整大小'); } catch (error) { console.error('错误:', error); }}

resizeImage();


要保留比例,请使用 fit:



const sharp = require('sharp');

async function resizeWithFit() { await sharp('input.jpg') .resize({ width: 300, height: 200, fit: 'inside' // 'cover', 'contain', 'fill', 'inside', 'outside' }) .toFile('output-fit.jpg');}

resizeWithFit();


2. 裁剪 (crop)



裁剪允许您移除图像中不需要的部分。Sharp 支持按指定坐标或按策略(例如居中裁剪)进行裁剪。



const sharp = require('sharp');

async function cropImage() { await sharp('input.jpg') .extract({ left: 100, top: 50, width: 400, height: 300 }) .toFile('output-cropped.jpg');}

cropImage();


也可以使用带有 crop 选项的 resize:



const sharp = require('sharp');

async function cropWithResize() { await sharp('input.jpg') .resize(200, 200, { fit: 'cover', position: 'centre' }) .toFile('output-cover.jpg');}

cropWithResize();


3. 格式转换



Sharp 允许您轻松地将图像从一种格式转换为另一种格式。只需在输出文件中指定扩展名,或使用 .toFormat() 方法。



const sharp = require('sharp');

async function convertToWebP() { await sharp('input.png') .toFormat('webp') .toFile('output.webp');}

async function convertToJpeg() { await sharp('input.webp') .jpeg({ quality: 80 }) .toFile('output.jpg');}

convertToWebP();convertToJpeg();


4. 处理元数据



您可以提取图像的元数据:尺寸、色彩空间、DPI、EXIF 数据等。



const sharp = require('sharp');

async function getMetadata() { const metadata = await sharp('input.jpg').metadata(); console.log('元数据:', metadata); // { format:

推荐