Fading in/out an image in Swing

Apply a ConvolveOp filter with the following kernel to your image:

	[ 0  0  0
        0  fadeFactor  0
        0  0  0 ]

To fade in, increase fadeFactor by some number (in our example .1). To fade out, decrease fadeFactor.

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame implements Runnable {
   private BufferedImage sourceBi;
   private BufferedImage destBi;
   private float fadeFactor = 1f;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      }); 
 
      Image img = new javax.swing.ImageIcon("djkrush.jpg").getImage(); 
      sourceBi = toBufferedImage(img);
      setSize(img.getWidth(null), 25+img.getHeight(null)*2);
   } 
 
   public void paint(Graphics graphics) {
      Graphics2D g2d = (Graphics2D) graphics;
  
      g2d.drawImage(sourceBi, 0, 20, this);
      if (destBi != null) {
         g2d.drawImage(destBi, 0, 20+sourceBi.getHeight(), this);
      }
   }
 
   public void run() {
      while (true) {
         fadeIn(); 
         sleep(3000);
         fadeOut();
         sleep(3000);
      }
   }
 
   public void sleep(long millis) {
      try {
         Thread.sleep(millis);
      }
      catch(InterruptedException e) {
      }
   }
 
   public void fadeIn() {
      fadeFactor = 0;
      for (int i=0; i<10; i++) {
         fadeFactor += .1;
         performConvolve();
         repaint();
         sleep(100);
      }
   }
 
   public void fadeOut() {
      for (int i=0; i<10; i++) {
         fadeFactor -= .1;
         performConvolve();
         repaint();
         sleep(100);
      }
   }
 
   public void performConvolve() {
      destBi = new BufferedImage(sourceBi.getWidth(), sourceBi.getHeight(), 
                                 BufferedImage.TYPE_INT_RGB);
  
      Kernel kernel = new Kernel(3, 3, new float[] 
                                         { 0, 0, 0,
                                           0, fadeFactor, 0,
                                           0, 0, 0 });
      ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
      cOp.filter(sourceBi, destBi);
   }
 
   public static BufferedImage toBufferedImage(Image image) {
      BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), 
                                           BufferedImage.TYPE_INT_RGB); 
 
      // copy the original image
      Graphics g = bi.createGraphics();
    
      g.drawImage(image, 0, 0, null);
      g.dispose();
 
      return bi;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
 
      Thread t = new Thread(main);
      t.start();
   }
}

Image used:


To learn more about image processing,
check out this excellent but expensive book: