Search code examples
javabufferedimageraster

How to create a Raster from a pixel float array in Java?


I'm trying to take a BufferedImage, apply a Fourier transform (using jtransforms), and write the data back to the BufferedImage. But I'm stuck creating a new Raster to set the results back, am I missing something here?

BufferedImage bitmap;
float [] bitfloat = null;

bitmap = ImageIO.read(new File("filename"));
FloatDCT_2D dct = new FloatDCT_2D(bitmap.getWidth(),bitmap.getHeight());

bitfloat = bitmap.getData().getPixels(0, 0, bitmap.getWidth(), bitmap.getHeight(), bitfloat);
dct.forward(bitfloat, false);

But I'm stumped trying to finish off this line, what should I give the createRaster function? The javadocs for createRaster make little sense to me:

bitmap.setData(Raster.createRaster(`arg1`, `arg2`, `arg3`));

I'm starting to wonder if a float array is even necessary, but there aren't many examples of jtransforms out there.


Solution

  • Don't create a new Raster. Use WritableRaster.setPixels(int,int,int,int,float[]) to write the array back to the image.

    final int w = bitmap.getWidth();
    final int h = bitmap.getHeight();
    
    final WritableRaster wr = bitmap.getData();
    bitfloat = wr.getPixels(0, 0, w, h, bitfloat);
    
    // do processing here
    
    wr.setPixels(0, 0, w, h, bitfloat);    
    

    Note also that if you're planning to display this image, you should really copy it to a screen-compatible type; ImageIO seldom returns those.