Created
May 22, 2015 21:37
-
-
Save javiergamarra/beba9320a8eb98f94fa8 to your computer and use it in GitHub Desktop.
Classic code for resizing an image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static byte[] decodeSampledBitmapFromResource(String path, int reqWidth, int reqHeight) { | |
// First decode with inJustDecodeBounds=true to check dimensions | |
final BitmapFactory.Options options = new BitmapFactory.Options(); | |
options.inJustDecodeBounds = true; | |
BitmapFactory.decodeFile(path, options); | |
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); | |
options.inJustDecodeBounds = false; | |
Bitmap bitmap = BitmapFactory.decodeFile(path, options); | |
ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream(); | |
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayBitmapStream); | |
return byteArrayBitmapStream.toByteArray(); | |
} | |
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { | |
final int height = options.outHeight; | |
final int width = options.outWidth; | |
int inSampleSize = 1; | |
if (height > reqHeight || width > reqWidth) { | |
final int halfHeight = height / 2; | |
final int halfWidth = width / 2; | |
// Calculate the largest inSampleSize value that is a power of 2 and keeps both | |
// height and width larger than the requested height and width. | |
while ((halfHeight / inSampleSize) > reqHeight | |
&& (halfWidth / inSampleSize) > reqWidth) { | |
inSampleSize *= 2; | |
} | |
} | |
return inSampleSize; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment