2016-11-30 76 views
0

考虑到我要保存在手机上的公共库的特殊文件夹的位图,我尝试这样做:如何将位图保存为PNG到图库中的特定文件夹?

public static void saveToGallery(Context context, Bitmap bitmap) { 
    File path = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), File.separator + "FolderForMyApp"); 
    path.mkdirs(); 
    File imageFile = new File(path, "image_name.png"); 
    FileOutputStream out = null; 
    try { 
     out = new FileOutputStream(imageFile); 
     bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); 
     out.flush(); 
     out.close(); 
    } 
    catch (IOException e) { 
     Log.w(TAG, "Could not resolve file stream: " + e); 
    } 
} 

但是实际上它并不在图库中显示出来。我究竟做错了什么?

+1

https://stackoverflow.com/questions/32789157/how-to-write-files-to-external-public-storage-in-android-so-that-they-are-visibl – CommonsWare

+0

@CommonsWare就是这样正确添加行'MediaScannerConnection.scanFile(context,new String [] {imageFile.getAbsolutePath()},new String [] {“image/png”},null);'? – KaliMa

+1

这应该工作。请注意,这项工作是异步的,无论是在更新'MediaStore'方面,还是任何给定的图库类型的应用都必须基于'MediaStore'更改来更新其UI。 – CommonsWare

回答

0

它不会出现在画廊,因为你必须刷新库,所以它知道有关新的文件

// Tell the media scanner about the new file so that it is 
// immediately available to the user. 
MediaScannerConnection.scanFile(this, 
     new String[] { file.toString() }, null, 
     new MediaScannerConnection.OnScanCompletedListener() { 
    public void onScanCompleted(String path, Uri uri) { 
     Log.i("ExternalStorage", "Scanned " + path + ":"); 
     Log.i("ExternalStorage", "-> uri=" + uri); 
    } 
}); 

Sry基因有关的格式。我在打电话。

相关问题