简体   繁体   English

Android调整图库图片大小

[英]Android resize gallery image

When I pick an image from the gallery it is too large and I need to resize it. 从图库中选取图像时,图像太大,需要调整其大小。 Can anyone give me suggestions on how I might be able to accomplish this? 谁能给我关于我如何能够做到这一点的建议?

See code below: 参见下面的代码:

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

            }
        });

This post has some excellent samples for you: How to Resize a Bitmap in Android? 这篇文章为您提供了一些出色的示例: 如何在Android中调整位图的大小?

In your case, this method helps 就您而言,此方法有助于

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

Edit 编辑

Also from the same post, this fits your need in an easier way 同样在同一篇文章中,这可以轻松满足您的需求

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

Update 更新资料

You can use the code in this way: 您可以通过以下方式使用代码:

// 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();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM