Android向系统相册中插入图片,相册中会出现两张 一样的图片(只是图片大小不一致)
向系统相册中插入图片调用此方法时,相册中会出现两张一样的图片
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; }
分类:
Android
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
2013-09-27 Android 混淆打包