Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a WritableRaster based on int array

I need to take an int array and turn it into BufferImage. I really don't have any background on this subject and I learn it all from the internet so here's what I'm trying to do: Create an array from BufferedImage(done), turn this array into IntBuffer(done) - (Later i'll need to do some opertions on the image through the IntBuffer), put the changed values from the IntBuffer in new array(done), and turn this array into WritableRaster. (If something isn't right in my understading of the process please tell me)

Here's the line where I deal with the WritableRaster:

WritableRaster newRaster= newRaster.setPixels(0, 0, width, height, matrix);

Eclipse marks this as a mistake and says ''Type mismatch:Cannot convert from void to WritableRaster"

Please help! I'm a bit lost.

Also sorry for bad english.

EDIT: The matrix:

         int height=img.getHeight();
         int width=img.getWidth();
         int[]matrix=new int[width*height];

The part of the code where I try to insert values to the Raster:

    BufferedImage finalImg = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
    WritableRaster newRaster= (WritableRaster)finalImg.getData();
    newRaster.setPixels(0, 0, width, height, matrix);

The error message:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10769
at java.awt.image.SinglePixelPackedSampleModel.setPixels(Unknown Source)
at java.awt.image.WritableRaster.setPixels(Unknown Source)
like image 477
user3917631 Avatar asked Feb 13 '23 07:02

user3917631


1 Answers

You can create a WritableRaster and/or BufferedImage from an int array like this:

int w = 300;
int h = 200;
int[] matrix = new int[w * h];

// ...manipulate the matrix...

DataBufferInt buffer = new DataBufferInt(matrix, matrix.length);

int[] bandMasks = {0xFF0000, 0xFF00, 0xFF, 0xFF000000}; // ARGB (yes, ARGB, as the masks are R, G, B, A always) order
WritableRaster raster = Raster.createPackedRaster(buffer, w, h, w, bandMasks, null);

System.out.println("raster: " + raster);

ColorModel cm = ColorModel.getRGBdefault();
BufferedImage image = new BufferedImage(cm, raster, cm.isAlphaPremultiplied(), null);

System.err.println("image: " + image);
like image 140
Harald K Avatar answered Feb 15 '23 09:02

Harald K