Java 如何将彩色图像转换为纯黑白图像(0-255格式) 公共类黑白{ 公共静态void main(字符串[]args) { 尝试 { BuffereImage original=ImageIO.read(新文件(“彩色图像”); BuffereImage binarized=新的BuffereImage(original.getWidth()、original.getHeight()、BuffereImage.TYPE_BYTE_BINARY); 红色; 整数像素; int阈值=230; 对于(int i=0;i
您正在将图像正确地从彩色转换为黑白;但是,当您将输出另存为Java 如何将彩色图像转换为纯黑白图像(0-255格式) 公共类黑白{ 公共静态void main(字符串[]args) { 尝试 { BuffereImage original=ImageIO.read(新文件(“彩色图像”); BuffereImage binarized=新的BuffereImage(original.getWidth()、original.getHeight()、BuffereImage.TYPE_BYTE_BINARY); 红色; 整数像素; int阈值=230; 对于(int i=0;i,java,image,swing,image-processing,bufferedimage,Java,Image,Swing,Image Processing,Bufferedimage,您正在将图像正确地从彩色转换为黑白;但是,当您将输出另存为JPEG时,会创建一些颜色 只需将输出保存到PNG(或JPEG以外的任何格式),输出将如您所期望的那样仅为黑白 public class BlackWhite { public static void main(String[] args) { try { BufferedImage original = ImageIO.read(new File("colorima
JPEG
时,会创建一些颜色
只需将输出保存到PNG
(或JPEG
以外的任何格式),输出将如您所期望的那样仅为黑白
public class BlackWhite {
public static void main(String[] args)
{
try
{
BufferedImage original = ImageIO.read(new File("colorimage"));
BufferedImage binarized = new BufferedImage(original.getWidth(), original.getHeight(),BufferedImage.TYPE_BYTE_BINARY);
int red;
int newPixel;
int threshold =230;
for(int i=0; i<original.getWidth(); i++)
{
for(int j=0; j<original.getHeight(); j++)
{
// Get pixels
red = new Color(original.getRGB(i, j)).getRed();
int alpha = new Color(original.getRGB(i, j)).getAlpha();
if(red > threshold)
{
newPixel = 0;
}
else
{
newPixel = 255;
}
newPixel = colorToRGB(alpha, newPixel, newPixel, newPixel);
binarized.setRGB(i, j, newPixel);
}
}
ImageIO.write(binarized, "jpg",new File("blackwhiteimage") );
}
catch (IOException e)
{
e.printStackTrace();
}
}
private static int colorToRGB(int alpha, int red, int green, int blue) {
int newPixel = 0;
newPixel += alpha;
newPixel = newPixel << 8;
newPixel += red; newPixel = newPixel << 8;
newPixel += green; newPixel = newPixel << 8;
newPixel += blue;
return newPixel;
}
}
例如,如果您有一个保存为PNG
的二值图像,则直方图可能类似(仅限黑白像素):
对于相同的图像,如果保存为JPEG
,可以看到在直方图中,一些靠近白色和黑色的像素开始出现
是的,除了
JPEG
我只是举个例子,你为什么关心alpha
?
ImageIO.write(binarized, "png",new File("blackwhiteimage") );