egg+next项目上传图片并压缩实现方案

233 阅读2分钟

概述

由于没有购买CDN功能,且服务器资源有限,上传原图加载速度较慢,所以想压缩后再存到服务器中。

选择现有插件

sharp

sharp 模块的参数可以传递文件路径或文件流,这取决于你想要处理的图片数据来源。

1.传递文件流: 如果你的图片数据是通过文件流获取的(例如在 Egg.js 中使用 ctx.getFileStream() 获取上传的图片流),可以将文件流作为 sharp 的参数。例如:

const sharp = require('sharp');
const fs = require('fs');
const stream = await ctx.getFileStream();
await processImage(stream);
async function processImage(stream) {
  const outputFilePath = 'output.jpg'; // 替换为你希望输出的图片路径

  sharp(stream)
    .resize(800)
    .toFile(outputFilePath, (err, info) => {
      if (err) {
        console.error('处理图片出错:', err);
      } else {
        console.log('图片处理完成!', info);
      }
    });
}

如果你已经有了一个现有的图片文件,并希望对它进行处理,可以直接将文件路径作为 sharp 的参数。

const sharp = require('sharp'); 
const inputFilePath = 'path/to/your/input.jpg';// 替换为你的图片路径
const outputFilePath = 'path/to/your/output.jpg'; // 替换为你希望输出的图片路径 
sharp(inputFilePath).resize(800) .toFile(outputFilePath, (err, info) => { 
    if (err) { 
    console.error('处理图片出错:', err);
    } else { 
    console.log('图片处理完成!', info); 
    } 
});

无论是传递文件路径还是文件流,sharp 都会根据传入的数据进行图片处理。使用哪种方式取决于你的具体需求和图片数据的来源

问题:由于我的服务器时centos7,sharp的兼容性有问题,需要安装libvips到系统内,不然安装sharp会出现问题

npm ERR! command sh -c -- (node install/libvips && node install/dll-copy && prebuild-install) || (node install/can-compile && node-gyp rebuild && node install/dll-copy)

尝试在服务器系统安装libvips sudo yum search libvips 警告

已加载插件:fastestmirror Loading mirror speeds from cached hostfile 
警告:没有匹配 libvips 的软件包 No matches found

尝试下载源码安装

  1. 下载 libvips 源码包: 访问 libvips 的官方网站(libvips.github.io/libvips/),找… libvips 的源码包。
  2. 解压源码包: 使用 tar 命令解压下载的源码包:
bashCopy code
tar xf libvips-x.x.x.tar.gz
cd libvips-x.x.x
  1. 配置和编译: 运行以下命令配置和编译 libvips:
bashCopy code
./configure
make
sudo make install

发现即使安装了libvips依然会有问题,所以尝试换另一个库

Jimp

Jimp 是一个纯 JavaScript 编写的图像处理库,可以在浏览器和 Node.js 中使用。它提供了丰富的图像处理功能,如调整大小、裁剪、滤镜、文字添加等。 Jimp 也支持从流中读取图像数据,并可以将压缩后的图像数据写入到输出流中。

示例代码:

Jimp:


const Jimp = require('jimp');

// 假设你已经有一个 Buffer 包含图像数据
const inputBuffer = ...;

// 从 Buffer 创建 Jimp 图像对象
Jimp.read(inputBuffer)
  .then(image => {
    // 压缩图像
    return image.resize(200, 100).quality(80).getBufferAsync(Jimp.MIME_JPEG);
  })
  .then(outputBuffer => {
    // 在这里可以对输出的 Buffer 做进一步操作或保存到文件
  })
  .catch(err => {
    // 处理错误
  });