java – 将图像转换为黑白图像

前端之家收集整理的这篇文章主要介绍了java – 将图像转换为黑白图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在imagemagick中使用如下命令将图像转换为黑色和白色:
convert myimg.png -monochrome  out3.png

我想知道它是否有可能在Java中实现相同的结果?不使用Im4Java或JMagick?

解决方法

我想这取决于你所说的“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,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,this);
                x += master.getWidth();
                g.drawImage(blackWhite,this);

            }
        }


    }
}
原文链接:https://www.f2er.com/java/127890.html

猜你在找的Java相关文章