GrayImage.java Source code

Java tutorial

Introduction

Here is the source code for GrayImage.java

Source

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class GrayImage extends JPanel {
    public GrayImage() {
    }

    public void paint(Graphics g) {
        Image myImage = new ImageIcon("yourImage.png").getImage();
        BufferedImage bufferedImage = new BufferedImage(myImage.getHeight(this), myImage.getWidth(this),
                BufferedImage.TYPE_BYTE_GRAY);

        Graphics gi = bufferedImage.getGraphics();
        gi.drawImage(myImage, 0, 0, null);
        gi.dispose();

        Graphics2D g2d = (Graphics2D) g;
        g2d.drawImage(bufferedImage, null, 0, 0);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.add(new GrayImage());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}