Android bitmap 按比例缩放

首先得到原bitmap 宽高

int width = bitmap.getWidth();
int height = bitmap.getHeight();

得到新的宽高与原宽高的比例

float scaleWidth = (newWidth)/width;
float scaleHeight = (newHeight)/height;

使用 Matrix 类

 Matrix matrix = new Matrix();
 matrix.postScale(scaleWidth,ScaleHeight);

生成新的Bitmap

 BItmap newBitmap = Bitmap.createBitmap(bitmap,0,0,width,height,martix,false);
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Android中,你可以使用BitmapFactory.Options类的inSampleSize属性来实现同时等比例缩放和压缩Bitmap的功能。具体步骤如下: 1. 通过BitmapFactory.decodeFile或BitmapFactory.decodeStream方法获取原始Bitmap对象。 2. 计算出缩放比例,公式为:inSampleSize = 原始宽度 / 目标宽度(或者原始高度 / 目标高度,取两者中比例较小的值)。 3. 设置BitmapFactory.Options对象的inSampleSize属性为计算出的缩放比例。 4. 通过BitmapFactory.decodeFile或BitmapFactory.decodeStream方法,传入设置了inSampleSize属性的BitmapFactory.Options对象,获取压缩后的Bitmap对象。 下面是示例代码: ```java public static Bitmap compressBitmap(String filePath, int targetWidth, int targetHeight) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); int width = options.outWidth; int height = options.outHeight; int inSampleSize = 1; if (width > targetWidth || height > targetHeight) { int widthRatio = Math.round((float) width / (float) targetWidth); int heightRatio = Math.round((float) height / (float) targetHeight); inSampleSize = Math.min(widthRatio, heightRatio); } options.inJustDecodeBounds = false; options.inSampleSize = inSampleSize; Bitmap compressedBitmap = BitmapFactory.decodeFile(filePath, options); return compressedBitmap; } ``` 在上述示例代码中,compressBitmap方法接受三个参数:文件路径、目标宽度和目标高度。方法内部首先通过设置options.inJustDecodeBounds为true来获取原始Bitmap对象的宽度和高度,然后根据目标宽度和高度计算出缩放比例inSampleSize,最后再通过设置options.inSampleSize属性来获取压缩后的Bitmap对象。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值