Drawable to byte[]

AndroidDatabaseDrawableAndroid Bitmap

Android Problem Overview


I have an image from the web in an ImageView. It is very small (a favicon) and I'd like to store it in my SQLite database. I can get a Drawable from mImageView.getDrawable() but then I don't know what to do next. I don't fully understand the Drawable class in Android.

I know I can get a byte array from a Bitmap like:

Bitmap defaultIcon = BitmapFactory.decodeStream(in);
		
ByteArrayOutputStream stream = new ByteArrayOutputStream();
defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, stream);

byte[] bitmapdata = stream.toByteArray();

But how do I get a byte array from a Drawable?

Android Solutions


Solution 1 - Android

Drawable d; // the drawable (Captain Obvious, to the rescue!!!)
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitmapdata = stream.toByteArray();

Solution 2 - Android

Thanks all and this solved my problem.

Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.my_pic);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitMapData = stream.toByteArray();

Solution 3 - Android

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tester);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitMapData = stream.toByteArray();

Solution 4 - Android

If Drawable is an BitmapDrawable you can try this one.

long getSizeInBytes(Drawable drawable) {
	if (drawable == null)
		return 0;

	Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
	return bitmap.getRowBytes() * bitmap.getHeight();
}

Bitmap.getRowBytes() returns the number of bytes between rows in the bitmap's pixels.

For more refer this project: LazyList

Solution 5 - Android

File myFile = new File(selectedImagePath);

byte [] mybytearray  = new byte [filelenghth];

BufferedInputStream bis1 = new BufferedInputStream(new FileInputStream(myFile));

bis1.read(mybytearray,0,mybytearray.length);

now the image is stored in the bytearray..

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid ShellabargerView Question on Stackoverflow
Solution 1 - AndroidCristianView Answer on Stackoverflow
Solution 2 - AndroidRandulaView Answer on Stackoverflow
Solution 3 - AndroidKalpeshView Answer on Stackoverflow
Solution 4 - AndroidFavas KvView Answer on Stackoverflow
Solution 5 - AndroidAbhishek SusarlaView Answer on Stackoverflow