how to convert an image to byte array in android

986 views Asked by At

I want to send an image as byte[] with my webservice. While sending request I am getting an error java.io.BufferedInputStream.streamClosed(BufferedInputStream.java:125) but the Image is Uploaded successfully here is my function to convert InputStream to byte[],

     public static byte[] streamToBytes(InputStream is) {
         ByteArrayOutputStream os = new ByteArrayOutputStream();
         byte[] buffer = new byte[1024];
         int len=0;
         try {
             while ((len = is.read(buffer)) >= 0) {
                 os.write(buffer, 0, len);
             }
         os.flush();
         os.close();
         is.close();
         } catch (java.io.IOException e) {
         }
         return os.toByteArray();
     }
1

There are 1 answers

0
Amit Das On

You can use this -

ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
        BufferedImage img=ImageIO.read(file);
        ImageIO.write(img, "jpg", baos);
        baos.flush();

        byte[] byteArray = baos.toByteArray();