在安卓上将图片从drawable资源保存到SD卡

23

我想知道如何通过按钮点击将图像保存到用户的SD卡中。有人可以向我展示如何做吗?该图片是以.png格式存储在drawable目录中。我想编写一个按钮程序来将该图片保存到用户的SD卡中。


是什么类型的图像?刚拍摄的照片?来自相册的照片?还是完全不同的东西?更多细节是非常必要的。如果您发布了一些相关代码并描述了您尝试过的内容,这将有助于我们提供帮助。 - MattDavis
尝试使用此链接:https://dev59.com/v3RB5IYBdhLWcg3wXWG2 - Rakesh
这是一个很好的资源,但能否有人解释一下,比如代码放在哪里?我应该放在 OnClick 里面吗? - Moussa
3个回答

45

保存文件的过程(在您的情况下是图像)在这里描述:save-file-to-sd-card


从drawable资源将图像保存到SD卡:

假设您有一个名为ic_launcher的图像在drawable中。然后从此图像获取一个位图对象,如下所示:

Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.ic_launcher);

可以使用以下代码获取SD卡的路径:

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

然后在按钮点击时使用以下代码将其保存到SD卡:

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


抱歉,我迟到了,很久没有登录了。谢谢。 - Moussa
我在代码上遇到了问题,具体是在这一段:File file = new File(extStorageDirectory, "ic_launcher.PNG"); outStream = new FileOutputStream(file); bm.compress(Bitmap.CompressFormat.PNG, 100, outStream); outStream.flush(); outStream.close(); 所有的输出都出现了一个错误,请问你能帮我吗?错误提示是“无法将outStream解析为变量”。 - Moussa
@IranianLIon 这里是完整的示例项目:保存图片,请使用它。 - Imran Rana
抱歉,我的错,我没有注意到我这样做了。 - Moussa
为什么它会保存两份图像副本? - Si8
显示剩余8条评论

3

我认为这个问题没有真正的解决方案,唯一的方法是像这样从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);

0

如果您使用Kotlin,您可以这样做:

val mDrawable: Drawable? = baseContext.getDrawable(id)
val mbitmap = (mDrawable as BitmapDrawable).bitmap
val mfile = File(externalCacheDir, "myimage.PNG")
        try {
            val outStream = FileOutputStream(mfile)
            mbitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream)
            outStream.flush()
            outStream.close()
        } catch (e: Exception) {
            throw RuntimeException(e)
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接