前言

Android项目中经常需要调整图片的尺寸大小以适应存储、传输和图片处理等需求。虽然Android API中提供了一些缩放图片的方法,在调试中发现,使用Android API中的CanvasBitmapFactoryThumbnailUtils等类的相关方法缩放图片,锯齿感明显,图像质量不高。

这里记录一下对图片的缩放代码,方便自己查阅。

PS: 本文摘抄的。

正文

使用Canvas

创建一个Canvas对象,使用Canvas的drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint)方法,根据Rect dst指定bitmap绘制在canvas上的位置,从而改变bitmap的大小。需要注意的是,使用这种方法时,为了得到更好效果的输出,要添加抗锯齿处理。

/**
     * 使用Canvas
     * @param bitmap 原始的Bitmap
     * @param rect Bitmap被缩放放置的Rect
     * @return 缩放后的Bitmap
     */
    public static Bitmap scaleCanvas(Bitmap bitmap, Rect rect) {
        Bitmap newBitmap = Bitmap.createBitmap(rect.width(), rect.height(), Bitmap.Config.ARGB_8888);//创建和目标相同大小的空Bitmap
        Canvas canvas = new Canvas(newBitmap);
        Paint paint = new Paint();
        Bitmap temp = bitmap;

        //针对绘制bitmap添加抗锯齿
        PaintFlagsDrawFilter pfd= new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG);
        paint.setFilterBitmap(true); //Bitmap进行滤波处理
        paint.setAntiAlias(true);//设置抗锯齿
        canvas.setDrawFilter(pfd);
        canvas.drawBitmap(temp, null, rect, paint);

        return newBitmap;
    }

使用Matrix

Bitmap实际上就是由像素点组成的矩阵,在Android中的Matrix主要用于对图像缩放、平移和旋转处理操作,Matrix对象调用postScale(float sx, float sy)方法设置缩放,在Bitmap的createBitmap(Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter)方法中将Matrix对象传入,即可根据Matrix规则生成新的Bitmap。

    /**
     * 使用Matrix
     *
     * @param bitmap 原始的Bitmap
     * @param width  目标宽度
     * @param height 目标高度
     * @return 缩放后的Bitmap
     */
    public Bitmap scaleMatrix(Bitmap bitmap, int width, int height) {
        float scaleW = width * 1.0f / bitmap.getWidth();
        float scaleH = height * 1.0f / bitmap.getHeight();
        Matrix matrix = new Matrix();
        matrix.postScale(scaleW, scaleH);// 长和宽放大缩小的比例
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

使用ThumbnailUtils

ThumbnailUtils是Android API提供的获取缩略图的工具类,所以可以很容易地获得缩放后的Bitmap,使用该类中extractThumbnail(Bitmap source, int width, int height)方法返回获得缩放的Bitmap,该方法的参数中,source指输入待缩放的原始Bitmap,width和height分别指目标宽度和高度。

ThumbnailUtils.extractThumbnail(bitmap, width, height);

参考文章

  1. Android中缩放图片的方法_TuGeLe的博客-CSDN博客_android 图片缩放

相关文章

暂无评论

none
暂无评论...