[摘]Android对Bitmap缩放图片的记录

Android2022年11月30日 am11:40发布2年前 (2022)更新 3XCN.COM站长
0 0 0
广告也精彩
目录

前言

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 图片缩放

 历史上的今天

版权声明 1、 本站名称: 91易搜
2、 本站网址: 91es.com3xcn.com
3、 本站文章: 部分来源于网络,仅供站长学习和参考,若侵权请留言
广告也精彩

相关文章

广告也精彩

暂无评论

评论审核已启用。您的评论可能需要一段时间后才能被显示。

暂无评论...

网站升级中

公告

近期网站升级中,可能存在一些bug。欢迎反馈 https://www.91es.com/we.html

本站域名

本站域名 : 91es.com3xcn.com。本站邮箱 : 站长邮箱 i@oorr.cn,通知邮箱we@oorr.cn ,如有更新,请看公告 。