经过自己整理,思路来自 stormzhang 的博文
目的是将图片保存到自定义目录下,并在系统图库中展示
一、保存图片到自定义路径
通常情况下,我们对保存图片的处理是这样的:
public static File saveImage(Bitmap bmp) {
File appDir = new File(Environment.getExternalStorageDirectory(), "SelfDefine");
if (!appDir.exists()) {
appDir.mkdir(); //创建文件夹
}
String fileName = System.currentTimeMillis() + ".jpg"; //需要的图片格式
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file); //获取文件流
bmp.compress(CompressFormat.JPEG, 100, fos); //保存成图片
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
这样,图片就被保存到了/sdcard/SelfDefine/路径下了
二、将图片插入系统图库并更新
<code class="language-ruby" data-lang="ruby"><span class="no">MediaStore</span><span class="o">.</span><span class="n">Images</span><span class="o">.</span><span class="n">Media</span><span class="o">.</span><span class="n">insertImage</span><span class="p">(</span><span class="n">getContentResolver</span><span class="p">(),</span> <span class="n">bitmap</span><span class="p">,</span> <span class="s2">"title"</span><span class="p">,</span> <span class="s2">"description"</span><span class="p">);</span></code>
这样就可以通过android系统提供的一个多媒体数据库类:MediaStore,把bitmap图片插入到系统图库中,但是无法指定保存的路径和名称,参数title、description参数只是插入数据库中的字段,真实的图片名称系统会自动分配。
MediaStore.Images.Media.insertImage(getContentResolver(), "image path", "title", "description");
此方法是可以制定目录的,符合我们自定义的要求。
注意,以上方法不会更新图库,需要手工再去更新图库,才可以将图片显示在图库中。
更新图库方法如下:
1、广播扫描SD卡,扫描中不能访问SD卡,体验不好
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
2、扫描指定文件
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File("/sdcard/SelfDefine/image.jpg"))););
3、重写MedisScannerConnectionClient类的 onMediaScannerConnected() onScanCompleted
final MediaScannerConnection msc = new MediaScannerConnection(mContext, new MediaScannerConnectionClient() {
public void onMediaScannerConnected() {
msc.scanFile("/sdcard/SelfDefine/image.jpg", "image/jpg");
}
public void onScanCompleted(String path, Uri uri) {
Log.v(TAG, "scan completed");
msc.disconnect();
}
});
三、两者结合的终极方法
public static void saveImageToGallery(Context context, Bitmap bmp) {
// 首先保存图片
File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(),
file.getAbsolutePath(), fileName, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 最后通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
}