在Android中将Bitmap大小减小到指定像素

33

我想将位图图像的大小减小到最大640px。例如,我的位图图像大小为1200x1200像素...如何将其减小到640px。

4个回答

102

如果您传递位图的宽度高度,则使用以下代码:

public Bitmap getResizedBitmap(Bitmap image, int bitmapWidth, int bitmapHeight) {
    return Bitmap.createScaledBitmap(image, bitmapWidth, bitmapHeight, true);
}

如果您想保持位图的比例不变,但将其缩小到最大边长,可以使用:

public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
        int width = image.getWidth();
        int height = image.getHeight();

        float bitmapRatio = (float) width / (float) height;
        if (bitmapRatio > 1) {
            width = maxSize;
            height = (int) (width / bitmapRatio);
        } else {
            height = maxSize;
            width = (int) (height * bitmapRatio);
        }

        return Bitmap.createScaledBitmap(image, width, height, true);
}

8
谢谢提供这段代码。然而存在一个错误,你需要检查的是"if (bitmapRatio > 1)"而不是"if (bitmapRatio > 0)"。即使高度更大,比率也不会为负数。 - ClemM
我在各处看到这个解决方案,但是为什么它会裁剪我的位图?我只剩下左上角的部分,而且它也向屏幕右侧移动了。 - Sermilion

15

使用此方法

 /** getResizedBitmap method is used to Resized the Image according to custom width and height 
  * @param image
  * @param newHeight (new desired height)
  * @param newWidth (new desired Width)
  * @return image (new resized image)
  * */
public static Bitmap getResizedBitmap(Bitmap image, int newHeight, int newWidth) {
    int width = image.getWidth();
    int height = image.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(image, 0, 0, width, height,
            matrix, false);
    return resizedBitmap;
}

13

或者你可以这样做:

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

将 filter 参数设为 false 会导致图像出现方块状、像素化。

将 filter 参数设为 true 则能使边缘更加平滑。


你怎么使用这个方法?这个方法不存在! - coolcool1994
5
你是否给它点了踩? 你的意思是它不存在吗?Bitmap.createScaledBitmap从api lvl 1就存在了。 - Marko Niciforovic

0

以下是可工作的代码,将位图图像分辨率(像素)缩小到所需值...

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.Toast;

public class ImageProcessActivity extends AppCompatActivity {


    private static final String TAG = "ImageProcessActivity";
    private static final String IMAGE_PATH = "/sdcard/DCIM/my_image.jpg";

    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {

        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

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

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {

                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    public static Bitmap decodeSampleDrawableFromFile(String file, int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(file, options);

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

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_process);

        new AsyncTask<Object, Object, Bitmap>() {

            @Override
            protected Bitmap doInBackground(Object... objects) {

                try {

                    return decodeSampleDrawableFromFile(IMAGE_PATH, 640, 640);

                } catch (Exception e) {

                    e.printStackTrace();

                }
                return null;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                super.onPostExecute(bitmap);

                ((ImageView) findViewById(R.id.img)).setImageBitmap(bitmap);
            }
        }.execute();
    }
}

步骤:
  1. 获取Bitmap.Options(图像信息)。

  2. 将大小采样到所需的样本大小。

  3. 使用给定选项(所需分辨率)从图像文件加载到bitmap对象中。但是,请在后台线程中执行此操作。

  4. 在UI线程上将Bitmap图像加载到ImageView中(onPostExecute())。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接