Image to byte array and back to image in J2ME

I have recently been working with a mobile client where the possibility to retrieve the raw byte array from an image was important. I struggled to find any working solutions on forums all over but none was working as I wanted. Why don’t the Image.java have an option to retrieve the raw byte array?

The numorus options on forums included getting the RGB-data as an int array and then bit-switching to get the proper output. BUT, if you want to create an Image based on your newly created byte array, if fails with an IllegalArgumentException.

Here is what I did for this workaround. I’m not sure if this is the correct way to do it but in my case it did what I wanted:

/**
   * Get the resource from jar-package as input stream to get the byte[] raw format
   * @param resource The local file name
   * @return The image byte array
   */
public byte[] getResourceAsByteArray(String resource){
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	InputStream bais;
	try {
		bais = (InputStream)getClass().getResourceAsStream("//" + resource);
		int c;
		while((c = bais.read()) != -1){
			baos.write(c);
		}
		bais.close();
		baos.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return baos.toByteArray();
}

Post to Twitter

Tags: convert to byte array, image to byte array, Image.java, Java ME