我试图将彩色图像转换为可使用的单色图像,但没有“锯齿”边缘。
从类似的问题asking to convert an image from color to black and white,其中一个公认的答案提供了一个简单的技巧,从JavaFX的ColorAdjust类使用setBrightness(-1)技术。这种技术的好处是保持黑白之间的软边,如支持高对比度主题,而不创建所有新的图标集。
注意:--我理解这里单词“单色”的不精确性(会出现一些灰度缩放),但我不知道如何描述这种技术。
使用纯Java模拟ColorAdust技术的方法是什么?
所需:

不想要:

发布于 2019-07-02 22:05:04
这是一种纯Java方法。创建图像不需要Swing代码。我们不是将图像更改为黑白,而是将图像更改为黑色和透明性。这就是我们保护羽毛边缘的方法。
结果:

如果您想要一个没有alpha的真正灰度图像,请制作一个graphics2d对象,用所需的背景色填充它,然后将图像绘制到它上。
至于保护白人为白人,这是可以做到的,但有两件事必须承认。要么你放弃黑白的一面,采用真正的灰度图像,要么你保持你的黑白,但得到一个锯齿状的边缘,白色羽毛进入任何其他颜色。这是因为一旦我们击中一个浅色像素,我们如何知道它是一个浅色特征,或过渡像素之间的白色和另一种颜色。我不知道如何在没有边缘检测的情况下解决这个问题。
public class Main {
private static void createAndShowGUI() {
//swing stuff
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Alpha Mask");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));
JLabel picLabel = new JLabel(new ImageIcon(getImg()));
frame.getContentPane().add(picLabel);
BufferedImage alphaMask = createAlphaMask(getImg());
JLabel maskLabel = new JLabel(new ImageIcon(alphaMask));
frame.getContentPane().add(maskLabel);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static BufferedImage getImg() {
try {
return ImageIO.read(new URL("https://i.stack.imgur.com/UPmqE.png"));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static BufferedImage createAlphaMask(BufferedImage img) {
//TODO: deep copy img here if you actually use this
int width = img.getWidth();
int[] data = new int[width];
for (int y = 0; y < img.getHeight(); y++) {
// pull down a line if argb data
img.getRGB(0, y, width, 1, data, 0, 1);
for (int x = 0; x < width; x++) {
//set color data to black, but preserve alpha, this will prevent harsh edges
int color = data[x] & 0xFF000000;
data[x] = color;
}
img.setRGB(0, y, width, 1, data, 0, 1);
}
return img;
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(() -> createAndShowGUI());
}
}https://stackoverflow.com/questions/56856443
复制相似问题