Convert base64 image data to an image file(.pn

2020-07-17 14:58发布

I am having Image data in base64 format, I want to convert this base64 string to image(.PNG) file and save that file to Local file system in my android application. Please suggest a solution for me

2条回答
Juvenile、少年°
2楼-- · 2020-07-17 15:38

Try this.

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;
    }
}
查看更多
做个烂人
3楼-- · 2020-07-17 15:47

To convert this in image file you can use this...

byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
    Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 

and to save it to file system, you can use this:

_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();
查看更多
登录 后发表回答