public void handleActivityResult(int requestCode, int resultCode, Intent data) { // 处理ActivityResult的逻辑 ImageView imageView= getView().findViewById(R.id.book_cover); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { Uri uri = data.getData(); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri); // 将图片显示在 ImageView 控件中 imageView.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } } FileOutputStream fos = null; try { fos = openFileOutput("book_cover.jpg", Context.MODE_PRIVATE); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fos != null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } } }bitmap和openfileoutput为红
时间: 2023-06-23 11:09:19 浏览: 270
这段代码存在两个问题:
1. `bitmap` 变量未定义,需要在 `try` 代码块外定义 `Bitmap` 类型的变量 `bitmap`,并在 `try` 代码块内对其进行赋值。
2. `openFileOutput()` 方法不是 `Activity` 类的方法,需要使用 `getActivity().openFileOutput()` 来获取 `FileOutputStream` 对象。
修改后的代码如下:
```
public void handleActivityResult(int requestCode, int resultCode, Intent data) {
// 处理ActivityResult的逻辑
ImageView imageView = getView().findViewById(R.id.book_cover);
Bitmap bitmap = null;
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
// 将图片显示在 ImageView 控件中
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream fos = null;
try {
fos = getActivity().openFileOutput("book_cover.jpg", Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文