android - 将图像转换为位图并减小其大小

标签 android bitmap scaling image-resizing bitmapimage

我研究过许多不同的方法来创建缩小尺寸的图像位图,但它们都无法正常工作/我需要一些不同的方法。

这有点难以解释:-)

我需要的是保持图片比例但小于特定大小的位图 - 例如 1mb 或像素尺寸的等效值(因为此位图需要添加为 putExtra() 用于 Intent )。

我目前遇到的问题:

我看过的大多数方法都创建了位图的缩放版本。所以:图像-> Bitmap1(未缩放)-> Bitmap2(缩放)。但是如果图像的分辨率非常高,则缩小得不够。我认为解决方案是创建一个精确大小的位图,以便可以充分降低任何分辨率。

但是,此方法的副作用是已经小于所需大小的图像将被调整大小(或者调整大小不起作用?)。所以需要有一个“if”来检查图像是否可以在不调整大小的情况下转换为位图。

我不知道该怎么做,所以非常感谢您的帮助! :-)

这就是我目前正在使用的(我不希望它这样做):

// This is called when an image is picked from the gallery
@Override
    public void onActivityResult(int requestCode, int resultCode,
            Intent imageReturnedIntent) {
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

        switch (requestCode) { 
        case 0:
            if (resultCode == Activity.RESULT_OK) {
                selectedImage = imageReturnedIntent.getData();
                viewImage = imageReturnedIntent.getData();

                try {
                    decodeUri(selectedImage);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                iv_preview.setImageBitmap(mImageBitmap);
            }
            break; // The rest is unnecessary

这是当前正在缩放的​​部分:

private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException { 


        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true; //
        BitmapFactory.decodeStream(getActivity().getContentResolver()
                .openInputStream(selectedImage), null, o);

        // The new size we want to scale to
        final int REQUIRED_SIZE = 260; // Is this kilobites? 306

        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
                break;
            }
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }


        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        o2.inScaled = false; // Better quality?
        mImageBitmap = BitmapFactory.decodeStream(getActivity()
                .getContentResolver().openInputStream(selectedImage), null, o2);
        return BitmapFactory.decodeStream(getActivity().getContentResolver()
                .openInputStream(selectedImage), null, o2);

    }

如果有什么需要解释的,请说。

谢谢

最佳答案

调用方式:

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

        Uri selectedImage = data.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 picturePath = cursor.getString(columnIndex);
        cursor.close();
        pho1.setImageBitmap(decodeSampledBitmapFromResource(picturePath,
                80, 60));

方法:

public static int calculateInSampleSize(BitmapFactory.Options options,
            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and
            // width
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = 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;
    }

    public static Bitmap decodeSampledBitmapFromResource(String path,
            int reqWidth, int reqHeight) {
        Log.d("path", path);
        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(path, options);
    }

关于android - 将图像转换为位图并减小其大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17722804/

相关文章:

android - 自动更改 Android 模拟器区域设置

Android Drawable getBitmap 大小不匹配

android - 如何从图库中选择图像并将其设置为位图

sprite-kit - Sprite Kit 中的 9 切片缩放

mysql - 如何有效地更改具有数百万条目的表上的 MySQL 表结构?

android - Imageview 缩放方法 "centercrop"作为代码

android - 如何以编程方式将 9 补丁图像重新应用到 ImageView?

java - 在特定时间切换 FLAG_KEEP_SCREEN_ON

android - 如何处理 diffrent-2 屏幕分辨率 android 的 xml UI

android - 如何使用 Volley Library 从缓存中获取图像位图