android bitmap压缩压缩方式
时间: 2023-10-12 11:05:22 浏览: 187
Android中常用的Bitmap压缩方式有以下几种:
质量压缩:使用Bitmap的compress方法,将图片的质量压缩至指定的大小,但是图片的像素大小不会改变。
尺寸压缩:使用BitmapFactory.Options的inSampleSize属性,将图片的像素大小压缩至指定的尺寸,但是图片的质量会有所下降。
RGB_565压缩:使用BitmapFactory.Options的inPreferredConfig属性,将图片的像素格式从ARGB_8888压缩至RGB_565,减少内存占用。
JNI压缩:使用JNI调用C/C++代码进行图片压缩,可以压缩至指定的像素大小和质量,但是需要对C/C++有一定的了解。
需要根据具体情况选择合适的压缩方式。
相关问题
android 压缩bitmap时同时等比例缩放
在Android中,你可以使用BitmapFactory.Options类的inSampleSize属性来实现同时等比例缩放和压缩Bitmap的功能。具体步骤如下:
- 通过BitmapFactory.decodeFile或BitmapFactory.decodeStream方法获取原始Bitmap对象。
- 计算出缩放比例,公式为:inSampleSize = 原始宽度 / 目标宽度(或者原始高度 / 目标高度,取两者中比例较小的值)。
- 设置BitmapFactory.Options对象的inSampleSize属性为计算出的缩放比例。
- 通过BitmapFactory.decodeFile或BitmapFactory.decodeStream方法,传入设置了inSampleSize属性的BitmapFactory.Options对象,获取压缩后的Bitmap对象。
下面是示例代码:
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对象。
android Bitmap方法
Android中有许多Bitmap相关的方法,用于处理图像数据。以下是一些常用的Bitmap方法:
创建Bitmap对象:
Bitmap.createBitmap(int width, int height, Bitmap.Config config)
: 创建指定宽度和高度的Bitmap对象。Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)
: 创建指定宽度和高度的缩放Bitmap对象。
加载Bitmap:
BitmapFactory.decodeResource(Resources res, int resId)
: 从资源文件中加载Bitmap对象。BitmapFactory.decodeFile(String pathName)
: 从文件路径中加载Bitmap对象。
获取和设置像素:
getPixel(int x, int y)
: 获取指定坐标处的像素值。setPixel(int x, int y, int color)
: 设置指定坐标处的像素值。
处理图像:
createBitmap(Bitmap source, int x, int y, int width, int height)
: 从现有的Bitmap对象中创建一个新的Bitmap对象,截取指定区域的图像。copy(Bitmap.Config config, boolean isMutable)
: 创建一个拷贝当前Bitmap对象的新对象。
压缩和保存Bitmap:
compress(Bitmap.CompressFormat format, int quality, OutputStream stream)
: 将Bitmap对象压缩并保存到输出流中。compress(Bitmap.CompressFormat format, int quality, String path)
: 将Bitmap对象压缩并保存到指定路径。
这些只是Bitmap类中的一些常用方法,还有其他更多的方法可根据具体需求进行使用。
阅读全文
相关推荐
















