RealBadCoder
RealBadCoder

Reputation: 351

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

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

Upvotes: 10

Views: 21392

Answers (2)

Codemaker2015
Codemaker2015

Reputation: 1

You can use the following method to convert imageView to bytesArray.

public byte[] getBytes(ImageView imageView) {
    try {
        Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] bytesData = stream.toByteArray();
        stream.close();
        return bytesData;
    } catch(Exception e) {
        e.printStackTrace();
        return null;
    }
    return null;
}

Upvotes: 0

Rogério Peixoto
Rogério Peixoto

Reputation: 2247

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

Upvotes: 32

Related Questions