基于int数组创建WritableRaster

时间:2014-08-07 09:24:39

标签: java image-processing raster

我需要一个int数组并将其转换为BufferImage。我真的没有任何关于这个主题的背景知识,我从互联网上学到了所有这些,所以这就是我想要做的: 从BufferedImage(完成)创建数组,将此数组转换为IntBuffer(完成) - (稍后我需要通过IntBuffer对图像执行一些操作),将IntBuffer中更改的值放入新数组(完成),并将此数组转换为WritableRaster。 (如果我对这个过程的描述不对,请告诉我)

这是我处理WritableRaster的行:

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

Eclipse将此标记为错误并说''类型不匹配:无法从void转换为WritableRaster“

请帮忙!我有点失落。

也很抱歉英语不好。

编辑: 矩阵:

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

我尝试将值插入Raster的代码部分:

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

错误消息:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10769
at java.awt.image.SinglePixelPackedSampleModel.setPixels(Unknown Source)
at java.awt.image.WritableRaster.setPixels(Unknown Source)

3 个答案:

答案 0 :(得分:6)

您可以从WritableRaster数组创建BufferedImage和/或int,如下所示:

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);

答案 1 :(得分:1)

    ColorModel cm = ColorModel.getRGBdefault();
    int w = 300;
    int h = 200;
    WritableRaster raster = cm.createCompatibleWritableRaster(w, h);
    DataBufferInt buffer = (DataBufferInt) raster.getDataBuffer();
    int[] bufferData = buffer.getData();
    int[] array = new int[2400];
    Random random = new Random();
    for (int i = 0; i < 2400; i++) {
        array[i] = random.nextInt(2);
    }
    System.arraycopy(array, 0, bufferData, 0, (array.length < bufferData.length ? array.length : bufferData.length));
    BufferedImage image = new BufferedImage(cm, raster, false, null);
    FileOutputStream fos = new FileOutputStream("D:\\abc\\OCR\\" + "LearningRaster" + ".png");
    ImageIO.write(image, "PNG", fos);
    fos.close();

答案 2 :(得分:0)

setPixels返回void:

public static void setPixels(BufferedImage img,
                         int x, int y, int w, int h, int[] pixels)

所以你需要创建Raster而不是设置像素:

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

你需要为每个像素放置4个int(它取决于颜色模型,4个用于ARGB)。因此,矩阵大小必须

int[] matrix = new int[width * height * 4]

在此处查看有关WritableRaster的更多信息 -

Oracle: WritableRaster

Code examples