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.Optionsoptions=newBitmapFactory.Options();
options.inScaled = true;
finalUriimageURI= imageReturnedIntent.getData();
finalInputStreaminStr= getContentResolver().openInputStream(imageURI);
finalBitmapselectImg= BitmapFactory.decodeStream(inStr, null, options);
addPic.setImageBitmap(selectImg);
with the code below
finalUriimageURI= imageReturnedIntent.getData();
finalInputStreaminStr=newBufferedInputStream(getContentResolver().openInputStream(imageURI));
intheight= addPic.getHeight();
intwidth= addPic.getWidth();
BitmapFactory.Optionsoptions=newBitmapFactory.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();
}
BitmapselectImg= BitmapFactory.decodeStream(inStr, null, options);
addPic.setImageBitmap(selectImg);
And add this function to your class
publicintcalculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of imagefinalintheight= options.outHeight;
finalintwidth= options.outWidth;
intinSampleSize=1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and widthfinalintheightRatio= Math.round((float) height / (float) reqHeight);
finalintwidthRatio= 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
:
<ImageButtonandroid: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"