Android 如何将 Drawable 资源写入文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10174399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:45:20  来源:igfitidea点击:

How can I write a Drawable resource to a File?

androidexportdrawable

提问by Vlatego

I need to export some Drawableresources to a file.

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

For example, I have a function that returns to me a Drawableobject. I want to write it out to a file in /sdcard/drawable/newfile.png. How can i do it?

例如,我有一个函数返回给我一个Drawable对象。我想把它写到/sdcard/drawable/newfile.png. 我该怎么做?

回答by Mauker

Although the best answer here have a nice approach. It's link only. Here's how you can do the steps:

虽然这里的最佳答案有一个很好的方法。只是链接而已。以下是您可以如何执行这些步骤:

Convert Drawable to Bitmap

将 Drawable 转换为位图

You can do that in at least two different ways, depending on where you're getting the Drawablefrom.

您至少可以通过两种不同的方式来做到这一点,具体取决于您Drawable从何处获取。

  1. Drawable is on res/drawablefolders.
  1. Drawable 在res/drawable文件夹上。

Say you want to use a Drawablethat is on your drawable folders. You can use the BitmapFactory#decodeResourceapproach. Example below.

假设您想使用Drawable可绘制文件夹中的 。您可以使用该BitmapFactory#decodeResource方法。下面举例。

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

If you're getting a PictureDrawablefrom somewhere else "at runtime", you can use the Bitmap#createBitmapapproach to create your Bitmap. Like the example below.

如果您PictureDrawable“在运行时”从其他地方获取 a ,您可以使用该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;
}

Save the Bitmap to disk

将位图保存到磁盘

Once you have your Bitmapobject, you can save it to the permanent storage. You'll just have to choose the file format (JPEG, PNG or WEBP).

拥有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;
}

And to get the target directory, try something like:

要获取目标目录,请尝试以下操作:

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.");
}

Obs:Remember to do this kind of work on a background Thread if you're dealing with large images, or many images, because it can take some time to finish and might block your UI, making your app unresponsive.

Obs:如果您正在处理大图像或许多图像,请记住在后台线程上执行此类工作,因为它可能需要一些时间才能完成并可能阻塞您的 UI,使您的应用程序无响应。

回答by Nitesh Khosla

get the image stored in sdcard..

获取存储在sdcard中的图像..

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

}

Update:

更新:

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