在Android10.0中进行图片保存时,运行这一句代码:
MediaStore.Images.Media.insertImage(MainActivity.this.getContentResolver(), storepath, imgpath, null)
会出现如下错误:
java.lang.IllegalArgumentException: MIME type application/octet-stream cannot be inserted into content://media/external/images/media; expected MIME type under image/
程序闪退,但是图片可以保存在文档中。请问这个问题怎么解决?
保存图片的整个函数如下:
public void saveimg(){
if (bitmap2==null){
Toast toast=Toast.makeText(MainActivity.this,"图像尚未处理,无法保存",Toast.LENGTH_SHORT);
toast.show();
}
else {
final MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(this).builder()
.setTitle("请输入")
.setEditText("");
myAlertInputDialog.setPositiveButton("确认", new View.OnClickListener() {
@Override
public void onClick(View v) {
myAlertInputDialog.dismiss();
String storepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures";
String imgpath = myAlertInputDialog.getResult().toString() + ".jpg";
FileOutputStream fos = null;
try {
File file = new File(storepath, imgpath);
fos = new FileOutputStream(file);
bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
MediaStore.Images.Media.insertImage(MainActivity.this.getContentResolver(), storepath, imgpath, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + storepath + "/"+imgpath)));
}
}).setNegativeButton("取消", new View.OnClickListener() {
@Override
public void onClick(View v) {
myAlertInputDialog.dismiss();
}
});
myAlertInputDialog.show();
}
}
在Android10.0以下的机型都可以正常运行。
试试换其他方法保存图片
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, imgFile.getAbsolutePath());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg(图片类型)");
Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);