首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在node.js上调整图像大小

在node.js上调整图像大小
EN

Stack Overflow用户
提问于 2021-05-27 18:40:47
回答 1查看 46关注 0票数 0

我想保存图像后调整大小,所以使用夏普包,但不要小图像size.Iadded等待夏普(uploadImage.name).resize(600,600);行保存文件夹后,我错过了什么?

代码语言:javascript
复制
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 };

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2021-05-27 20:03:19

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

假设这是您的存储路径:

代码语言:javascript
复制
const outputPath = __dirname + `/../storage/myImage.jpeg`;

您可以将该路径提供给sharp

代码语言:javascript
复制
await sharp('path/of/originalImage').withMetadata().resize(600, 600).toFile(outputPath);

我强烈建议你使用withMetaData(),否则你会丢失你的图片metaData

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67720474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档