Hello everyone! I have tried again and again to get this to work using multiple suggestions from the Internet. I am trying to convert an int[] to an Image object. I am getting the array using a PixelGrabber object:

int img1_1d[] = new int[img1_w * img1_h];
        PixelGrabber grab1 = new PixelGrabber(img1,0,0,img1_w,img1_h,img1_1d,0,img1_w);
        try {
            boolean r = grab1.grabPixels();
            if (!r) System.out.println("Pixel grabber ERROR");
        } catch (InterruptedException e2) {
            e2.printStackTrace();
            System.exit(1);
        }

I am attempting to create the Image object using this code:

public static Image getImageFromArray(int[] pixels, int width, int height) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);
        WritableRaster raster = (WritableRaster) image.getData();
        raster.setPixels(0,0,width,height,pixels);
        return image;
    }

Every time the above method gets called, the image return is of the right dimesions but is solid black. What is happening? I need this fixed as soon as possible and thanks in advance for the help.

Recommended Answers

All 3 Replies

Are you 100% sure that you actually have data in your array?

Any special reason to use BYE_BINARY rather than the obvious int ARGB?

In case this helps:
I have a running application that copies Images over an internet socket by sending the ARGB int array data (compressed - but that's not relevant here). The relevant code looks like this:

  // sender: get the ARGB int array for the image to send
  BufferedImage image = ...
  Raster ras =  image.getData();
  DataBufferInt db = (DataBufferInt) ras.getDataBuffer();
  int[] data = db.getData(); // this is the int array I compress & send

  // at the receiving end...
  // create in-memory Image, and get access to its raw pixel data array
  image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
  DataBufferInt db = (DataBufferInt) image.getRaster().getDataBuffer();
  int[] pixels = db.getData();
  // then simply update the pixels array directly with the received ARGB values

The decoding of ARGB from int looks like this:

   int pixel = pixels[i];
   int alpha = (pixel >> 24) & 0xff;
   int r = (pixel >> 16) & 0xff;
   int g = (pixel >> 8) & 0xff;
   int b = (pixel) & 0xff;

and encoding them is exactly the reverse, ie

pixels[i] = alpha << 24 | r << 16 | g << 8 | b; // all values must be 0-255

ps: Even if you're not using the alpha channel, remember to set it to 255, not 0. 0 is fully transparent, so all you will see on the screen is whatever background colour is behind the image

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.