0

Here I am type casting the byte array data[] to int. But getting positive and negetive integer values as output array in arr[i]. But pixel values should come positive right? For grayscale (0 to 255) I think I am converting wrong way. Can anyone please suggest some code to convert my byte array data[] to integer 1D array arr[]?

public class Imagemat {
    public static void main(String[] args) throws Exception  { 
        //*************convert byte array*************//
        BufferedImage bImage = ImageIO.read(new File("image path"));
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(bImage, "jpg", bos);
        byte[] data = bos.toByteArray(); //byte array data[]

         //*****convert to integer array *****//
        int[] arr = new int[data.length];
        for(int i = 0; i < data.length; i++) {
            arr[i] = (int)data[i];
        }
        for(int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + "  "); //integer array arr[i]
            System.out.println();
        }
    }
}

Getting output like:

-1  -40  -1  -32  0  16  74  70  73  70  0  1  2  0  0  1  0  1  0  0  -1  -37  0  67  0  8  6  6  7  
6  5  8  7  7  7  9  9  8  10  12  20  13  12  11  11  1........
Yuri Kovalenko
  • 1,325
  • 9
  • 19
S.Podder
  • 35
  • 4

1 Answers1

0

I am not sure how JPG images are stored in bytes, but to convert a unsigned byte to an int you can use Byte.toUnsignedInt(byte x) to get the unsigned value of a byte. (This function just returns ((int) x) & 0xff so you can use that instead if you want)

Example:

int[] arr = new int[data.length];
for(int i = 0; i < data.length; i++) {
   arr[i] = Byte.toUnsignedInt(data[i]);
}
for(int i = 0; i < arr.length; i++) {
   System.out.print(arr[i] + "  "); //integer array arr[i]
   System.out.println();
}
lxr196
  • 108
  • 2
  • 7
  • actually I am trying to convert a grayscale image to integer 2D array or matrix. using following code i am getting byte array data [] BufferedImage bImage = ImageIO.read(new File("grayscale.jpg")); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(bImage, "jpg", bos ); byte [] data = bos.toByteArray(); after this I am trying to convert it to int 2D array. First getting 1D array , then converting to 2D array.. – S.Podder Nov 26 '19 at 10:45
  • I am not sure whether the data is coming correctly after converting byte to unsigned Int. total length of byte array is showing 3962. But how to divide this size as row and column? Can you please help me? the image dimension is 225*225. – S.Podder Nov 26 '19 at 10:52
  • @S.Podder Again you need to realise the data is compressed and stored in a specific format so you can just read the file and expect it to correspond 1:1 to your 255x255 sized image. A simple math example, if your file is using 8 bit then the size should be 255*255 byte which is about 63.5 Kb. Your array is less than 4 Kb. – Joakim Danielson Nov 26 '19 at 18:43