Skip to content

Instantly share code, notes, and snippets.

@talhahasanzia
Last active October 1, 2018 09:14
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 talhahasanzia/84873ec8a5112168f0d8f6486d89b88b to your computer and use it in GitHub Desktop.
Save talhahasanzia/84873ec8a5112168f0d8f6486d89b88b to your computer and use it in GitHub Desktop.
private File getCompressedFile(String filePath, Context context) {
int compressionRatio = 50;
float scaleDownFactor = 0.5f;
File inputFile = new File(filePath);
// by default it has same file reference as original one
// if create temp file fails it will have some file
File outputFile=new File(filePath);
try {
File outputDir = context.getCacheDir(); // context being the Activity pointer
outputFile = File.createTempFile("temp", ".jpeg", outputDir);
Bitmap bitmap = BitmapFactory.decodeFile(inputFile.getPath());
Bitmap resized = Bitmap.createScaledBitmap(bitmap, Math.round(bitmap.getWidth() * scaleDownFactor), Math.round(bitmap.getHeight() * scaleDownFactor), true);
resized.compress(Bitmap.CompressFormat.JPEG, compressionRatio, new FileOutputStream(outputFile));
} catch (IOException e) {
e.printStackTrace();
}
return outputFile;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment