【问题标题】:image resize on node.js在 node.js 上调整图像大小
【发布时间】:2021-08-15 14:47:05
【问题描述】:

我想在调整大小后保存图像,所以使用了清晰的包,但图像尺寸不小。添加 await sharp(uploadImage.name).resize(600, 600);保存文件夹后的行我错过了什么?

const path = require('path');
const fs = require('fs');
const AdminBro = require('admin-bro');
const sharp=require('sharp');

/** @type {AdminBro.After<AdminBro.ActionResponse>} */
const after = async (response, request, context) => {
  const { record, uploadImage } = context;

  if (record.isValid() && uploadImage) {
   // console.log(uploadImage.name);
   await sharp(uploadImage.name).resize(600, 600);
 
    const filePath = path.join('uploads', record.id().toString(), uploadImage.name);
    await fs.promises.mkdir(path.dirname(filePath), { recursive: true });

    await fs.promises.rename(uploadImage.path, filePath);

    await record.update({ imagePath: `/${filePath}` });
  }
  return response;
};

/** @type {AdminBro.Before} */
const before = async (request, context) => {
  if (request.method === 'post') {
    const { uploadImage, ...otherParams } = request.payload;

    // eslint-disable-next-line no-param-reassign
    context.uploadImage = uploadImage;

    return {
      ...request,
      payload: otherParams,
    };
  }
  return request;
};

module.exports = { after, before };

const filePath = path.join('uploads', record.id().toString(), uploadImage.name); 
    await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
    await sharp(uploadImage.path).withMetadata().resize(600,600).toFile(filePath);//here added correct paths but now although it saved image, doesnt reduce imageSize

【问题讨论】:

    标签: node.js image resize sharp


    【解决方案1】:

    您没有将处理后的图像写入文件。

    假设这是您的存储路径:

    const outputPath = __dirname + `/../storage/myImage.jpeg`;
    

    您可以将该路径提供给sharp

    await sharp('path/of/originalImage').withMetadata().resize(600, 600).toFile(outputPath);
    

    我强烈建议您使用withMetaData(),否则您会丢失图像元数据

    【讨论】:

    • sharp() 和 toFile() 中的变量是否相同?
    • 不,path是资源图片的路径(原图)
    • 等待 fs.promises.mkdir(path.dirname(filePath), { recursive: true });等待尖锐(uploadImage.path).withMetadata().resize(600,600).toFile(filePath);控制台.log(上传图片);等待 fs.promises.rename(uploadImage.path, filePath);等待记录更新({ imagePath:/${filePath}});像这样程序既不会给我错误也不会减少 imageSize
    • 我无法理解这个问题。请把这部分添加到你的问题中好吗?
    • 但是您没有指定任何文件扩展名。处理后的图像的扩展名是什么?您可以尝试在filepath 末尾添加.jpeg 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 2017-03-25
    • 2012-10-06
    • 2014-07-24
    • 2013-07-12
    • 2017-04-22
    相关资源
    最近更新 更多