Nodejs GM 图片处理如何不压缩小尺寸图片

Nodejs GM 图片处理如何不压缩小尺寸图片

操作发现上传大图压缩非常好。可惜我小图上传他也把图拉扯大、如何解决

2 回复

Nodejs GM 图片处理如何不压缩小尺寸图片

在使用 gm(GraphicsMagick for Node.js)处理图片时,有时会遇到这样的问题:上传小尺寸图片时,即使原图很小,gm 也会对其进行放大处理,导致图片质量下降。本文将介绍如何通过配置 gm 来避免这种情况。

示例代码

const gm = require('gm').subClass({ imageMagick: true });

function processImage(inputPath, outputPath) {
    gm(inputPath)
        .size((err, size) => {
            if (err) throw err;
            
            // 获取图片的宽度和高度
            const width = size.width;
            const height = size.height;

            // 定义目标宽度和高度
            const targetWidth = 300;
            const targetHeight = 300;

            // 如果图片尺寸小于目标尺寸,则保持原尺寸
            if (width < targetWidth || height < targetHeight) {
                gm(inputPath)
                    .write(outputPath, (err) => {
                        if (err) throw err;
                        console.log(`Processed image saved to ${outputPath}`);
                    });
            } else {
                // 否则,按比例缩放图片到目标尺寸
                gm(inputPath)
                    .resize(targetWidth, targetHeight)
                    .write(outputPath, (err) => {
                        if (err) throw err;
                        console.log(`Processed image saved to ${outputPath}`);
                    });
            }
        });
}

// 使用示例
processImage('path/to/input.jpg', 'path/to/output.jpg');

解释

  1. 引入 gm 模块:首先需要引入 gm 模块,并设置为使用 imageMagick
  2. 获取图片尺寸:使用 gm().size() 方法获取输入图片的尺寸。
  3. 定义目标尺寸:设定一个目标宽度和高度(例如,300x300 像素)。
  4. 条件判断:检查输入图片的尺寸是否小于目标尺寸。如果是,则直接保存原图;否则,按比例缩放图片到目标尺寸。
  5. 保存输出图片:根据上述逻辑,选择性地进行缩放或直接保存原图,并将其写入输出路径。

通过这种方式,可以确保小尺寸图片不会被拉伸或压缩,从而保持其原始质量。


在使用 Node.js 的 gm(GraphicsMagick)库处理图片时,默认情况下可能会对小尺寸图片进行压缩或拉伸。为了避免这种情况,你可以通过调整 gm 模块的一些选项来确保小尺寸图片不会被压缩。

示例代码

首先,你需要安装 gm 模块:

npm install gm

然后,你可以使用以下代码来处理图片,避免压缩小尺寸图片:

const gm = require('gm').subClass({imageMagick: true});

function resizeAndSaveImage(inputPath, outputPath, maxWidth, maxHeight) {
    gm(inputPath)
        .resize(maxWidth, maxHeight, '^>')
        .write(outputPath, (err) => {
            if (err) throw err;
            console.log(`Image saved to ${outputPath}`);
        });
}

// 使用示例
const inputPath = 'path/to/input/image.jpg';
const outputPath = 'path/to/output/image.jpg';
const maxWidth = 800; // 最大宽度
const maxHeight = 600; // 最大高度

resizeAndSaveImage(inputPath, outputPath, maxWidth, maxHeight);

解释

  • resize(maxWidth, maxHeight, '^>')
    • maxWidthmaxHeight 分别定义了最大宽度和高度。
    • '^>' 是一个几何操作符,它表示如果图像的任意一边大于指定的最大边,则按比例缩小。这意味着如果图片尺寸已经小于给定的最大尺寸,它将保持原样而不被拉伸或压缩。

通过这种方式,你可以确保小尺寸图片不会被拉伸或压缩。该方法会自动根据需要调整图片大小,同时保留小尺寸图片的原始比例。

如果你希望完全禁止任何尺寸的图片被拉伸或压缩,可以在特定条件下进一步检查输入图片的实际尺寸并进行相应的处理。

回到顶部