-1

I want to convert the image file into byte[] array format. I used this code

   Bitmap bm = getBitmapFromLocalPath(file1.getPath(),1);
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
   bm.recycle();
   byte[] image = baos.toByteArray();

//method

public static Bitmap getBitmapFromLocalPath(String path, int sampleSize)
    {
        try
        {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = sampleSize;
            return BitmapFactory.decodeFile(path, options);
        }
        catch(Exception e)
        {
            //  Logger.e(e.toString());
        }

        return null;
    }

It showing error like

E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/DCIM/Camera/IMG_20200324_121621.jpg (Permission denied)
E/AndroidRuntime: FATAL EXCEPTION: Thread-2
    Process: com.example.multiupload, PID: 5477
    java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
Zoe
  • 27,060
  • 21
  • 118
  • 148

1 Answers1

0

To load a file in memory declare a byte array with the size of the file. Then read the bytes of the file in that array.

Usable for all files.

Especially dont use Bitmap and BitmapFactory classes for image files. They will change the bytes of the file.

blackapps
  • 8,011
  • 2
  • 11
  • 25