Save bitmap to file function
Here is the function which help you
private void saveBitmap(Bitmap bitmap,String path){
if(bitmap!=null){
try {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(path); //here is set your file path where you want to save or also here you can set file object directly
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); // bitmap is your Bitmap instance, if you want to compress it you can compress reduce percentage
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Two example works for me, for your reference.
Bitmap bitmap = Utils.decodeBase64(base64);
try {
File file = new File(filePath);
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
}
catch (Exception e) {
e.printStackTrace();
LOG.i(null, "Save file error!");
return false;
}
and this one
Bitmap savePic = Utils.decodeBase64(base64);
File file = new File(filePath);
File path = new File(file.getParent());
if (savePic != null) {
try {
// build directory
if (file.getParent() != null && !path.isDirectory()) {
path.mkdirs();
}
// output image to file
FileOutputStream fos = new FileOutputStream(filePath);
savePic.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
ret = true;
} catch (Exception e) {
e.printStackTrace();
}
} else {
LOG.i(TAG, "savePicture image parsing error");
}
In kotlin :
private fun File.writeBitmap(bitmap: Bitmap, format: Bitmap.CompressFormat, quality: Int) {
outputStream().use { out ->
bitmap.compress(format, quality, out)
out.flush()
}
}
usage example:
File(exportDir, "map.png").writeBitmap(bitmap, Bitmap.CompressFormat.PNG, 85)
Edit: This was my original answer and its nice, but lately I use this:
fun File.createFileAndDirs() = apply {
parentFile?.mkdirs()
createNewFile()
}
fun File.write(
bitmap: Bitmap, format: Bitmap.CompressFormat = Bitmap.CompressFormat.JPEG, quality: Int = 80
) = apply {
createFileAndDirs()
outputStream().use {
bitmap.compress(format, quality, it)
it.flush()
}
}
It's better because there are some useful defaults in-place and also it creates file if it doesn't exist.
You need an appropriate permission in
manifest.xml
:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
out.flush()
check theout
is not null..String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PhysicsSketchpad"; File dir = new File(file_path); if(!dir.exists()) dir.mkdirs(); File file = new File(dir, "sketchpad" + pad.t_id + ".png"); FileOutputStream fOut = new FileOutputStream(file); bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut); fOut.flush(); fOut.close();