在Android中将图片添加到图库

时间:2014-09-11 10:04:25

标签: android image broadcast

我有一个应用程序可以完成两件事:

  • 它通过相​​机应用程序捕获照片并将其保存到图库 - 这个工作
  • 从图片中生成.gif并将其保存在ExternalStoragePublicDirectory中 - 这不起作用

这是我用来将文件添加到图库的方法:

public static void galleryAddPic(Context context, String currentPhotoPath) {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(currentPhotoPath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    context.sendBroadcast(mediaScanIntent);
}

我已经在某处看过这在Android Api 19上无效,任何人都可以确认吗? 有没有比上面的方法更好的解决方案添加图片到图库? 干杯

1 个答案:

答案 0 :(得分:1)

尝试以下代码

private void SaveImage(Bitmap finalBitmap) {

    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/saved_images");    
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-"+ n +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete (); 
    try {
           FileOutputStream out = new FileOutputStream(file);
           finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
           out.flush();
           out.close();

    } catch (Exception e) {
           e.printStackTrace();
    }
}
相关问题