react image crop output to base64 is not working

1.2k Views Asked by At

I am trying to crop the image and then upload to server, but the api server accepts the image as base64 format, it seems not to be working, if there's any work around? much appreciated!!! and im getting the image as blob, i dont know how to convert it to base64.

This is the output i am getting from the image tag

src="blob:http://localhost:3000/c61ee692-8697-43c3-b9c0-5077322940eb"

Please take a look at the code below


 getCroppedImg(image, crop, fileName) {
        const canvas = document.createElement('canvas');
        const scaleX = image.naturalWidth / image.width;
        const scaleY = image.naturalHeight / image.height;
        canvas.width = crop.width;
        canvas.height = crop.height;
        const ctx = canvas.getContext('2d');
        ctx.imageSmoothingQuality = 'high';
        ctx.drawImage(
            image,
            crop.x * scaleX,
            crop.y * scaleY,
            crop.width * scaleX,
            crop.height * scaleY,
            0,
            0,
            crop.width,
            crop.height
        );
        // As Base64 string
        const base64Image = canvas.toDataURL('image/jpeg');

        return new Promise((resolve, reject) => {
            canvas.toBlob(blob => {
                if (!blob) {
                    console.error('Canvas is empty');
                    return;
                }
                blob.name = fileName;
                window.URL.revokeObjectURL(this.fileUrl);
                this.fileUrl = window.URL.createObjectURL(blob);
                resolve(this.fileUrl);
            }, 'image/jpeg');
        });
    }

1

There are 1 best solutions below

0
On

Note the "convert to base64" comment in the sample below. Identify that section in your code and add that.

    return new Promise((resolve, reject) => {
  canvas.toBlob(
    (blob) => {
      if (!blob) {
        //reject(new Error('Canvas is empty'));
        console.error("Canvas is empty");
        return;
      }
      //convert to base64
      var reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onloadend = function () {
        var base64String = reader.result;
        console.log("Base64 String - ", base64String);
        //
      };

      blob.name = fileName;
      window.URL.revokeObjectURL(this.fileUrl);
      this.fileUrl = window.URL.createObjectURL(blob);
      console.log(this.fileUrl);
      resolve(this.fileUrl);
    },
    "image/jpeg",
    1
  );
});