Skip to content

Instantly share code, notes, and snippets.

@Ankit-Slnk
Last active February 23, 2022 16:18
Show Gist options
  • Save Ankit-Slnk/410f4e465534ea050771314a2560f914 to your computer and use it in GitHub Desktop.
Save Ankit-Slnk/410f4e465534ea050771314a2560f914 to your computer and use it in GitHub Desktop.
public static File bitmapToFile(Bitmap bitmap) {
// File name like "image.png"
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String fileNameToSave = sdf.format(new Date());
//create a file to write bitmap data
File file = null;
try {
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator + fileNameToSave + ".png");
file.createNewFile();
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos); // YOU can also save it in JPEG
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(file);
fos.write(bitmapdata);
fos.flush();
fos.close();
Log.e("exists", file.exists() + "");
return file;
} catch (Exception e) {
e.printStackTrace();
return file; // it will return null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment