0

I've been trying to fix my problem looking for questions like this one (Drawable to byte[]) but I couldn't fix it.

I'm setting a drawable picture (the user can change it too) from an imageview and later i'm trying to get this picture and convert it into a byte array to save it in a database.

My code:

//imageview1.setImageResource(R.drawable.pictureJM);
imageview1.setImageDrawable(getResources().getDrawable(R.drawable.pictureJM));

Drawable d1=imageview1.getDrawable();
Bitmap bitmap =((BitmapDrawable)d1).getBitmap();  <-- (The application stops here)

ByteArrayOutputStream streamJM = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, streamJM);
byte[] imageInByte = streamJM.toByteArray();

Can you tell me what's wrong ?

Community
  • 1
  • 1
Frange
  • 191
  • 1
  • 4
  • i have tried the same code you have entered, it's working fine. What error you are getting exactly? – Arshdeep_somal Apr 02 '14 at 02:13
  • what's exactly the point of putting a resource in a `ImageView` instead of decoding the resource directly as `Bitmap`? `BitmapFactory.decodeResource(context.getResources(), R.drawable.pictureJM)` – sherpya Apr 02 '14 at 02:27
  • (Arshdeep_somal)- There is no error, It just stops the execution but if I put a picture from the gallery with other function I made It works... I don't understand and It's difficult to explain. (sherpya), what I should do with these line of code ? Thank you both, I'm having a headache with this problem. – Frange Apr 02 '14 at 10:17

2 Answers2

0

Try this:

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pictureJM);
ByteArrayOutputStream streamJM = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, streamJM); 
byte[] imageInByte = streamJM.toByteArray();
Luis Lavieri
  • 4,064
  • 6
  • 39
  • 69
  • These lines of code works but the problem is the user can change the picture of the imageview, the picture is not static so "R,drawable.pictureJM" it's only correct in one case. – Frange Apr 02 '14 at 11:51
0

I really don't understand what was wrong with it but finally I fixed. I didn't change any other part of my code and when I wrote this It started to work:

Bitmap bitmap = ((BitmapDrawable)imageview1.getDrawable()).getBitmap();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte=stream.toByteArray();

Thank all of you for trying to help me ! Cheers

Frange
  • 191
  • 1
  • 4