【发布时间】:2014-09-11 06:52:55
【问题描述】:
我正在使用InputStream 和OutputStream 将图像从res/drawable 保存到Gallery。它工作正常并保存图像。但问题是它不会更新图库中的图像。如果我使用ES File Explorer 检查文件夹,那么我可以在那里看到图像。我还检查了ddms,它也会在write 代码执行后立即更新那里的图像。
如果我保存服务器图像,它会正常工作。如何防止这个问题?我想在图像保存后立即更新图库。
我也尝试MediaScanner 扫描文件夹但没有效果。
我的代码:
Toast.makeText(context, "Downloading Image...\nPlease Wait.",
Toast.LENGTH_LONG).show();
File direct = new File(Environment.getExternalStorageDirectory()
+ "/Images");
if (!direct.exists()) {
direct.mkdirs();
}
DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy-HHmmss");
Date date = new Date();
String CurrentDateTime = dateFormat.format(date);
InputStream input = null;
OutputStream output = null;
try {
input = context.getResources().openRawResource(
context.getResources().getIdentifier(
"@drawable/" + picName, "drawable",
context.getPackageName()));
output = new FileOutputStream(direct + "/" + "IMG-"
+ CurrentDateTime + ".jpg");
byte[] buf = new byte[1024];
int len;
while ((len = input.read(buf)) > 0) {
output.write(buf, 0, len);
}
MediaScannerConnection.scanFile(context,
new String[] { direct.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Toast.makeText(context, "Image Saved.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.e("Internal Image Save Error->", e.toString());
Toast.makeText(context,
"Couldn't Save Image.\nError:" + e.toString() + "",
Toast.LENGTH_LONG).show();
} finally {
try {
if (input != null) {
input.close();
}
if (output != null) {
output.close();
}
} catch (IOException ignored) {
Log.e("Internal Image Save Error->", ignored.toString());
Toast.makeText(
context,
"Couldn't Save Image.\nError:" + ignored.toString()
+ "", Toast.LENGTH_LONG).show();
}
}
【问题讨论】:
-
@ZerO,我的帖子不是关于如何保存图像的。这是关于画廊更新。
-
是的。现在阅读副本中的内容...
标签: android inputstream android-drawable outputstream android-mediascanner