如何在android中保存图像文件?

时间:2016-04-23 08:10:04

标签: android

我想在android中保存图像文件,系统库可以查看或删除它。我使用以下代码,但发现gallery无法找到它,更不用说查看或删除它了。有什么建议吗?

private void saveImage(Bitmap finalBitmap){
    String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
    File myDir = new File(root + getString(R.string.folderName));
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-"+ n +".png";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        out.flush();
        out.close();
        sendBroadcast(new Intent(
                Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://" + Environment.getExternalStorageDirectory())));

    } catch (Exception e) {
        e.printStackTrace();
    }
}

2 个答案:

答案 0 :(得分:0)

如果您希望图库扫描并添加您的应用图片文件夹,请在保存图片后尝试使用此代码。

MediaScannerConnection.scanFile(this,new String[] { imagePath }, null,
    new MediaScannerConnection.OnScanCompletedListener() {

    public void onScanCompleted(String path, Uri uri) {
    if(Config.LOG_DEBUG_ENABLED) {
        // if required do something after the scan complet
        Log.d(TAG, "scanned : " + path);
    }
}

答案 1 :(得分:0)

只需更改此行:

sendBroadcast(new Intent(
                Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://" + Environment.getExternalStorageDirectory())));

要:

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, 
             Uri.parse("file://"+ Environment.getExternalStorageDirectory())));