Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Image into Byte Array in Android

Tags:

android

bitmap

I am facing one real issue. I need to convert image into byte array format, so that I can upload the byte array into web server. I have tried a lot however its not working. I am also getting negative values for byte array. I am not sure what i am doing wrong to take byte values in array.

Below is my code. Please help me what i am doing wrong?

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.home_menu_icon);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
like image 822
user2576081 Avatar asked May 15 '26 07:05

user2576081


1 Answers

Here i show code for both if your image is from GALLERY and CAMERA

if (requestCode == IMAGE_PICKER_REQUEST && resultCode == RESULT_OK) {
        fileName = getRealPathFromURI(data.getData());

        try {
             if (bitmap != null) {
                    bitmap.recycle();
                }
            InputStream stream = getContentResolver().openInputStream(
                    data.getData());

            bitmap = BitmapFactory.decodeStream(stream);
            stream.close();
            image.setImageBitmap(bitmap);
            //picNameText.setText("Selected: en"
                //  + getStringNameFromRealPath(fileName));

            ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream1);
            imageInByte = stream1.toByteArray();

        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        } 
    }

    if (requestCode == IMAGE_TAKER_REQUEST && resultCode == RESULT_OK) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        image.setImageBitmap(photo);

        ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
        photo.compress(Bitmap.CompressFormat.PNG, 100, stream2);
        imageInByte = stream2.toByteArray();

    }

enjoy it work for me.....

like image 143
Dhaval Patel Avatar answered May 16 '26 21:05

Dhaval Patel