Waiting for an image to be loaded

Using javax.swing.ImageIcon

Main.java:

import javax.swing.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame {
   public static void main(String []args) throws Exception {
      Main main = new Main();
      main.loadImage(new URL("http://www.esus.com/images/space.jpg"));
      System.exit(0);
   }
 
   public Image loadImage(URL url) throws Exception {
      System.out.print("Loading image... ");   
      Image image = new javax.swing.ImageIcon(url).getImage(); 
      System.out.println("done!");
      return image;
   }
}

Using MediaTracker

Main.java:

import javax.swing.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame {
   public static void main(String []args) throws Exception {
      Main main = new Main();
      main.loadImage(new URL("http://www.esus.com/images/space.jpg"));
      System.exit(0);
   }
 
   public Image loadImage(URL url) throws Exception {
      MediaTracker mt = new MediaTracker(this);
 
      Image image = Toolkit.getDefaultToolkit().getImage(url);
  
      // add image to MediaTracker registry and give it an ID
      mt.addImage(image, 1); 
 
      System.out.print("Loading image... "); 
      // wait for that ID to be completed
      boolean status = false;
      try { 
         mt.waitForID(1); 
         
         status = mt.checkID(1, true); 
      } 
      catch (InterruptedException e) { }
      System.out.println("done! (status = " + status + ")");
 
      return image;
   }
}

Drawing text on top of a BufferedImage

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   BufferedImage image;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      createImage();
   }
 
   public void createImage() {
      Image backImage = new javax.swing.ImageIcon("mong.jpg").getImage(); 
      int width = backImage.getWidth(this); 
      int height = backImage.getHeight(this); 
      image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
      Graphics2D g2d = image.createGraphics(); 
      g2d.drawImage(backImage, 0, 0, this); 

      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                           RenderingHints.VALUE_ANTIALIAS_ON);
      Font f = new Font("Mistral", Font.BOLD, 56);
      g2d.setFont(f);
      String text = "Philip Elliott";
      FontMetrics fm = getFontMetrics(f);       
      int swidth = fm.stringWidth(text);
      int sheight = fm.getAscent();
 
      GradientPaint gp = new GradientPaint(20, 50, Color.red, 
                                           100, 130, Color.yellow, true); 
      g2d.setPaint(gp);
      g2d.drawString(text, width/2 - swidth/2, height/2 + sheight/2);   
 
      setSize(width, height);
   }
  
   public void paint(Graphics g) { 
      Graphics2D g2d = (Graphics2D) g; 
 
      g2d.drawImage(image, null, 0, 0); 
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
   }
}

Image used:

Creating image thumbnails

Use the class AffineTransform.

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
 
public class Main extends JFrame {
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
   }
 
   public void createThumbs() {
      setTitle("JPG thumbnail images of " + System.getProperty("user.dir"));
 
      File f[] = new File(".").listFiles();
      for (int i=0; i<f.length; i++) {
         if (f[i].getName().endsWith(".jpg")) {
            ImageIcon imageIcon = new ImageIcon(f[i].getName()); 
            ImageIcon image = getThumb(imageIcon, 50);
            JLabel label = new JLabel(image);
            label.setToolTipText(f[i].getName());
            getContentPane().add(label);
            validate();
         }
      }
   } 
  
   public ImageIcon getThumb(ImageIcon imageIcon, int wh) {
      Image source = imageIcon.getImage();
 
      double scalex = (double) wh / source.getWidth(null);
      double scaley = (double) wh / source.getHeight(null);
 
      BufferedImage dest = new BufferedImage(wh, wh, 
                                    BufferedImage.TYPE_INT_RGB);
 
      AffineTransform ta = new AffineTransform();
      ta.scale(scalex, scaley);
          
      Graphics2D g2d = dest.createGraphics();
      g2d.drawImage(source, ta, null);
      g2d.dispose();
 
      return new ImageIcon(dest); 
    }

   public static void main(String[] args) {
      Main main = new Main();
      main.setSize(500, 150);
      main.setVisible(true);
 
      main.createThumbs();
   } 
}

Read a JPG image, rescale it, and write it back to disk

This example shows how to read, scale and rewrite all jpeg images from the current directory.

Main.java:

import com.sun.image.codec.jpeg.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
 
public class Main
{
   private final static float JPG_QUALITY = 1f;   // keep original JPEG quality
  
   public static void main(String []args) throws Exception {
      if (args.length != 2) {
         System.err.println("Usage: java Main scalex scaley");
         System.err.println("Scales all .jpg and .gif images to scalex, scaley");
         System.exit(1);
      } 
 
      int scalex = Integer.parseInt(args[0]);
      int scaley = Integer.parseInt(args[1]);
 
      File f = new File(".");
      String[] fileList = f.list();
 
      for (int i=0; i<fileList.length; i++) {
         if (fileList[i].endsWith(".jpg")) {
            System.out.print("Rescaling " + fileList[i] + "...");  
            readScaleWrite(fileList[i], scalex, scaley);
            System.out.println(" done.");
         }
      }
 
      System.exit(1);
   }
 
   public static void readScaleWrite(String filename, int scalex, int scaley) 
                                                           throws Exception {
      Image img = new javax.swing.ImageIcon(filename).getImage(); 
      BufferedImage bi = toBufferedImage(img);
      BufferedImage scaledBi = new BufferedImage(scalex, scaley, bi.getType());
 
      AffineTransform at = new AffineTransform();
      at.scale((double) scalex / bi.getWidth(), (double) scaley / bi.getHeight());
 
      Graphics2D g2d = scaledBi.createGraphics();
      g2d.drawImage(bi, at, null);
      g2d.dispose();
 
      FileOutputStream fos = new FileOutputStream(filename);
      if (filename.endsWith(".jpg")) {
         JPGWrite(scaledBi, fos);
      }
      fos.close();
   }
 
   public static void JPGWrite(BufferedImage bi, OutputStream out) throws IOException {
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
      JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
      param.setQuality(JPG_QUALITY, true);
      encoder.encode(bi, param);
   }
 
   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;
   }
}

Setting individual pixels in a BufferedImage in Swing

You can use the method setRGB. This example goes through a loop painting each pixel of the BufferedImage individually.

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private boolean firstTime = true;
   private BufferedImage bufferedImage;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      }); 
   } 
 
   public void paint(Graphics graphics) {
      Graphics2D g2d = (Graphics2D) graphics;
  
      g2d.drawString("Please wait...", 100, 100);
      if (firstTime) {
         bufferedImage = (BufferedImage) createImage(getSize().width, getSize().height);
 
         int x=0, y=0;
         for (int r=0; r<=255; r+=4) {
            for (int g=0; g<=255; g+=4) {
               for (int b=0; b<=255; b+=4) {
                  x++; if (x>getSize().width) { y++; x = 0; }
                  Color c = new Color(r, g, b);
                  bufferedImage.setRGB(x, y, c.getRGB());
               }
            }
         }
 
         firstTime = false;
      }
 
      g2d.drawImage(bufferedImage, 0, 0, this);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
      main.setSize(512, 512);
   }
}

Converting an Image to a BufferedImage in Swing

This following example reads a JPEG imgage from disk, converts it to a bufferedimage and displays it onto the screen.

import java.awt.event.*;
import java.awt.image.*;
import java.awt.color.*;
import javax.swing.*;
import java.awt.*;
                           
public class Main extends JFrame
{
   public Main() throws Exception {
      BufferedImage bi = createBufferedImage("ally.jpg");
                       
      // add the image inside a JLabel component to the window
      getContentPane().add(new JLabel(new ImageIcon(bi)));
      pack();
                         
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public BufferedImage createBufferedImage(String filename) {
      Image img = Toolkit.getDefaultToolkit().getImage(filename);
      try {
         MediaTracker tracker = new MediaTracker(this);
         tracker.addImage(img, 0);
         tracker.waitForID(0);
      }
      catch ( Exception e ) {} 
 
      BufferedImage bi = 
         new BufferedImage(img.getWidth(this), img.getHeight(this),
                        BufferedImage.TYPE_INT_RGB);
      Graphics2D g2d = bi.createGraphics();
      g2d.drawImage(img, 0, 0, this);
 
      return bi;
   }
 
   public static void main(String args[]) throws Exception {
      Main main = new Main();
      main.show();
   }
}

Converting a color image to a black and white one in Swing

Use the ColorConvertOp class. Its filter() method does a pixel-by-pixel color conversion of the original image.
Following example captures the screen, converts it to gray-scale and displays it in a window:

import java.awt.event.*;
import java.awt.image.*;
import java.awt.color.*;
import javax.swing.*;
import java.awt.*;
  
public class Main extends JFrame
{
   public Main() throws Exception {
      Robot robot = new Robot();
      int width = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
      int height = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
 
      // capture the whole screen
      BufferedImage image = robot.createScreenCapture(new Rectangle(0, 0, width, height));
  
      // convert to black and white
      BufferedImage bwimage = convert2bw(image);
 
      // add the image inside a JLabel component to the window
      getContentPane().add(new JLabel(new ImageIcon(bwimage)));
      pack();
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   // converts an image to a black and white one
   public BufferedImage convert2bw(BufferedImage image) {
      ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
      ColorConvertOp ccop = new ColorConvertOp(cs, null);

      return ccop.filter(image, null);
   }
  
   public static void main(String args[]) throws Exception {
      Main main = new Main();
      main.show();
   }
}

Clip an image to be rendered with a text in Swing



Main.java:

import java.awt.image.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.font.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private BufferedImage image; 
   private boolean clip = false;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      image = toBufferedImage(new javax.swing.ImageIcon("djkrush.jpg").getImage());
      JButton button = new JButton("Clip to Text");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            clip = true;
            repaint();
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.SOUTH, button);
   }
 
   public void paint(Graphics g) {
      super.paint(g);
 
      Graphics2D g2d = (Graphics2D) g;
 
      if (clip) {
         int w = getSize().width;
         int h = getSize().height;
 
         FontRenderContext frc = g2d.getFontRenderContext();
         Font font = new Font("Helvetica", Font.PLAIN, 12);
         TextLayout tl = new TextLayout("ALICIA", font, frc);
 
         double stringWidth = tl.getBounds().getWidth();
         double stringHeight = tl.getBounds().getHeight();
 
         // determine to what extend the string should be 
         // scaled in order to fill the window
         double scalex = (w - 50) / stringWidth;
         double scaley = (h - 50) / stringHeight;
         AffineTransform ta = AffineTransform.getScaleInstance(scalex, scaley);
 
         // transform the string in a shape
         Shape shape = tl.getOutline(ta);
 
         // position the shape
         double shapeWidth  = shape.getBounds().getWidth();
         double shapeHeight = shape.getBounds().getHeight();
         AffineTransform at = AffineTransform.getTranslateInstance(
                                                w / 2 - shapeWidth / 2, 
                                                h / 2 + shapeHeight / 2);
         shape = at.createTransformedShape(shape);
 
         g2d.clip(shape);
      }
 
      g2d.setColor(Color.red);
      g2d.fillRect(20, 50, 100, 140);
 
      Rectangle2D tr = new Rectangle2D.Double(0, 0, image.getWidth(), image.getHeight());
      TexturePaint tp = new TexturePaint(image, tr);
      g2d.setPaint(tp);
      g2d.fillRect(120, 50, 100, 140);
       
      g2d.setColor(Color.blue);
      g2d.fillRect(220, 50, 100, 140);
 
      g2d.setColor(Color.yellow);
      g2d.fillOval(320, 50, 100, 140);
   }
 
   public 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.setSize(440, 240);
      main.setVisible(true);
   }
}

Image used:

Clipping an image to be rendered with a shape in Swing



Main.java:

import java.awt.image.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private BufferedImage image; 
   private boolean clip = false;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      image = toBufferedImage(new javax.swing.ImageIcon("djkrush.jpg").getImage());
      JButton button = new JButton("Clip to QuadCurve");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            clip = true;
            repaint();
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.SOUTH, button);
   }
 
   public void paint(Graphics g) {
      super.paint(g);
 
      Graphics2D g2d = (Graphics2D) g;
 
      if (clip) {
         BasicStroke bs = new BasicStroke(50, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
                                          10, null, 0);
         g2d.setStroke(bs);
         QuadCurve2D.Float qc = new QuadCurve2D.Float(20, 50, 100, 140, 460, 170);
         g2d.setClip(qc);
      }
 
      // draw texture filled ellipse
      g2d.drawRect(20, 50, 80, 120);
      g2d.drawOval(140, 50, 80, 120);
      
      BasicStroke bs = new BasicStroke(5, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
                           10, new float[] {10}, 0);
      g2d.setStroke(bs);
      g2d.drawRect(260, 50, 80, 120);
 
      Rectangle2D tr = new Rectangle2D.Double(0, 0, image.getWidth(), image.getHeight());
      TexturePaint tp = new TexturePaint(image, tr);
      g2d.setPaint(tp);
      g2d.fillRect(380, 50, 80, 120);
   }
 
   public 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.setSize(480, 240);
      main.setVisible(true);
   }
}

Image used:

Drawing an image in Swing

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private Image image;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      image = Toolkit.getDefaultToolkit().getImage("c:\djkrush.jpg");
   }
 
   public void paint(Graphics g) {
      g.drawImage(image, 0, 20, this);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(150, 150);
      main.setVisible(true);
   }
}

Image used: