1 回答

TA貢獻1839條經驗 獲得超15個贊
這是一種純 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());
}
}
添加回答
舉報