我需要将一些Drawable
资源导出到文件中。
例如,我有一个函数返回给我一个Drawable
对象。我想把它写到/sdcard/drawable/newfile.png
. 我该怎么做?
虽然这里的最佳答案有一个很好的方法。它只是链接。以下是如何执行这些步骤:
您可以通过至少两种不同的方式做到这一点,具体取决于您从哪里获得Drawable
。
res/drawable
文件夹上。假设您想使用Drawable
可绘制文件夹上的 a 。您可以使用该BitmapFactory#decodeResource
方法。下面的例子。
Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.your_drawable);
PictureDrawable
对象。如果您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;
}
拥有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.");
}
Obs:如果您正在处理大图像或许多图像,请记住在后台线程上执行此类工作,因为它可能需要一些时间才能完成并且可能会阻塞您的 UI,使您的应用程序无响应。
获取存储在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);
}
String path = Environment.getExternalStorageDirectory()+ "/Images/test.jpg";
File imgFile = new File(path);