有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java字节图像处理

我需要用Java创建一个简单的图像处理演示。我的代码是基于swing的。我不需要做任何复杂的事情,只要显示图像在某种程度上发生了变化。我把图像读为byte[]。无论如何,我可以在不破坏字节的情况下操作这个字节数组,以显示一些非常简单的操作。我不想使用paint()等。我可以直接对byte[]数组执行任何操作来显示一些更改吗

编辑:
我正在使用ApacheIO库以byteArrayInputStream的形式读取jpg图像。字节读取正常,我可以通过将它们写回jpeg来确认


共 (1) 个答案

  1. # 1 楼答案

    您可以尝试将RGB图像转换为灰度。如果图像以每像素3字节的形式表示为红-绿-蓝,则可以使用以下公式:y=0.299*r+0.587*g+0.114*b

    为了清楚起见,迭代字节数组并替换颜色。这里有一个例子:

        byte[] newImage = new byte[rgbImage.length];
    
        for (int i = 0; i < rgbImage.length; i += 3) {
            newImage[i] = (byte) (rgbImage[i] * 0.299 + rgbImage[i + 1] * 0.587
                    + rgbImage[i + 2] * 0.114);
            newImage[i+1] = newImage[i];
            newImage[i+2] = newImage[i];
        }
    

    更新:

    以上代码假设您使用的是原始RGB图像,如果需要处理Jpeg文件,可以执行以下操作:

            try {
                BufferedImage inputImage = ImageIO.read(new File("input.jpg"));
    
                BufferedImage outputImage = new BufferedImage(
                        inputImage.getWidth(), inputImage.getHeight(),
                        BufferedImage.TYPE_INT_RGB);
                for (int x = 0; x < inputImage.getWidth(); x++) {
                    for (int y = 0; y < inputImage.getHeight(); y++) {
                        int rgb = inputImage.getRGB(x, y);
                        int blue = 0x0000ff & rgb;
                        int green = 0x0000ff & (rgb >> 8);
                        int red = 0x0000ff & (rgb >> 16);
                        int lum = (int) (red * 0.299 + green * 0.587 + blue * 0.114);
                        outputImage
                                .setRGB(x, y, lum | (lum << 8) | (lum << 16));
                    }
                }
                ImageIO.write(outputImage, "jpg", new File("output.jpg"));
            } catch (IOException e) {
                e.printStackTrace();
            }