23

我想知道如何通过单击按钮将图像保存到用户的 SD 卡。有人可以告诉我怎么做。图像为 .png 格式,存储在可绘制目录中。我想编写一个按钮来将该图像保存到用户的 SD 卡中。

4

3 回答 3

43

此处描述了保存文件(在您的情况下为图像)的过程:save-file-to-sd-card


从drawble资源将图像保存到sdcard:

假设您的可绘制对象中有一个名为 ic_launcher 的图像。然后从此图像中获取位图对象,例如:

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

可以使用以下方式检索 SD 卡的路径:

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

然后在按钮单击时保存到 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();

不要忘记添加android.permission.WRITE_EXTERNAL_STORAGE权限。

这是从drawable保存的修改文件:SaveToSd ,一个完整的示例项目:SaveImage

于 2012-05-12T06:17:01.840 回答
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);
于 2014-03-18T18:43:18.157 回答
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)
        }
于 2021-11-21T13:42:05.197 回答