3

I tried to use Sharp image processing in my create react app. But it sends an error enter image description here

This is my code:

import sharp from 'sharp';

const buffer = await sharp(req.file.buffer)
          .resize({ width: 250, height: 250 })
          .extend({
            top: 10,
            bottom: 10,
            left: 10,
            right: 10,
            background:  '#d7d8de'
          })
          .png()

Edit: I’m using Node.js version 12.18.0

Rupam
  • 75
  • 1
  • 9

2 Answers2

3

No.

Sharp uses the node.js runtime as well as binary executable code that is installed on the host system. All this means that Sharp does not work in a web browser.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • Is there any similar library for react js? Actually I like Sharp extend option. But this option are absent in many image processing library. – Rupam Nov 02 '21 at 16:36
0

I see that somebody already provided a good answer, but more alternatives can't hurt

For the simple task of resizing an image that I had to do in a service worker for a Chrome V3 extension, after many tries with canvases I found that image-js easily did the trick.

Here is a snippet for what I did:

import { Image } from 'image-js';

export const downsizeImage = async (
    imageBase64: string
): Promise<string> => {
  const blob = await fetch(imageBase64).then(r => r.blob());
  const buffer = await blob.arrayBuffer();

  const image = await Image.load(buffer);

  const resizedImage = image.resize({ width: 200, height: 200 });

  const imgBuffer = resizedImage.toBuffer();

  // convert to base64
  return Buffer.from(imgBuffer)
      .toString('base64');
}