首页 > 解决方案 > BufferedImage 灰度图太暗

问题描述

我的任务是将 png 格式的灰度图像读取到二维数组,并对每个像素进行一些算术运算。我写了一些代码来读取我的图像并将其转换为二维数组,但结果我的图像更暗,即使我还没有改变任何东西。我的代码:

            BufferedImage image = ImageIO.read(new File(IMAGE_PATH + "gray/squirrel.png"));

            int width = image.getWidth();
            int height = image.getHeight();

            int[][] imageData = new int[width][height];
            for(int i = 0; i < width ; ++i){
                for(int j = 0 ; j < height ; ++j){
                    Color color = new Color(image.getRGB(i,j));
                    imageData[i][j] = (color.getRed() + color.getGreen() + color.getBlue()) / 3;
                }
            }

            BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);

            for (int x = 0; x < width ; x++) {
                for (int y = 0; y < height; y++) {
                    newImage.setRGB(x, y, imageData[x][y]);
                }
            }

            File outputfile = new File("image.png");
            ImageIO.write(newImage, "png", outputfile);

图片

标签: javaimagebufferedimage

解决方案


推荐阅读