Convert base64 image data to an image file(.pn

2020-07-17 15:14发布

问题:

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 7 years ago.

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

回答1:

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


回答2:

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