reactjs canvas.toBlob不适用于iPhone图像上传

5ktev3wc  于 4个月前  发布在  React
关注(0)|答案(1)|浏览(57)

我一直在React中开发一个具有裁剪功能的应用程序。代码应该将图像转换为画布,然后将画布转换为Blob,这样我就可以在稍后的代码中使用base64字符串。一切都很好,并且在我的Android手机上正常工作,在我的电脑和不同的浏览器上。唯一的问题是iPhone。只有当从iPhone上传时选择实际大小时,我才会从canvas.toBlob()获得空值.当我上传图片并选择大而不是实际大小时,代码正常运行。下面是代码:

const getCroppedImg = (image: any, crop: Crop) => {
        const canvas = document.createElement('canvas');
        const pixelRatio = window.devicePixelRatio;
        const scaleX = image.naturalWidth / image.width;
        const scaleY = image.naturalHeight / image.height;
        const ctx = canvas.getContext('2d');
    
        canvas.width = crop.width * pixelRatio * scaleX;
        canvas.height = crop.height * pixelRatio * scaleY;

        if(ctx == null){
            return;
        }
    
        ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
        ctx.imageSmoothingQuality = 'high';
    
        ctx.drawImage(
          image,
          crop.x * scaleX,
          crop.y * scaleY,
          crop.width * scaleX,
          crop.height * scaleY,
          0,
          0,
          crop.width * scaleX,
          crop.height * scaleY
        );
    
        return new Promise((resolve, reject) => {
          canvas.toBlob(
            (blob) => {
              if (!blob) {
                reject(new Error('Canvas is empty'));
                console.error('Canvas is empty');
                alert("Canvas is emtpy")
                return;
              }
              const reader = new FileReader();
              reader.readAsDataURL(blob)
              reader.onloadend = function(){
                if(reader.result != null && typeof(reader.result) === 'string'){
                    const base64data:string = reader.result
                    resolve(base64data);
                }
              }
              
            },
            'image/jpeg',
            0.5
          );
        });
    }

字符串
图片大小并不重要,我上传了更大的文件大小从电脑和它的工作,我也做了6000 x 6000像素的图像,也上传罚款从我的电脑.我真的很困惑,不知道从哪里开始.我看到人们抱怨Safari上的toBlob,但toBlob的工作正常,如果实际大小没有选择.此外,同样的事情发生在iPhone上的Chrome.
任何线索都是有帮助的,因为我已经没有想法了。我认为发布其他代码只会让这篇文章膨胀,但如果有人需要知道应用程序中还发生了什么,我也很乐意发布。

e0bqpujr

e0bqpujr1#

这里是toBlob()的浏览器限制链接。
Safari自2017年和iOS 11以来一直支持它,但仍然不支持“quality”。似乎您正在以某种形式使用该参数“imageSmoothingQuality = 'high'”。
如果最终你遇到了浏览器支持问题,一个解决方案是用blueimp-canvas-to-blob之类的东西来填充它。或者显然只是不使用有问题的参数。

相关问题