android缩放图片到指定大小显示的两种方法

2021-01-16  本文已影响0人  duoduo7628

第一种用BitmapFactory.Options

    private Bitmap scaleCreateBitmap(String path, int targetWidth, int targetHeight) {

        path = "/storage/emulated/0/arhomework/test_get_answer/key_store_bitmap_file.jpg";
        targetWidth = 100;
        targetHeight = 100;

        int sampleSize = 0;
        int sampleSizeIndex = 0;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bitmap = null;
        do {

            sampleSize = (int) Math.pow(2, sampleSizeIndex++);
            options.inSampleSize = sampleSize;
            BitmapFactory.decodeFile(path, options);

        } while (options.outWidth > targetWidth || options.outHeight > targetHeight);

        options.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(path, options);

        Log.e("testCreateBitmap", "sampleSize = " + sampleSize + "  bitmap.getWidth() = " + bitmap.getWidth() + "  bitmap.getHeight() = " + bitmap.getHeight());

        return bitmap;
    }

先用options.inJustDecodeBounds = true;只加载获得图片的宽高,获得相应的sampleSize,然后再次解析即可。
但是这样有个坑是,没办法获得指定大小的图,只能是2的幂次方。所以最终获取的宽高小于等于指定大小。

第二种 用矩阵Matrix ,可以缩放到指定大小。

    private Bitmap createScaleBitmap(String path, int targetWidth, int targetHeight) {

        Bitmap bmpSrc = BitmapFactory.decodeFile(path);


        int srcWidth = bmpSrc.getWidth();
        int srcHeight = bmpSrc.getHeight();
        float scale = 1;
        float widthScale = targetWidth * 1.0f / srcWidth;
        float heightScale = targetHeight * 1.0f / srcHeight;

        if(widthScale < heightScale){

            scale = widthScale;
        }else{

            scale = heightScale;
        }

        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale, 0, 0);
        // 如需要可自行设置 Bitmap.Config.RGB_8888 等等
        Bitmap bmpRet = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bmpRet);
        // 如需要可自行设置 Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG 等等
        Paint paint = new Paint();
        canvas.drawBitmap(bmpSrc, matrix, paint);
        return bmpRet;
    }

根据scale

    private Bitmap createScaleBitmap(Bitmap bmpSrc, float scale) {
        int srcWidth = bmpSrc.getWidth();
        int srcHeight = bmpSrc.getHeight();
        int dstWidth = Math.round(srcWidth * scale);
        int dstHeight = Math.round(srcHeight * scale);

        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale, 0, 0);
        // 如需要可自行设置 Bitmap.Config.RGB_8888 等等
        Bitmap bmpRet = Bitmap.createBitmap(dstWidth, dstHeight, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bmpRet);
        // 如需要可自行设置 Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG 等等
        Paint paint = new Paint();
        canvas.drawBitmap(bmpSrc, matrix, paint);
        return bmpRet;
    }
上一篇下一篇

猜你喜欢

热点阅读