[英]Save Bitmap as a jpeg image
在我的android應用程序中,我生成一個qr代碼,然后將其另存為jpeg圖像,我使用以下代碼:
imageView = (ImageView) findViewById(R.id.iv);
final Bitmap bitmap = getIntent().getParcelableExtra("pic");
imageView.setImageBitmap(bitmap);
save = (Button) findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOutputStream = null;
File file = new File(path + "/Captures/", "screen.jpg");
if (!file.exists()) {
file.mkdirs();
}
try {
fOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOutputStream);
fOutputStream.flush();
fOutputStream.close();
MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
}
});
但它總是在行上捕獲異常:
fOutputStream = new FileOutputStream(file);
是什么引起了這個問題?
是什么引起了這個問題?
語句file.mkdirs();
用名字screen.jpg
創建了一個目錄。 當找到具有該名稱的目錄時, FileOutputStream
無法創建名稱為screen.jpg
的文件。 所以你得到:
java.io.FileNotFoundException
您能否替換以下代碼段:
File file = new File(path + "/Captures/", "screen.jpg");
if (!file.exists()) {
file.mkdirs();
}
通過以下片段:
String dirPath = path + "/Captures/";
File dirFile = new File(dirPath);
if(!dirFile.exists()){
dirFile.mkdirs();
}
File file = new File(dirFile, "screen.jpg");
看看結果嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.