简体   繁体   中英

Set src of an image with object url doesn't work in electron

I'm building an electron ("electron": "^5.0.9", on windows 10 1903) app and have a nodejs buffer(Uint8Array) ("node": "v10.6.0") containing data like "[255, 216, 255, 224, 0, 16,..." with MIME type "image/jpeg".

I tried to create an object url from the buffer and set the url as the "src" of an image, but the image didn't show

I have tried to save it as a jpg on local fs to verify the data and successed

In the Network tool, there was a request sent to blob:file:///60cb1522-25d2-44e9-982d-21e2106dddf8 and the Status Code is 200 .

The code like this

    const imgBlob = new Blob(buffer, { type: `image/jpeg` })
    const imgUrl = window.URL.createObjectURL(imgBlob)
    document.querySelector(`img`).src = imgUrl

Expected: the image show correctly

Actual result: the image didn't show

I found the answer here

How can I create a PNG blob from binary data in a typed array?

All I need is just a [ ] to wrap the buffer like

const imgBlob = new Blob([buffer], { type: `image/jpeg` })

According to the MDN

var aBlob = new Blob(array [, options]);

array is an Array of ArrayBuffer, ArrayBufferView, Blob, DOMString objects, or a mix of any of such objects , that will be put inside the Blob. DOMStrings are encoded as UTF-8.

Blob()

Holy crap!

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