Drawable to Byte[]

Drawable to byte[]

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();

Converting an image from drawable to byte array in Android

First you need to convert your Drawable image to Bitmap using this code written by Chris.Jenkins:

public static Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}

// We ask for the bounds if they have been set as they would be most
// correct, then we check we are > 0
final int width = !drawable.getBounds().isEmpty() ?
drawable.getBounds().width() : drawable.getIntrinsicWidth();

final int height = !drawable.getBounds().isEmpty() ?
drawable.getBounds().height() : drawable.getIntrinsicHeight();

// Now we check we are > 0
final Bitmap bitmap = Bitmap.createBitmap(width <= 0 ? 1 : width, height <= 0 ? 1 : height,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);

return bitmap;
}

After getting your Bitmap object, you need to convert it to a byte array using this code from Mezm:

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
bmp.recycle();

converting from byte array to drawable image gives corrupt image: Android

Try the following code,

Convert Bitmap to ByteArray.

Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.myImage);
ByteArrayOutputStream opstream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, opstream);
byte[] bytArray = opstream.toByteArray();

Convert ByteArray to Bitmap.

Bitmap bitmap = BitmapFactory.decodeByteArray(bytArray, 0, bytArray.length);
ImageView img = (ImageView) findViewById(R.id.imgv1);
img.setImageBitmap(bitmap);

This may helps you.

Java convert drawable to bytearray

You cant pass an image bitmap directly in the params, you must pass a URI. The URI must point a resource the facebook app can access. You can quickly get a URI from a bitmap like this:

String path = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "temp", "Test Image");
params.putString("picture", path);

Use that instead of setting picture directly to bitmap or bitmap bytes.

How to get a byte array from a drawable resource ?

Get a bitmap decodeResource(android.content.res.Resources, int)
Then either compress it to ByteArrayOutputStream() or copyPixelsToBuffer and get your array from the buffer.
http://developer.android.com/reference/android/graphics/Bitmap.html



Related Topics



Leave a reply



Submit