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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11321347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:45:37  来源:igfitidea点击:

Phonegap - How to generate image file from base64 string?

javascriptandroidcordovabase64phonegap-plugins

提问by mukama

Am writing a phonegap app for Android and at one point, I save a base64 PNG string as a file. However, I have observed that the string is just dumped into a file and can't be viewed as an image when opened.

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

I'd like to be able to save an image generated from the base64 string.This is what I have:

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

The Javascript (Formated for Phonegap):

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);
}

I tried editing the code to save just the image data but it did't work either. (See below)

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

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

The HTML that triggers everthing:

触发一切的 HTML:

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

Please help. Thank you.

请帮忙。谢谢你。

回答by Simon MacDonald

You just need to set the src of your image to the base 64 data to view the image.

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

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

回答by kathir

here no need to replace base64 string, just set convert string by following:

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

in javascript:

在 JavaScript 中:

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

in jquery:

在jQuery中:

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