将图像从 Android 上的可绘制资源保存到 sdcard [英] Save image to sdcard from drawable resource on Android
问题描述
我想知道如何通过单击按钮将图像保存到用户的 SD 卡中.有人可以告诉我如何做到这一点.图像为 .png 格式,并存储在 drawable 目录中.我想编写一个按钮来将该图像保存到用户的 SD 卡中.
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.
推荐答案
此处描述了保存文件(在您的情况下为图像)的过程:save-file-to-sd-card
The process of saving a file (which is image in your case) is described here: save-file-to-sd-card
假设您的 drawable 中有一个名为 ic_launcher 的图像.然后从此图像中获取位图对象,例如:
Say you have an image namely ic_launcher in your drawable. Then get a bitmap object from this image like:
Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.ic_launcher);
可以使用以下方法检索 SD 卡的路径:
The path to SD Card can be retrieved using:
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
然后使用以下按钮保存到sdcard:
Then save to sdcard on button click using:
File file = new File(extStorageDirectory, "ic_launcher.PNG");
FileOutputStream outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
不要忘记添加android.permission.WRITE_EXTERNAL_STORAGE
权限.
这是用于从 drawable 保存的修改文件:SaveToSd,一个完整的示例项目:SaveImage
Here is the modified file for saving from drawable: SaveToSd , a complete sample project: SaveImage
这篇关于将图像从 Android 上的可绘制资源保存到 sdcard的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!