Skip to content

Instantly share code, notes, and snippets.

@milaptank
Created March 9, 2016 06:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milaptank/3f13558c3f5c38c27ab9 to your computer and use it in GitHub Desktop.
Save milaptank/3f13558c3f5c38c27ab9 to your computer and use it in GitHub Desktop.
public static String saveBitmapToFile(String path) {
try {
File file = new File(path);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
o.inSampleSize = 6;
FileInputStream inputStream = new FileInputStream(file);
BitmapFactory.decodeStream(inputStream, null, o);
inputStream.close();
// The new size we want to scale to
final int REQUIRED_SIZE = 75;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE &&
o.outHeight / scale / 2 >= REQUIRED_SIZE) {
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
inputStream = new FileInputStream(file);
Bitmap selectedBitmap = BitmapFactory.decodeStream(inputStream, null, o2);
inputStream.close();
String externalDir = Environment.getExternalStorageDirectory().toString();
File folder = null;
String fileName = "name" + new Random().nextInt(10);
folder = new File(externalDir + "/NEAction/profile");
fileName = String.format("NE_profile_%s_%s.jpeg", System.currentTimeMillis(), new Random().nextInt(10));
assert folder != null;
if (!folder.exists()) {
folder.mkdirs();
}
File compressedFile = new File(folder.getAbsolutePath(), fileName);
FileOutputStream outputStream = new FileOutputStream(compressedFile);
selectedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
return compressedFile.getAbsolutePath();
} catch (Exception e) {
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment