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

例如,我有一个向我返回Drawable对象的函数。我想将其写到/sdcard/drawable/newfile.png中的文件中。我该怎么做?

最佳答案

虽然这里最好的答案有一个不错的方法。仅链接。您可以按照以下步骤进行操作:
将Drawable转换为位图
您可以通过至少两种不同的方式执行此操作,具体取决于您从何处获取Drawable

  • 可绘制对象位于res/drawable文件夹中。

  • 假设您要使用可绘制文件夹中的Drawable。您可以使用 BitmapFactory#decodeResource 方法。下面的例子。
    Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.your_drawable);
    
  • 您有一个 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.");
    }
    
    对象:如果要处理大型图像或许多图像,请记住在后台线程上执行此类工作,因为这可能需要一些时间才能完成,并且可能会阻塞UI,从而使应用程序无响应。

    08-18 03:11
    查看更多