我当前的编程项目有问题。赋值调用从我的计算机中获取图像(我使用计算机提供的示例图片之一)并将其转换为灰度,绿色,红色和蓝色。我编写了该程序的代码,它成功转换了前两张图片(原始=>灰度和原始=>绿色),但当它转换为红色和蓝色时,它会产生一个全黑图像(应该是什么发生的是图片应该从原始=>红色和原始=>蓝色以及之前的两个转换,灰色和绿色转换。这是我的代码:
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class Prog3a
{
public static void main(String args[]) throws IOException
{
BufferedImage img = null;
File f = null;
//read image
try
{
f = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg");
img = ImageIO.read(f);
}
catch(IOException exception)
{
System.out.println(exception);
}
//get image width and height
int width = img.getWidth();
int height = img.getHeight();
//convert to grayscale
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
int p = img.getRGB(x,y);
int a = (p>>24)&0xff;
int r = (p>>16)&0xff;
int g = (p>>8)&0xff;
int b = p&0xff;
//calculate average
int avg = (r+g+b)/3;
//replace RGB value with avg
p = (a<<24) | (avg<<16) | (avg<<8) | avg;
img.setRGB(x, y, p);
}
}
//write image
try
{
File toGray = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\CS108toGray");
ImageIO.write(img, "jpg", toGray);
}
catch(IOException exception)
{
System.out.println(exception);
}
//convert to green image
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
int p = img.getRGB(x,y);
int a = (p>>24)&0xff;
int g = (p>>8)&0xff;
//set new RGB
p = (a<<24) | (0<<16) | (g<<8) | 0;
img.setRGB(x, y, p);
}
}
//write image
try
{
File toGreen = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\CS108toGreen");
ImageIO.write(img, "jpg", toGreen);
}
catch(IOException e)
{
System.out.println(e);
}
//convert to red image
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
int p = img.getRGB(x,y);
int a = (p>>24)&0xff;
int r = (p>>16)&0xff;
//set new RGB
p = (a<<24) | (r<<16) | (0<<8) | 0;
img.setRGB(x, y, p);
}
}
//write image
try
{
File toRed = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\CS108toRed");
ImageIO.write(img, "jpg", toRed);
}
catch(IOException e)
{
System.out.println(e);
}
//convert to blue image
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
int p = img.getRGB(x,y);
int a = (p>>24)&0xff;
int b = p&0xff;
//set new RGB
p = (a<<24) | (0<<16) | (0<<8) | b;
img.setRGB(x, y, p);
}
}
//write image
try
{
File toBlue = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\CS108toBlue");
ImageIO.write(img, "jpg", toBlue);
}
catch(IOException e)
{
System.out.println(e);
}
}
}
如何修改程序以使红色和蓝色图像转换器正确地将图像转换为各自的颜色?作为一名初学程序员,我们非常感谢您提供的任何意见和建议,谢谢。