Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize an image i picked from the gallery in android?

I am building an android where. Inside of one activity I have an image button. When I click on it the gallery opens up and I can choose an image. Then I set that image as the new image for the image button. The problem is the image appears way too big inside my activity. How can I make it fit into my image button?

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

    switch(requestCode) { 
    case SELECT_PHOTO:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();


            Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);

            mImageButton.setImageBitmap(yourSelectedImage);
        }
    }
}
like image 379
user1420042 Avatar asked May 27 '12 11:05

user1420042


1 Answers

Refer this LINK

Use: Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)

or use these method::

public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
    int width = bm.getWidth();
    int height = bm.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;

    // create a matrix for the manipulation
    Matrix matrix = new Matrix();

    // resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);

    // recreate the new Bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);

    return resizedBitmap;
}
like image 172
Shankar Agarwal Avatar answered Oct 05 '22 22:10

Shankar Agarwal