我正在 Electron 和 Svelte 中制作梦想日记应用程序。我有一种自定义文件格式,其中包含标题、描述和一张或多张图像。请参阅:
程序输入
文件输出
当我需要时,我可以调用ipcRenderer.invoke()
在主进程中读取文件,然后返回该文件以在渲染器进程中检索它(不用担心,我正在使用 async
await
来确保我不仅仅是得到一个 promise 。另外,对于我的测试,我仅发回代表图像的 Uint8Array)。
在尝试显示图像但失败后,我决定检查一下我是否按预期接收了信息。我将响应按原样发送回主进程并将其写入文件。当我在画图软件中打开该文件时,它就会显示出来。
所以,信息是正确的。这是我尝试显示图像的代码:
在<script>
内
let src;
onMount(async () => {
let a = await ipcRenderer.invoke("file-read");
console.log(a);
let blob = new Blob(a, {type: 'image/png'});
console.log(blob);
ipcRenderer.send("verify-content", a); // this is the test I mentioned, where it was written to a file
src = URL.createObjectURL(blob);
});
在体内
{#if src}
<img src={src} />
{/if}
我还尝试了另一种方式:
在<script>
内
onMount(async () => {
let a = await ipcRenderer.invoke("file-read");
console.log(a);
let blob = new Blob(a, {type: 'image/png'});
console.log(blob);
ipcRenderer.send("verify-content", a);
const img = document.createElement("img");
img.src = URL.createObjectURL(blob);
img.onload = function() {
URL.revokeObjectURL(this.src);
}
document.getElementById("target").appendChild(img);
});
在体内
<div id="target"></div>
但是,这就是我所得到的:
不显示。我怎样才能显示这个图像?我发现的所有其他“blob to img”示例都使用 type="file"
<input />
标签。如果可能,我想避免使用 Base64 数据 URI。谢谢。
最佳答案
事实证明,当我用它制作一个 blob 时,我必须将 Uint8Array package 在一个数组中(wtf)。
let blob = new Blob([a], {type: "image/png"});
关于javascript - 如何将原始二进制数据转换为 blob 并将其显示在 img 标记中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66466412/