本文介绍了如何使用Java将图像转换为黑白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用如下命令在 imagemagick 中将图像转换为黑白:
I convert an image to black&white in imagemagick with a command like this:
convert myimg.png -monochrome out3.png
我想知道是否有可能在 Java 中实现相同的结果?不使用 Im4Java 或 JMagick?
I'm wondering whether its possible to achieve the same result in Java? Without using Im4Java or JMagick?
推荐答案
我想这取决于你所说的单色"/黑白"是什么意思...
I guess it depends on what you mean by "mono-chrome"/"black & white"...
public class TestBlackAndWhite {
public static void main(String[] args) {
new TestBlackAndWhite();
}
public TestBlackAndWhite() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage master;
private BufferedImage grayScale;
private BufferedImage blackWhite;
public TestPane() {
try {
master = ImageIO.read(new File("C:/Users/shane/Dropbox/pictures/439px-Join!_It's_your_duty!.jpg"));
grayScale = ImageIO.read(new File("C:/Users/shane/Dropbox/pictures/439px-Join!_It's_your_duty!.jpg"));
ColorConvertOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
op.filter(grayScale, grayScale);
blackWhite = new BufferedImage(master.getWidth(), master.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g2d = blackWhite.createGraphics();
g2d.drawImage(master, 0, 0, this);
g2d.dispose();
} catch (IOException ex) {
ex.printStackTrace();
}
}
@Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
if (master != null) {
size = new Dimension(master.getWidth() * 3, master.getHeight());
}
return size;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (master != null) {
int x = (getWidth() - (master.getWidth() * 3)) / 2;
int y = (getHeight() - master.getHeight()) / 2;
g.drawImage(master, x, y, this);
x += master.getWidth();
g.drawImage(grayScale, x, y, this);
x += master.getWidth();
g.drawImage(blackWhite, x, y, this);
}
}
}
}
这篇关于如何使用Java将图像转换为黑白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!