Save image to sdcard from drawable resource on Android

[亡魂溺海] 提交于 2019-12-17 03:39:20

问题


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.


回答1:


The process of saving a file (which is image in your case) is described here: save-file-to-sd-card


Saving image to sdcard from drawble resource:

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);

The path to SD Card can be retrieved using:

String extStorageDirectory = Environment.getExternalStorageDirectory().toString();

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();

Don't forget to add android.permission.WRITE_EXTERNAL_STORAGE permission.

Here is the modified file for saving from drawable: SaveToSd , a complete sample project: SaveImage




回答2:


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:

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);


来源:https://stackoverflow.com/questions/10558053/save-image-to-sdcard-from-drawable-resource-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!