如何将Drawable资源写入文件?

30

我需要将一些 Drawable 资源导出到文件中。

例如,我有一个函数返回一个 Drawable 对象。 我想将它写入到 /sdcard/drawable/newfile.png 文件中。如何实现?


1
你可以尝试以下答案之一。 - Mauker
2个回答

44

虽然这里的最佳答案有一个不错的方法,但它只是链接。以下是你可以执行的步骤:

将Drawable转换为Bitmap

您可以以至少两种不同的方式来完成此操作,具体取决于您从何处获取Drawable

  1. Drawable位于res/drawable文件夹中。

假设您想要使用位于drawable文件夹中的Drawable。您可以使用BitmapFactory#decodeResource方法。以下是示例。

Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.your_drawable);
  1. 你有一个PictureDrawable对象。

如果你从其他地方“在运行时”获取了PictureDrawable,你可以使用Bitmap#createBitmap方法来创建你的Bitmap。就像下面的例子一样。

public Bitmap drawableToBitmap(PictureDrawable pd) {
    Bitmap bm = Bitmap.createBitmap(pd.getIntrinsicWidth(), pd.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bm);
    canvas.drawPicture(pd.getPicture());
    return bm;
}

保存位图到磁盘

一旦你有了Bitmap对象,你可以将其保存到永久存储。你只需要选择文件格式(JPEG、PNG或WEBP)。

/**
 * @param dir you can get from many places like Environment.getExternalStorageDirectory() or mContext.getFilesDir() depending on where you want to save the image.
 * @param fileName The file name.
 * @param bm The Bitmap you want to save.
 * @param format Bitmap.CompressFormat can be PNG,JPEG or WEBP.
 * @param quality quality goes from 1 to 100. (Percentage).
 * @return true if the Bitmap was saved successfully, false otherwise.
 */
boolean saveBitmapToFile(File dir, String fileName, Bitmap bm, 
    Bitmap.CompressFormat format, int quality) {
    
    File imageFile = new File(dir,fileName);

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(imageFile);

        bm.compress(format,quality,fos);

        fos.close();

        return true;
    }
    catch (IOException e) {
        Log.e("app",e.getMessage());
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    return false;
}

要获取目标目录,可以尝试以下方法:

File dir = new File(Environment.getExternalStorageDirectory() + File.separator + "drawable");

boolean doSave = true;
if (!dir.exists()) {
    doSave = dir.mkdirs();
}

if (doSave) {
    saveBitmapToFile(dir,"theNameYouWant.png",bm,Bitmap.CompressFormat.PNG,100);
}
else {
    Log.e("app","Couldn't create target directory.");
}

注意:如果您处理大型图像或多个图像,请在后台线程上执行此类工作,因为完成可能需要一些时间,并可能阻止您的用户界面,使您的应用程序无响应。


你好。这个答案只有在需要图像时才有帮助。但是我如何像复制文件一样复制矢量可绘制资源,而不需要位图等呢? - user5698345

-12

获取存储在SD卡中的图像..

File imgFile = new  File(“/sdcard/Images/test_image.jpg”);
if(imgFile.exists()){

    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

    ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
    myImage.setImageBitmap(myBitmap);

}

更新:

String path = Environment.getExternalStorageDirectory()+ "/Images/test.jpg"; 
File imgFile = new File(path);

1
不要使用固定路径来指定SD卡目录,而应该使用 **Environment.getExternalStorageDirectory().getPath();**。 - Paresh Mayani
String path = Environment.getExternalStorageDirectory() + "/Images/test.jpg";File imgFile = new File(path); - Nitesh Khosla
2
好的,但我不想从SD卡中读取文件,我想将可绘制资源写入文件... - Vlatego
嗯,这可能是一个正确的答案,即使它不是对这个问题的回答。 :-) - Gary Sheppard

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