How to Write a Drawable Resource to a File

How can I write a Drawable resource to a File?

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

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

  1. Drawable is on res/drawable folders.

Say you want to use a Drawable that is on your drawable folders. You can use the BitmapFactory#decodeResource approach. Example below.

Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.your_drawable);

  1. You have a PictureDrawable object.

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

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 Bitmap object, you can save it to the permanent storage. You'll just have to choose the file format (JPEG, PNG or 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.

Android create file from drawable

Try the following sample code:

        Drawable drawable = getResources().getDrawable(R.drawable.ic_action_home);
if (drawable != null) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
final byte[] bitmapdata = stream.toByteArray();
String url = "http://10.0.2.2/api/fileupload";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

// Add binary body
if (bitmapdata != null) {
ContentType contentType = ContentType.create("image/png");
String fileName = "ic_action_home.png";
builder.addBinaryBody("file", bitmapdata, contentType, fileName);
httpEntity = builder.build();
...
}
...
}

Create a file from drawable

You can open an InputStream from your drawable resource using following code:

InputStream is = getResources().openRawResource(id);

here id is the identifier of your drawable resource. for eg: R.drawable.abc

Now using this input stream you can create a file. If you also need help on how create a file using this input stream then tell me.

Update: to write data in a file:

try
{
File f=new File("your file name");
InputStream inputStream = getResources().openRawResource(id);
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
}
catch (IOException e){}
}

How to add an image to a Drawable Resource File

You can add like below.

 <?xml version="1.0" encoding="utf-8"?>
<layer-list>

<item>
<shape>
<solid android:color="#000000"/>
<padding android:right="#000000"/>
</shape>
</item>

<item>

<bitmap android:gravity="right|center" android:src="@drawable/down_arrow" />

</item>

</layer-list>

How to draw specific drawable resource programmatically?

Your images has to be in png format (prefered by android) and must contain only lowercase letters and digits ([a-z0-9_.].
Then you can use

image.setImageResource(R.drawable.name_of_image);

You can get the name of the drawable with this:

String name = context.getResources().getResourceEntryName(R.drawable.name_of_image);

To get the drawable with the string name:

int id = context.getResources().getIdentifier("name_of_image", "drawable", context.getPackageName());
image.setImageResource(id);

Save images from drawable to internal file storage in Android

Saving image to sdcard from drawble resource:

Say you have an image namely ic_launcher in your drawable. Then get a bitmap object from this image like:

Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.ic_launcher);

The path to SD Card can be retrieved using:

String extStorageDirectory = Environment.getExternalStorageDirectory().toString();

Then save to sdcard on button click using:

File file = new File(extStorageDirectory, "ic_launcher.PNG");
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();

Don't forget to add android.permission.WRITE_EXTERNAL_STORAGE permission.

Is there a way to target certain Api's in a drawable.xml file?

You can create multiple resources for different API version and let Android choose one of them based on device's API version. Create a new drawable.xml file but choose API version 21 as a qualifier and put your code on that. Create another drawable.xml with no version qualifier and put another code which runs on pre 21 version.



Related Topics



Leave a reply



Submit