javascript - 图像上传、调整大小和编码为 base64 导致 Chrome 在移动设备上崩溃

标签 javascript android css

我的用户可以使用文件上传 HTML 输入元素选择图像 -

<强>1。从那里我缩小规模

<强>2。我转换为 base64

For some reason Chrome mobile & Android browser completely crash - and display an 'Out of Memory error'.

如果浏览器在更“现代/功能强大”的设备上运行,一切都很好。

什么可能导致这里的错误 - 可以修复吗?


这是缩小(同时保持纵横比)并返回图像的 Base64 字符串的函数。

function resizeAndConvertB64(img, maxWidth, maxHeight) {
    var imgWidth = img.width, 
        imgHeight = img.height;

    var ratio = 1, ratio1 = 1, ratio2 = 1;
    ratio1 = maxWidth / imgWidth;
    ratio2 = maxHeight / imgHeight;

    // Use the smallest ratio that the image best fit into the maxWidth x maxHeight box.
    if (ratio1 < ratio2) {
        ratio = ratio1;
    }
    else {
        ratio = ratio2;
    }
    var canvas = document.createElement("canvas");
    var canvasContext = canvas.getContext("2d");
    var canvasCopy = document.createElement("canvas");
    var copyContext = canvasCopy.getContext("2d");
    var canvasCopy2 = document.createElement("canvas");
    var copyContext2 = canvasCopy2.getContext("2d");
    canvasCopy.width = imgWidth;
    canvasCopy.height = imgHeight;  
    copyContext.drawImage(img, 0, 0);

    // init
    canvasCopy2.width = imgWidth;
    canvasCopy2.height = imgHeight;        
    copyContext2.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvasCopy2.width, canvasCopy2.height);


    var rounds = 1;
    var roundRatio = ratio * rounds;
    for (var i = 1; i <= rounds; i++) {


        // tmp
        canvasCopy.width = imgWidth * roundRatio / i;
        canvasCopy.height = imgHeight * roundRatio / i;

        copyContext.drawImage(canvasCopy2, 0, 0, canvasCopy2.width, canvasCopy2.height, 0, 0, canvasCopy.width, canvasCopy.height);

        // copy back
        canvasCopy2.width = imgWidth * roundRatio / i;
        canvasCopy2.height = imgHeight * roundRatio / i;
        copyContext2.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvasCopy2.width, canvasCopy2.height);

    } // end for


    // return Base64 string of the downscaled image
    canvas.width = imgWidth * roundRatio / rounds;
    canvas.height = imgHeight * roundRatio / rounds;
    canvasContext.drawImage(canvasCopy2, 0, 0, canvasCopy2.width, canvasCopy2.height, 0, 0, canvas.width, canvas.height);
    var dataURL = canvas.toDataURL();
    return dataURL;


}

最佳答案

我认为这是 Chrome 移动版的错误。
Chrome 移动版不稳定,我的手在使用时经常崩溃。
内存不足消息表示您的设备没有足够的内存用于此脚本。
检查它是否适用于 Dolphin 浏览器。
我认为它会起作用,但我不知道。

关于javascript - 图像上传、调整大小和编码为 base64 导致 Chrome 在移动设备上崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26257111/

相关文章:

jquery - 在应用类之前更改CSS类不生效

javascript - 文字的形状非常规

javascript - Bootstrap Twitter typeahead 设置不起作用

javascript - 转换带有对象的数组以进行操作

java - 在android中单击按钮时重新启动或刷新计时器

android - 如何在文本字段外触摸后隐藏键盘?

javascript - 无法使用 Highchart API 构建多级钻取图表

javascript - 在 javascript 中清理innerHTML

Android, 滑动抽屉

css - 为什么 offsetHeight 和 offsetWidth 间歇性地不准确?