Android调整图库大小

时间:2013-11-27 19:50:01

标签: android

当我从画廊中挑选一张图片时,它太大了,我需要调整它的大小。任何人都可以就如何实现这一目标向我提出建议吗?

见下面的代码:

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == REQUEST_GALLERY && resultCode == RESULT_OK) {
        Uri uri = data.getData();  
        try {
            bitmap = Media.getBitmap(this.getContentResolver(), uri);



        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}





        imageView.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {               
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_GALLERY);

                imageView.setImageBitmap(bitmap);

            }
        });

1 个答案:

答案 0 :(得分:0)

这篇文章为您提供了一些优秀的样本:How to Resize a Bitmap in Android?

在您的情况下,此方法有帮助

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;
}

修改

同样来自同一篇文章,这更符合您的需求

Bitmap resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, false);

更新

您可以这样使用代码:

// Set the new width and height you want
int newWidth;
int newHeight;
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == REQUEST_GALLERY && resultCode == RESULT_OK) {
        Uri uri = data.getData();  
        try {
            bitmap = Media.getBitmap(this.getContentResolver(), uri);
            bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}