向系统相册中插入图片调用此方法时,相册中会出现两张一样的图片
MediaStore.Images.Media.insertImage
一张图片是原图一张图片是缩略图。表现形式为:android4.4.4系统中插入的缩略图和原图在sdcard根目录下的DCIM文件夹这种,Android5.0以上的机型插入的缩略图在sdcard根目录下的Pictures文件夹下,原图存放在DCIM文件夹下。
导致这个问题的原因查看代码后知道在插入原图的同时系统自动生成了一个缩略图并保存再相应的文件目录下,代码如下。
解决办法是把红色框框中的代码注释掉就好了。
整理后的代码如下:
public void insertImage(String fileName) {
// Toast.makeText(this, "插入图片", Toast.LENGTH_LONG).show();
try { insertImageW(getContentResolver(), fileName, new File(fileName).getName(),
new File(fileName).getName());
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(new File(fileName));
intent.setData(uri);
sendBroadcast(intent);
MediaScannerConnection.scanFile(this, new String[] { fileName }, new String[] { "image/jpeg" },
new MediaScannerConnection.MediaScannerConnectionClient() {
@Override
public void onMediaScannerConnected() { } @Override
public void onScanCompleted(String path, Uri uri) {
photoGalleryFragment.addCaptureFile(path);
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public String insertImageW(ContentResolver cr, String imagePath, String name, String description)
throws FileNotFoundException {
// Check if file exists with a FileInputStream
FileInputStream stream = new FileInputStream(imagePath);
try {
Bitmap bm = BitmapFactory.decodeFile(imagePath);
String ret = insertImageT(cr, bm, name, description);
bm.recycle();
return ret;
} finally {
try {
stream.close();
} catch (IOException e) {
}
}
} public String insertImageT(ContentResolver cr, Bitmap source, String title, String description) {
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, title);
values.put(Images.Media.DESCRIPTION, description);
values.put(Images.Media.MIME_TYPE, "image/jpeg"); Uri url = null;
String stringUrl = null; /* value to be returned */ try {
String CONTENT_AUTHORITY_SLASH = "content://" + "media" + "/";
Uri uri = Uri.parse(CONTENT_AUTHORITY_SLASH + "external" + "/images/media");
url = cr.insert(uri, values);
} catch (Exception e) {
Log.e("heheh", "Failed to insert image", e);
if (url != null) {
cr.delete(url, null, null);
url = null;
}
} if (url != null) {
stringUrl = url.toString();
} return stringUrl;
}