javascript - python PIL _io.BytesIO 无法读取用 Canvas 转换的图像

标签 javascript python todataurl bytesio

Python PIL 拒绝读取您使用 Javascript Canvas 调整大小的图像

我在客户端使用 Javascript 调整图像大小:

var reader = new FileReader();
    reader.onload = function (e) {
        el('image-picked').src = e.target.result;
        el('image-picked').className = '';
        var image = new Image();

        //compress Image
        image.onload=function(){
            el("image-picked").src=image.src;
            var canvas=document.createElement("canvas");
            var context=canvas.getContext("2d");
            new_size = get_sizes(image.width,image.height,max_side_px)
            [canvas.width,canvas.height] = new_size;
            context.drawImage(image,
                0,
                0,
                image.width,
                image.height,
                0,
                0,
                canvas.width,
                canvas.height
            );
            console.log("Converted");

            //el('image-picked').className = 'no-display'
            //el('image-picked').src=""
            el('upload-Preview').className = ''
            el('upload-Preview').src = canvas.toDataURL("image/png", quality);

结果似乎还可以,体积更小,看起来还可以: enter image description here 使用 identify 的文件只有细微差别: enter image description here

(base) ➜  Desktop file before.png after.png
before.png: PNG image data, 4048 x 3036, 8-bit/color RGB, non-interlaced
after.png:  PNG image data, 500 x 375, 8-bit/color RGBA, non-interlaced

然后我通过 POST 发送文件:

    var xhr = new XMLHttpRequest();
    var loc = window.location
    xhr.open('POST', `${loc.protocol}//${loc.hostname}:${loc.port}/analyze`, true);
    xhr.onerror = function() {alert (xhr.responseText);}
    xhr.onload = function(e) {
        if (this.readyState === 4) {
            var response = JSON.parse(e.target.responseText);
            el('result-label').innerHTML = `Result = ${response['result']}`;
        }
    }

    var fileData = new FormData();
    var file = new File([el('upload-Preview').src],
      "image.png", { type: "image/png",
                     lastModified : new Date()});
    fileData.append('file', uploadFiles[0]);
    xhr.send(fileData);

然后我用 python open_image(BytesIO(img_bytes)) 在服务器上读取:

@app.route('/analyze', methods=['POST'])
async def analyze(request):
    data = await request.form()
    img_bytes = await (data['file'].read())
    img = open_image(BytesIO(img_bytes))

上面的工作没有任何正常图像的问题,但是它失败任何图像,这是用js调整大小的结果,错误是

File "/Users/brunosan/anaconda3/envs/fastai/lib/python3.7/site-packages/PIL/Image.py", line 2705, in open
    % (filename if filename else fp))
OSError: cannot identify image file <_io.BytesIO object at 0x124ce6360>```

我已经在 J​​S 端尝试了 canvas.toDataURL("image/jpeg", quality),并直接使用 PIL 读取(不是 fastai,它调用 PIL)。这是同样的错误:frowning_face:

最佳答案

找到答案 here .

当 POST 需要二进制文件时,我将图像作为 DataURL 注入(inject)。我可以使用“网络”选项卡看到不同之处: enter image description here

要将 DataURL 转换为二进制文件,我们需要制作一个 Blob,然后将其放入一个文件中:

function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type:mimeString});
}

blob=dataURItoBlob(el('upload-Preview').src)
var file = new File([blob],
      "image.png", { type: "image/png",
                     lastModified : new Date()});
var fileData = new FormData();
fileData.append('file', file);

关于javascript - python PIL _io.BytesIO 无法读取用 Canvas 转换的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57333540/

相关文章:

javascript - 根据某些条件在我的 HTML 页面中创建一个对话框

python - 无法在循环中设置正确的索引

javascript - 从 Canvas 保存图像时缺少扩展名

javascript - 使用 img.crossOrigin = "Anonymous"将图像绘制到 Canvas 不起作用

Javascript Pdfjs Canvas 到 Img

javascript - 菜单按钮在单击 React/CSS 时更改阴影

javascript - 如何让 DOM 元素的更新更加高效?

java - 如何动态构造和设置 dijit.form.select 小部件的选项?

python - 为什么我会收到 SQLAlchemy 嵌套回滚错误?

python - 在 Python 3 中逐行读取文件时捕获 UnicodeDecodeError 异常