Axios 是一个基于 Promise 的 HTTP 客户端,用于浏览器和 node.js。它可以帮助你轻松地从服务器获取数据,包括图像。
Sharp 是一个高性能的 Node.js 图像处理库,可以用来调整图像大小、裁剪、旋转等。
以下是一个使用 Axios 下载图像并使用 Sharp 调整图像大小的示例代码:
const axios = require('axios');
const sharp = require('sharp');
const fs = require('fs');
async function downloadAndResizeImage(url, outputPath, width, height) {
try {
// 使用 Axios 下载图像
const response = await axios({
method: 'GET',
url: url,
responseType: 'stream',
});
// 使用 Sharp 调整图像大小并保存
const transformer = sharp()
.resize(width, height)
.toBuffer();
const writer = fs.createWriteStream(outputPath);
response.data.pipe(transformer).pipe(writer);
return new Promise((resolve, reject) => {
writer.on('finish', resolve);
writer.on('error', reject);
});
} catch (error) {
console.error('Error:', error);
}
}
// 示例调用
downloadAndResizeImage(
'https://example.com/image.jpg',
'output/resized-image.jpg',
300,
200
).then(() => {
console.log('Image downloaded and resized successfully!');
}).catch((error) => {
console.error('Failed to download and resize image:', error);
});
通过以上方法,你可以有效地使用 Axios 下载图像并使用 Sharp 调整图像大小。
领取专属 10元无门槛券
手把手带您无忧上云