通过bitmap改变图片的大小

有时候需要在项目中改变图片的大小,那么在代码中我们怎么改变图片的大小呢?

下面就讲下实现过程

一、通过BitmapFactory获取原始图片

二、获取图片的宽、高

三、设置想要的宽、高大小

四、计算压缩的比率

五、获得缩放的matrix

六、获取新的bitmap

其实很简单,主要就是api的使用。下面就贴出代码

private Bitmap changeBitmapSize() {

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

int width = bitmap.getWidth();

int height = bitmap.getHeight();

Log.e(“width”,”width:”+width);

Log.e(“height”,”height:”+height);

//设置想要的大小

int newWidth=30;

int newHeight=30;

//计算压缩的比率

float scaleWidth=((float)newWidth)/width;

float scaleHeight=((float)newHeight)/height;

//获取想要缩放的matrix

Matrix matrix = new Matrix();

matrix.postScale(scaleWidth,scaleHeight);

//获取新的bitmap

bitmap=Bitmap.createBitmap(bitmap,0,0,width,height,matrix,true);

bitmap.getWidth();

bitmap.getHeight();

Log.e(“newWidth”,”newWidth”+bitmap.getWidth());

Log.e(“newHeight”,”newHeight”+bitmap.getHeight());

return bitmap;

}

使用的时候直接调用就行。使用示例:

《通过bitmap改变图片的大小》

我的博客:http://blog.csdn.NET/shenshizhong

我的简书:http://www.jianshu.com/users/345daf0211ad/latest_articles

    原文作者:shenshizhong
    原文地址: https://www.jianshu.com/p/f46f42e89b45
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞