0

I want to convert an image from img.src to jpeg format if it doesn't support any of the given formats. but here toBuffer(err,buffer) return buffer as null. What should i do.

import { JSDOM } from "jsdom";
import mammoth from "mammoth";
import gm from "gm";

const im = gm.subClass({ imageMagick: true });
import { Buffer } from "buffer";

function convertImage(imgBase64Str, cb) {
  const buffer = Buffer.from(imgBase64Str, "base64");
  im(buffer)
    .setFormat("png")
    .toBuffer((err, b) => {
      if (err) console.error(err);
      const newImgBase64Str = buffer.toString("base64");
      cb(newImgBase64Str);
    });
}

function checkAndConvertImage(imgBase64Str, cb) {
  const buffer = Buffer.from(imgBase64Str, "base64");
  const imgType = buffer.toString("hex", 0, 8);

  if (
    imgType.startsWith("ffd8") || // JPEG
    imgType.startsWith("89504e470d0a1a0a") || // PNG
    imgType.startsWith("474946383761") || // GIF (87a)
    imgType.startsWith("474946383961") || // GIF (89a)
    imgType.startsWith("424d") || // BMP
    imgType.startsWith("49492a00") || // TIFF (little-endian)
    imgType.startsWith("4d4d002a") // TIFF (big-endian)
  ) {
    return cb(imgBase64Str);
  } else {
    return convertImage(imgBase64Str, cb);
  }
}

export const parseDocx = async (req, res) => {
  try {
    const file = req.file;
    const result = await mammoth.convertToHtml({ path: file.path });
    const html = result.value; // The generated HTML
    // console.log(html);

    const dom = new JSDOM(html);
    const images = dom.window.document.querySelectorAll("img");
    console.log("THESE ARE ALL IMAGES", images);
    const imagePromises = [];
    images.forEach((image) => {
      // console.log(image.src);
      const imgBase64Str = image.src.split(",")[1];
      imagePromises.push(
        new Promise((resolve, reject) => {
          checkAndConvertImage(imgBase64Str, (newImgBase64Str) => {
            // console.log(newImgBase64Str);
            image.src = `data:image/jpeg;base64,${newImgBase64Str}`;
            resolve();
          });
        })
      );
    });
    await Promise.all(imagePromises);
    const newHtml = dom.serialize();

    const messages = result.messages; // Any messages, such as warnings during conversion
    res.status(200).json({ html: newHtml, messages });
  } catch (error) {
    console.log("naa bhai nhi chala ");
    res.status(500).json({ message: error.message });
  }
};

Expecting buffer data to be returned from convertImage and sent to callback function which can save it. should I use any other library for this?

0 Answers0