Search code examples
androidandroid-cameraimageimagebuttonnine-patch

Fit just taken photo into imagebutton


I have an ImageButton, when I press it I can take a picture with my phone. When I take the picture the ImageButtons gets the picture as its source. But the problem is, is that the image doesn't scale down to the dimensions of the ImageButton. It just shows a part of the image in the Imagebutton instead of scaling down. After doing a bit of research I saw you have to use a draw 9 patch. But that is not possible in this case, because the image aren't in my resources, they are made by the user itself.

Can someone help me with this?

My code:

if (requestCode == REQUEST_CAMERA) {
    File f = new File(Environment.getExternalStorageDirectory().toString());
    for (File temp : f.listFiles()) {
        if (temp.getName().equals("temp.jpg")) {
            f = temp;
            break;
        }
    }

    try {
        Bitmap bm;
        BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
        bm = BitmapFactory.decodeFile(f.getAbsolutePath(),btmapOptions);
        // bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
        btnImg.setImageBitmap(bm);
        String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "default";
        f.delete();
        OutputStream fOut = null;
        File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");

        try {
                fOut = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
            fOut.flush();
            fOut.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
            e.printStackTrace();
        }
            }
} 
else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String tempPath = getPath(selectedImageUri, MainActivity.this);
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
btnImg.setImageBitmap(bm);
}

Solution

  • Use ImageView's method setScaleType. Pass ScaleType.CENTER_INSIDE as parameter.

    btnImg.setImageBitmap(bm);
    btnImg.setScaleType(ScaleType.CENTER_INSIDE);