Phonegap - 如何从base64字符串生成图像文件

Phonegap - How to generate image file from base64 string?

本文关键字:图像 文件 字符串 base64 Phonegap      更新时间:2023-09-26

正在为Android编写一个Phonegap应用程序,有一次,我将base64 PNG字符串保存为文件。但是,我观察到字符串只是转储到文件中,打开时无法作为图像查看。

我希望能够保存从base64字符串生成的图像。这是我所拥有的:

Javascript(针对Phonegap格式化):

/*** Saving The Pic ***/
var dataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; //A simple red dot
function gotFS(fileSystem) {
    fileSystem.root.getFile("dot.png", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {  
    fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
    writer.write(dataURL); //does not open as image
}
function fail(error) {
    console.log(error.code);
}

我尝试编辑代码以仅保存图像数据,但它也不起作用。(见下文)

function gotFileWriter(writer) {
     var justTheData = dataURL.replace(/^data:image'/(png|jpg);base64,/, "");//Removes everything up to ...'base64,'
     writer.write(justTheData); //also does not show
 }

触发一切的 HTML:

<p onclick="window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail)">Save a Dot</p>

请帮忙。谢谢。

您只需要将图像的 src 设置为 base 64 数据即可查看图像。

var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + justTheData;

这里不需要替换base64字符串,只需通过以下方式设置转换字符串:

在 JavaScript 中:

var image = document.getElementById('myImage');
image.src = justTheData;// this convert data

在jquery中:

$("#imageid").attr("src",justTheData)