0

我正在尝试裁剪图像然后上传到服务器,但是 api 服务器接受图像为 base64 格式,它似乎不起作用,如果有任何解决方法?非常感激!!!我将图像作为 blob,我不知道如何将其转换为 base64。

这是我从图像标签得到的输出

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

请看下面的代码


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

4

1 回答 1

0

请注意下面示例中的“转换为 base64”注释。识别代码中的该部分并添加它。

    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
  );
});
于 2021-12-16T13:33:22.617 回答