将图像从 Android 上的可绘制资源保存到 SD 卡
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10558053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save image to sdcard from drawable resource on Android
提问by Moussa
I'm wondering how to save an image to user's sdcard through a button click. Could some one show me how to do it. The Image is in .png format and it is stored in the drawable directory. I want to program a button to save that image to the user's sdcard.
我想知道如何通过单击按钮将图像保存到用户的 SD 卡。有人可以告诉我如何做到这一点。图像为 .png 格式,并存储在 drawable 目录中。我想编写一个按钮来将该图像保存到用户的 SD 卡中。
回答by Imran Rana
The process of saving a file (which is image in your case) is described here: save-file-to-sd-card
此处描述了保存文件(在您的情况下为图像)的过程:save-file-to-sd-card
Saving image to sdcard from drawble resource:
将图像从 drawble 资源保存到 sdcard:
Say you have an image namely ic_launcher in your drawable. Then get a bitmap object from this image like:
假设您的 drawable 中有一个图像,即 ic_launcher。然后从此图像中获取位图对象,例如:
Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.ic_launcher);
The path to SD Card can be retrieved using:
可以使用以下方法检索 SD 卡的路径:
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
Then save to sdcard on button click using:
然后点击按钮保存到sdcard使用:
File file = new File(extStorageDirectory, "ic_launcher.PNG");
FileOutputStream outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
Don't forget to add android.permission.WRITE_EXTERNAL_STORAGE
permission.
不要忘记添加android.permission.WRITE_EXTERNAL_STORAGE
权限。
Here is the modified file for saving from drawable: SaveToSd, a complete sample project: SaveImage
回答by Ian Holing
I think there are no real solution on that question, the only way to do that is copy and launch from sd_card cache dir like this:
我认为这个问题没有真正的解决方案,唯一的方法是像这样从 sd_card 缓存目录复制和启动:
Bitmap bm = BitmapFactory.decodeResource(getResources(), resourceId);
File f = new File(getExternalCacheDir()+"/image.png");
try {
FileOutputStream outStream = new FileOutputStream(f);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) { throw new RuntimeException(e); }
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(f), "image/png");
startActivity(intent);
// NOT WORKING SOLUTION
// Uri path = Uri.parse("android.resource://" + getPackageName() + "/" + resourceId);
// Intent intent = new Intent();
// intent.setAction(android.content.Intent.ACTION_VIEW);
// intent.setDataAndType(path, "image/png");
// startActivity(intent);