bitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);
时间: 2024-05-27 12:13:08 浏览: 10
This code compresses a bitmap image in JPEG format with a compression quality of 50 and writes the compressed data to an output stream. The output stream can be a file, network socket, or any other type of output destination. The lower the compression quality (i.e., the higher the compression level), the smaller the resulting file size but the lower the image quality. Conversely, a higher compression quality (i.e., lower compression level) results in a larger file size but better image quality.
相关问题
Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
这个错误是由于你在对一个空对象进行操作,导致调用了一个空对象的方法。在这个例子中,你正在尝试对一个空的 Bitmap 对象进行压缩操作,因此发生了这个错误。你需要先检查 Bitmap 对象是否为空,然后再进行相应的操作。可以使用如下代码进行判断:
```
if(bitmap != null){
// 对 Bitmap 对象进行操作
} else {
// Bitmap 对象为空,进行相应的处理
}
```
这样就可以避免调用空对象的方法导致的错误。
java.lang.IllegalStateException: Can't compress a recycled bitmap
这个异常是因为尝试压缩一个已经被回收的位图对象。在Android中,当你使用`recycle()`方法回收一个位图对象后,它的像素数据会被释放并且不能再次使用。如果你尝试对已经回收的位图对象进行压缩操作,就会抛出`java.lang.IllegalStateException: Can't compress a recycled bitmap`异常。
以下是一个演示如何避免这个异常的例子:
```java
Bitmap bitmap = BitmapFactory.decodeFile("path/to/image.jpg");
if (bitmap != null && !bitmap.isRecycled()) {
FileOutputStream outputStream = new FileOutputStream("path/to/compressed_image.jpg");
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream);
outputStream.close();
bitmap.recycle();
}
```
在这个例子中,我们首先使用`BitmapFactory.decodeFile()`方法创建一个位图对象。然后,我们检查位图对象是否为null并且是否已经被回收。如果位图对象没有被回收,我们就可以对它进行压缩操作。在压缩完成后,我们关闭输出流并且回收位图对象。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)