Bitmap.CompressFormat有哪些
时间: 2024-01-19 08:03:18 浏览: 19
Bitmap.CompressFormat是一个枚举类,用于指定压缩Bitmap时的格式。Android中支持以下几种压缩格式:
1. JPEG: `Bitmap.CompressFormat.JPEG`
- 优点:压缩后的文件大小较小,支持无损压缩。
- 缺点:不支持透明度,压缩时会有一定的损失。
2. PNG: `Bitmap.CompressFormat.PNG`
- 优点:支持透明度,无损压缩。
- 缺点:压缩后的文件大小较大。
3. WEBP: `Bitmap.CompressFormat.WEBP`
- 优点:支持透明度,有损和无损压缩都可以选择。
- 缺点:在某些设备上可能不支持。
4. GIF: `Bitmap.CompressFormat.GIF`
- 优点:支持动画。
- 缺点:只能保存256色,不支持透明度。
这些压缩格式可根据具体需求选择,例如需要保留透明度时可以选择PNG或WEBP格式,需要较小的文件体积可以选择JPEG格式。
相关问题
ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray();看不懂
这段代码的作用是将一个Bitmap对象压缩成PNG格式的字节数组。具体来说,代码中创建了一个ByteArrayOutputStream对象stream,此对象可以用来将数据写入到字节数组中。然后,通过调用Bitmap对象的compress()方法,将Bitmap对象压缩成PNG格式的数据,并将数据写入到stream对象中。最后,通过调用stream对象的toByteArray()方法,将stream对象中的数据转换成一个字节数组byteArray,以便进行后续的操作。其中,compress()方法的第一个参数指定压缩格式,第二个参数指定压缩质量(0-100之间),这里设置为100表示不进行压缩。
该部分对应代码为 if (imageUri != null) { Bitmap bitmap = BitmapFactory.decodeFile(imageUri.getPath()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos); byte[] bytes = baos.toByteArray(); imageString = Base64.encodeToString(bytes, Base64.DEFAULT); }
根据您提供的代码,问题可能出现在 `BitmapFactory.decodeFile()` 方法中。请确保您传递给该方法的图片文件路径是正确的,并且该文件存在于您的设备上。
如果您确定路径正确,可以尝试使用 `BitmapFactory.Options` 对象来解决该问题。例如:
```java
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imageUri.getPath(), options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
options.inJustDecodeBounds = false;
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
Bitmap bitmap = BitmapFactory.decodeFile(imageUri.getPath(), options);
```
其中 `calculateInSampleSize()` 方法用于计算适当的采样率,以减少加载大型图片时的内存占用。您可以根据您的需求进行调整。
此外,您还可以使用 `try-catch` 块来捕获 `NullPointerException` 异常,并在发生异常时进行处理。例如:
```java
try {
Bitmap bitmap = BitmapFactory.decodeFile(imageUri.getPath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
byte[] bytes = baos.toByteArray();
imageString = Base64.encodeToString(bytes, Base64.DEFAULT);
} catch (NullPointerException e) {
e.printStackTrace();
// 处理异常
}
```