将base64图像数据转换为图像文件(.png)并保存到本地文件系统

5

我有一串以base64格式编码的图像数据,我想将这个字符串转换为图像(.PNG)文件,并将该文件保存到我的Android应用程序中的本地文件系统。请为我提供一个解决方案。

2个回答

21

试试这个。

FileOutputStream fos = null;
try {
    if (base64ImageData != null) {
       fos = context.openFileOutput("imageName.png", Context.MODE_PRIVATE);
       byte[] decodedString = android.util.Base64.decode(base64ImageData, android.util.Base64.DEFAULT);
       fos.write(decodedString);                        
       fos.flush();
       fos.close();             
    }

} catch (Exception e) {

} finally {
    if (fos != null) {
        fos = null;
    }
}

2
要将此转换为图像文件,您可以使用以下方法...
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
    Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 

如果你想将其保存到文件系统中,可以使用以下代码:

_bitmapScaled.compress(Bitmap.CompressFormat.PNG, 100, decodedString);
File f = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "test.png")
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());

// remember close de FileOutput
fo.close();

他肯定是想将实际文本保存为图像吧?将二进制转换的ASCII文本抛入字节数组中并不能实现这一点。 - Jason Robinson
@Misha Bhardwaj,“bytes”变量是什么? - valerybodak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接