Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I convert an imageview to byte array in Android Studio?

Tags:

java

android

My goal is to get a picture selected by the user and populate an image view with it. Then, on clicking a button, that image will be sent to a Parse database. I know I have to convert the imageview to byte array, but Doesn't seem to work.

Any help will be highly appreciated. here's my code:

 //send the imageviwew to parse database

 public void sendToParseBtn (View view){
     Bitmap bitmapImage = findViewById (R.id.imageView);
     ImageView imageView = (ImageView) findViewById(R.id.imageView);
     imageView.setImageBitmap(bitmapImage);

     ByteArrayOutputStream stream = new ByteArrayOutputStream();
     bitmapImage.compress(Bitmap.CompressFormat.JPEG, 40, stream);

     byte[] byteArray = stream.toByteArray();

     ParseFile file = new ParseFile("an.jpg",byteArray);
     ParseObject object = new ParseObject("MyParseObject");
     object.put("imageFile", file);

     object.saveInBackground();
 }
like image 539
RealBadCoder Avatar asked Jun 12 '16 22:06

RealBadCoder


1 Answers

Try converting the image view to a bitmap drawable first then get the byteArray:

ImageView imageView = (ImageView) findViewById(R.id.imageView);
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageInByte = baos.toByteArray();
//save your stuff
like image 52
Rogério Peixoto Avatar answered Sep 20 '22 21:09

Rogério Peixoto