我怎样才能写一个可绘制的资源文件?

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

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

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

将Drawable转换为位图

你至less可以通过两种不同的方式来实现,取决于你从哪里获得Drawable

  1. 可绘制的是res/drawable文件夹。

假设您要使用绘图文件夹中的Drawable 。 您可以使用BitmapFactory#decodeResource方法。 下面的例子。

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

如果您在“运行时”从其他位置获取PictureDrawable ,则可以使用Bitmap#createBitmap方法创build您的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对象,你可以将它保存到永久存储器中。 你只需要select文件格式(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."); } 

Obs:请记住在背景线程上执行此类工作,如果您处理的是大图像或多个图像,则可能需要一些时间才能完成,并可能会阻止您的UI,从而使您的应用程序无响应。

  1. 将可绘制转换为位图: 如何将可绘制转换为位图?
  2. 将位图保存到文件: 将位图保存到位置

获取存储在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);