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

Ban*_*ahu 2 api jpeg libjpeg node.js

有没有办法编写 API 将普通图像转换为使用 Nodejs 的渐进式图像。我不想使用 Base64。我在这方面做了很多研发。我找到了一个库,即 lib Turbo-jpeg 但只有这个库才能解码图像。我也想对该图像进行编码。请检查以下链接以供参考。如果有人有任何解决方案,请告诉我。

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

请帮我编写 API 将图像转换为渐进式。

先感谢您。

far*_*jad 5

您可以使用模块将支持的图像格式转换为渐进式JPEG gm

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

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();
Run Code Online (Sandbox Code Playgroud)

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