How To Scale An Image Down In Android
I am creating an android application and I can add an image. However, what I want to do is scale down the image to fit the ImageButton size. Is there any way to do that? The code I
Solution 1:
Here is some code that might help you:
Replace this code
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = true;
final Uri imageURI = imageReturnedIntent.getData();
final InputStream inStr = getContentResolver().openInputStream(imageURI);
final Bitmap selectImg = BitmapFactory.decodeStream(inStr, null, options);
addPic.setImageBitmap(selectImg);
with the code below
final Uri imageURI = imageReturnedIntent.getData();
final InputStream inStr = new BufferedInputStream(getContentResolver().openInputStream(imageURI));
int height = addPic.getHeight();
int width = addPic.getWidth();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(inStr, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, width, height);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
try {
inStr.reset();
} catch (IOException e) {
e.printStackTrace();
}
Bitmap selectImg = BitmapFactory.decodeStream(inStr, null, options);
addPic.setImageBitmap(selectImg);
And add this function to your class
public int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
For more information you can refer http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
Solution 2:
Use Scale attribute of ImageButton as :
<ImageButton
android:id="@+id/addImage"
android:layout_width="0dp"
android:layout_height="58dp"
android:layout_weight="1"
android:scaleType="fitXY"
android:background="@drawable/ic_social_person" />
Solution 3:
Try using this property on your ImageButton
:
<ImageButton
android:scaleType="fitXY"
... />
Hope this helps :)
Solution 4:
Maybe take out this from your ImageButton xml
android:layout_weight="1"
Post a Comment for "How To Scale An Image Down In Android"