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
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".
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;
}
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With