使用Node Js将普通图像转换为渐进图像

时间:2019-04-22 04:42:12

标签: node.js api jpeg libjpeg

有没有什么方法可以编写API,从而将普通图像转换为Nodejs渐进式。我不想使用Base64。 我已经做了很多研发工作。我发现的一个库即lib turbo-jpeg 但这只是他们在解码图像。我也想对该图像进行编码。 请检查以下链接以供参考。如果有人有任何解决方案,请告诉我。

链接为- https://github.com/LinusU/cwasm-jpeg-turbo

请帮助我编写API,以将图像转换为令人满意的图像。

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以将gm module结合使用,将支持的图像格式转换为渐进JPEG。

这是一个简单的示例(在具有GraphicsMagick v1.3.31和Node.js v10.15.3的macOS上测试):

const fs = require('fs');
const path = require('path');
const https = require('https');

const gm = require('gm'); // https://www.npmjs.com/package/gm

const gmIdentify = gmInstance =>
  new Promise((resolve, reject) => {
    gmInstance.identify((err, data) => {
      if (err) {
        reject(err);
        return;
      }
      resolve(data);
    });
  });

const gmStream = (gmInstance, writeStream, format = 'jpg') =>
  new Promise((resolve, reject) => {
    gmInstance
      .stream(format)
      .pipe(writeStream)
      .once('finish', resolve)
      .once('error', reject);
  });

// This function downloads the file from the specified `url` and writes it to
// the passed `writeStream`.
const fetchFile = (url, writeStream) =>
  new Promise((resolve, reject) => {
    https.get(url, res => {
      if (res.statusCode !== 200) {
        reject(new Error('Something went wrong!'));
        return;
      }

      res
        .pipe(writeStream)
        .once('finish', () => {
          resolve();
        })
        .once('error', err => {
          reject(err);
        });
    });
  });

const main = async () => {
  // Download a sample non-progressive JPEG image from the internet
  const originalJpegUrl =
    'https://upload.wikimedia.org/wikipedia/commons/b/b4/JPEG_example_JPG_RIP_100.jpg';
  const originalPath = path.join(__dirname, './original.jpeg');
  await fetchFile(originalJpegUrl, fs.createWriteStream(originalPath));
  originalJpegData = await gmIdentify(gm(fs.createReadStream(originalPath)));
  console.log(
    `Interlace for the original jpeg file is set to ${
      originalJpegData['Interlace']
    }`,
  );

  // Convert the downloaded file to Progressive-JPEG
  const progressiveJpegPath = path.join(__dirname, 'progressive.jpg');
  await gmStream(
    gm(fs.createReadStream(originalPath))
      .interlace('line' /* or 'plane' */) // https://www.imagemagick.org/MagickStudio/Interlace.html
      .quality(originalJpegData['JPEG-Quality']), // save with the same quality as the original file
    fs.createWriteStream(progressiveJpegPath),
  );
  const progressiveJpegData = await gmIdentify(
    gm(fs.createReadStream(progressiveJpegPath)),
  );
  console.log(
    `Interlace for the converted jpeg file is set to ${
      progressiveJpegData['Interlace']
    }`,
  );
};

main();

它将下载this个非渐进式JPEG图像,并将其转换为渐进式JPEG图像,并将其另存为progressive.jpg与脚本相同的目录。

答案 1 :(得分:1)

如果有人像我一样c / p @fardjad的回答并遇到以下错误,对我来说(Ubuntu 16.04)只是想更改一行:

(node:14862) UnhandledPromiseRejectionWarning: Error: Could not execute GraphicsMagick/ImageMagick: gm "identify" "-ping" "-verbose" "-" this most likely means the gm/convert binaries can't be found

发件人:

const gm = require('gm'); // https://www.npmjs.com/package/gm

收件人:

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