Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert base64 image data to an image file(.png) and save it to Local file system [closed]

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

like image 706
sachin Avatar asked Jan 18 '13 07:01

sachin


People also ask

Can a png be Base64?

data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even). It's not "instead of providing an URL".


Video Answer


2 Answers

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;
    }
}
like image 182
Raj Avatar answered Oct 06 '22 01:10

Raj


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();
like image 36
Misha Bhardwaj Avatar answered Oct 06 '22 01:10

Misha Bhardwaj