Thursday, April 15, 2021

[Java Code Sample] Add gray filter to image

 

Here's a sample Java code to add gray filter to an image.


Video tutorial:




Here's the code:




import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;

import javax.swing.GrayFilter;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
	
	JFrame window;
	JLabel pictureLabel;
	ImageIcon pic;

	public static void main(String[] args) {
		
		new Main();

	}
	public Main() {
				
		window = new JFrame();
		window.setSize(800,600);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.setLayout(null);
		
		pictureLabel = new JLabel();
		pictureLabel.setBounds(150,50,500,500);
		window.add(pictureLabel);
		
		pic = new ImageIcon(getClass().getClassLoader().getResource("ps.png"));
		
		pictureLabel.setIcon(pic);
		
		window.setVisible(true);
		
		addGrayFilter();
	}
	public void addGrayFilter() {
		
		Image colorImage = pic.getImage();
		ImageFilter iFilter = new GrayFilter(false, 10);
		ImageProducer iProducer = new FilteredImageSource(colorImage.getSource(), iFilter);
		Image grayImage = Toolkit.getDefaultToolkit().createImage(iProducer);
		ImageIcon grayIcon = new ImageIcon(grayImage);
		pictureLabel.setIcon(grayIcon);
	}
}

Result:

Without gray filter:



With gray filter:



end


No comments:

Post a Comment