【问题标题】:How to use Node Sharp package如何使用 Node Sharp 包
【发布时间】:2021-08-27 09:46:26
【问题描述】:

我实际上是在尝试使用 sharp 包调整图像大小。供参考:https://www.npmjs.com/package/sharp

我正在从前端(在反应中)获取图像数据到后端(在节点中),如下所示

    imageData {
      name: 'xyz.JPEG',
      data: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff db 00 43 00 01 01 01 01 01 01 01 01 01 01 01 01
    01 01 01 01 01 01 01 01 01 01 01 01 01 ... 23589 more bytes>,
      size: 23639,
      encoding: '7bit',
      tempFilePath: '',
      truncated: false,
      mimetype: 'image/jpeg',
      md5: '899917d14fe775aa2097487e3ddcc9f6',
      mv: [Function: mv]
    }


But I am not understanding which function to use exactly for the format which I am getting to the backend. As I am not understanding exactly where the buffer output is being passed in the sharp package functions.

请帮帮我。谢谢

【问题讨论】:

    标签: node.js node-modules sharp npm-package


    【解决方案1】:

    我在下面添加了一个示例,通过一个常数因子(例如 0.25)缩放图像数据。这将缩放图像的宽度和高度。

    文档中有更多有用的示例: https://sharp.pixelplumbing.com/api-resize#resize

    const sharp = require("sharp");
    
    // Resize both width and height to max dimension.
    async function resizeImageBuffer(imageBuffer, maxDimension) {
        const sharpImg = await sharp(imageBuffer);
        return sharpImg.resize({ width: maxDimension, height: maxDimension, fit: 'contain', background: { r: 255, g: 255, b: 255, alpha: 1 } }).toBuffer();
    }
    
    async function testResize(imgData) {
        console.log(`testResize: Resizing: ${imgData.name}...`);
        const MAX_DIMENSION = 64; 
        let resized = await resizeImageBuffer(imgData.data, MAX_DIMENSION);
        console.log(`testResize: resize complete: original: ${imgData.data.length} bytes, resized: ${resized.length} bytes.`);
        fs.writeFileSync(path.join(outputDir, imgData.name), resized);
    } 
    
    testResize(imgData);
    

    【讨论】:

    • 尺寸 64 X 64 的 SCALE_FACTOR 应该是多少
    • 要使图像为 64 x 64,请将宽度和高度传递给锐化调整大小,例如sharp.resize({ 宽度:64,高度:64 })。请注意,这可能会扭曲图像的纵横比。
    • 好的,知道了。但是,我观察到图像被裁剪而不是压缩
    • 我会看看适合的选项,例如sharp.resize({width: 64, height:64, fit: 'contain'}),有几个选项可以确定显示锐利调整图像大小。我建议使用 fit: 'contain' 或 fit: 'inside'
    • 能否请您发送我们可以找到选项的网址
    【解决方案2】:

    您需要的是前端的imageData 中的data,并在sharp 模块中使用resize 函数。

    以下是如何将图像大小调整为 150 像素宽的示例:

    import sharp from 'sharp';
    
    /*
     * This function will return a Promise<Buffer>
     */
    async function resize(imageData) {
      return sharp(imageData.data).resize(150).toBuffer();
    }
    

    这是 resize 方法 (v0.27.2) 的文档:

    /**
     * Resize image to width, height or width x height.
     *
     * When both a width and height are provided, the possible methods by which the image should fit these are:
     *  - cover: Crop to cover both provided dimensions (the default).
     *  - contain: Embed within both provided dimensions.
     *  - fill: Ignore the aspect ratio of the input and stretch to both provided dimensions.
     *  - inside: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified.
     *  - outside: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified.
     *             Some of these values are based on the object-fit CSS property.
     *
     * When using a fit of cover or contain, the default position is centre. Other options are:
     *  - sharp.position: top, right top, right, right bottom, bottom, left bottom, left, left top.
     *  - sharp.gravity: north, northeast, east, southeast, south, southwest, west, northwest, center or centre.
     *  - sharp.strategy: cover only, dynamically crop using either the entropy or attention strategy. Some of these values are based on the object-position CSS property.
     *
     * The experimental strategy-based approach resizes so one dimension is at its target length then repeatedly ranks edge regions,
     * discarding the edge with the lowest score based on the selected strategy.
     *  - entropy: focus on the region with the highest Shannon entropy.
     *  - attention: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
     *
     * Possible interpolation kernels are:
     *  - nearest: Use nearest neighbour interpolation.
     *  - cubic: Use a Catmull-Rom spline.
     *  - lanczos2: Use a Lanczos kernel with a=2.
     *  - lanczos3: Use a Lanczos kernel with a=3 (the default).
     *
     * @param width pixels wide the resultant image should be. Use null or undefined to auto-scale the width to match the height.
     * @param height pixels high the resultant image should be. Use null or undefined to auto-scale the height to match the width.
     * @param options resize options
     * @throws {Error} Invalid parameters
     * @returns A sharp instance that can be used to chain operations
     */
    resize(width?: number | null, height?: number | null, options?: ResizeOptions): Sharp;
    

    【讨论】:

      猜你喜欢
      • 2022-10-01
      • 1970-01-01
      • 2018-11-22
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      • 2016-06-27
      • 2021-09-21
      • 1970-01-01
      相关资源
      最近更新 更多