简体   繁体   中英

react image crop output to base64 is not working

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');
        });
    }

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
  );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM