这段代码是对我正在构建的更大程序的测试。应该将图像中的每个其他像素行着色为红色,但结果是在下面添加了图像。有人可以解释为什么红色不显示吗?

package code;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;

public class Pixel {

BufferedImage image;
int width;
int height;

public Pixel() throws IOException {
    File input = new File("/Users/SanchitBatra/Desktop/Depixelator.jpg");
    image = ImageIO.read(input);
    width = image.getWidth();
    height = image.getHeight();
}

public void changePixels() throws IOException{

        for(int i=0; i<height; i++){

            for(int j=0; j<width; j++){

                int red;
                //  Color c = new Color(image.getRGB(j, i));
                if(i%2==0){

                    red = 255;
                }
                else{
                    red=0;
                }
                int green = 0;
                int blue = 0;
                Color newColor = new Color(red, green, blue);

                image.setRGB(j,i,newColor.getRGB());

            }
        }

        File output = new File("/Users/SanchitBatra/Desktop/grayscale.jpg");
        ImageIO.write(image, "jpg", output);

    }


static public void main(String args[]) throws Exception {

    Pixel obj = new Pixel();
    obj.changePixels();
}
}


这是结果图像:

java - 有人可以解释为什么此代码不将图像中的每个其他像素列都着色为红色吗?-LMLPHP

编辑:该程序使用彩色图像作为源,正在执行其应做的工作。感谢所有贡献!我今天学到了很多:)

最佳答案

尝试这个:

public void changePixels() throws IOException{

    BufferedImage bi = new BufferedImage(side,side,BufferedImage.TYPE_INT_ARGB);
    int[] pixels = new int[width*height];

    for(int i=0; i<height; i++){

        for(int j=0; j<width; j++){
            int colorIn = image.getRGB(j,i);
            int redIn = 255&(colorIn<<16);
            int greenIn = 255&(colorIn<<8);
            int blueIn = 255&(colorIn);

            if(i%2==0){

                redIn = 255;
            }


            pixels[i+j*width] = (255<<24)|(redIn<<16)|(greenIn<<8)|blueIn;



        }
    }
    bi.setRGB(0, 0, width, height, pixels, 0, width);
    File output = new File("/Users/SanchitBatra/Desktop/grayscale.jpg");
    ImageIO.write(bi, "jpg", output);

}


我在这里向您展示了如何使用移位来拉出颜色值,以向您展示如何对过程进行更多控制。这还将保留原始像素值,并且如果它是偶数列,只会覆盖红色值。

10-07 13:17
查看更多