将图像从安卓上的可绘制资源保存到SD卡



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

保存文件(在您的案例中是图像)的过程如下所述: 将文件保存到 SD 卡


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

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

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权限。

这是用于从可绘制对象保存的修改文件:SaveToSd,一个完整的示例项目:保存图像

我认为

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

如果你使用 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)
        }

最新更新