从数组到BufferedImage的转换不正确

时间:2012-06-15 03:48:59

标签: java arrays bufferedimage

图像转换为RGB灰度 接下来,将灰度图像转换为数组,执行该数组以定义转换。结果,数组由“0”和“255”组成。

然后,我需要将此数组转换为BufferedImage。

我使用了代码:

public static BufferedImage getImageFromArray(int pixelsMain[][], int width, int height) throws IOException {

        int pixels[] = new int[320*240];

        for(int i=0, numb=0; i<pixelsMain.length; i++)
            for(int j=0; j<pixelsMain[i].length; j++){
                pixels[numb]=pixelsMain[i][j];
                numb++;
            }

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        WritableRaster raster = (WritableRaster) image.getData();
        raster.setPixels(0,0,width,height,pixels);
        try {
            ImageIO.write(image, "bmp", new FileOutputStream("[path]"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

但是,执行该方法后 - “255”的所有值都转换为“-1”。

因此,图像完全是黑色。

请告诉我如何解决问题?

1 个答案:

答案 0 :(得分:4)

使用image.getRaster()代替(WritableRaster)image.getData()。后者正在复制,所以改变它没有效果。