Emscripten:在 HTML 文件中显示图像

Emscripten: Display an image in HTML file

本文关键字:显示 显示图 图像 文件 HTML Emscripten      更新时间:2023-10-16

我已经从c ++文件构建了JS程序(带有emscripten),它会生成一个png文件。

该程序在 html 文件中加载和执行。

现在我想在这个html文件中显示创建的png文件。但是Emscripten有一个模拟的沙盒文件系统,所以我的png文件是写在这个文件系统中的。

如何检索此文件以显示它?

您可以通过 emscripten 文件系统 API 访问它。

假设您在 C++ 中有一个函数,该函数返回生成的 PNG 文件的路径,如下所示:

std::string processImage()
{
    std::string filename = "my.png";
    // open and write to your file
    return filename;
}

在 html 中,添加一些 js 来读取文件,将其转换为 blob,然后转换为对象 URL:

const filename = Module.processImage(); // Call your C++ function
const blob = new Blob([FS.readFile(filename)], {'type': 'image/png'});
const url = URL.createObjectURL(blob);
// You can use this url as the src attribute of an img element