-1

So this is the image file I got. Now, how do I convert this picturePath into a byte array so I can store it in my database?

Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    ivFoodPicture.setImageBitmap(BitmapFactory.decodeFile(picturePath));
  • You can also ask yourself *"How to store a image in database on Android ?"*. [This question](https://stackoverflow.com/questions/9357668) will then help you. – Gabriel Glenn Jan 12 '21 at 17:06

1 Answers1

0

You would need to get the Bitmap from the URI.

Pseduo:

Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);

And then to get the byte[] you can do:

   private byte[] toByteArray(@NonNull Bitmap bm)
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
        return baos.toByteArray();
    }

But do take care as these could Out Of Memory error with large files. Even base64Encoding these into a String can cause OOM.

Scott Johnson
  • 707
  • 5
  • 13
  • `You would need to get the Bitmap from the URI.` Not at all. And memory problems all around. Just load the jpg file in a byte array instead. In this way you can handle any file in the same way too. – blackapps Jan 12 '21 at 18:37
  • "Even base64 encoding" -- base64 encoding takes more memory than just a byte array, so would be more likely to cause an OOM error. – David Conrad Jan 12 '21 at 18:57
  • would i need to make the bitmap as an instance variable so I can pass it through the `toByteArray`? And how would i use this function inside my code? – millionclones Jan 13 '21 at 01:46