Page 1 of 1

Java Image Manipulation Part 1: Loading Shows how to load images. Rate Topic: ***** 1 Votes

#1 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2861
  • View blog
  • Posts: 10,968
  • Joined: 15-July 08

Posted 18 March 2010 - 08:59 AM

Java Image Manipulation – Part 1
~ Dogstopper

Image manipulation is something that is very necessary to do in Java for various reasons, whether that reason be so that you can have images on icons for Jbuttons or Jlabels, or have images for games. Either way, they both start the same way: you have to load them. Now, I hope that in today's lesson, I can also demonstrate the importance of packages when using resources (not solely for images). With correct packaging, one does not have to worry about JAR files behaving differently than just standard class files do.

Loading ImageIcons
So, we shall begin by learning about ImageIcon, which is primarily for spicing up JLabels, Jbuttons and the like. So, let's begin by loading it:

*Notice the package
package com.thousandcodes.imagespart1;

import java.net.URL;
import javax.swing.*;

public class Tutorial extends JFrame {
	
	private JLabel imageLabel;
	private ImageIcon image;
	
	public Tutorial() {
		
		// Get a URL to our image, which is going to be in a
		// subdirectory called images.
		URL imgURL = getClass().getResource("images/i2.png");
		
		// If our URL exists
	    if (imgURL != null) {
	    	// Then make a new icon. Notice the second argument
	    	// is for those people that are visually impaired
	        image = new ImageIcon(imgURL, "This is our icon");
	        
	    // Otherwise, if the image cannot be found, then quit.
	    } else {
	    	System.out.println("There was an error. The image was not loaded");
	    	System.exit(1);
	    }
	    
	    // Make a JLabel with the image on it and add it.
	    imageLabel = new JLabel(image);
	    add(imageLabel);
	    
	    // Standard JFrame things to do.
	    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    pack();
	    setVisible(true);
	}
	
	public static void main(String[] args) {
		new Tutorial();
	}
	
}



Now, the image is called i2.png and is located in the package com.thousandcodes.imagespart1.images. With this setup, the image can be accessed assuming it is all packaged together into the same JAR file. The URL is essentially a file location that makes file access easy because one doesn't have to worry about forward or backslashes based on the operating system. With a URL, it is always a forward slash.

Then it was a really simple matter of making a new JLabel with the image, and adding the JLabel to the JFrame.

Loading Images and BufferedImage
So see how easy the loading was with an ImageIcon? Well, that's nice, but not all the time can an ImageIcon be used. Usually, in gaming or image viewing applications and such similar things there is a need for something a bit...more...Thus comes the abstract class Image and concrete class BufferedImage. These two classes are going to be the focus of later image manipulation tutorials.

Now, loading a BufferedImage is a little bit more tricky as the loading is not quite so pretty. In this next example, I will use an InputStream to load the file. This involves grabbing the current class and then loading in the image as a resource. I understand that this may be complicated, but after working on it for a while, you begin to see it. Now, to actually load the image you can use the read() method of javax.imageio.ImageIO class.

The read() method is static and can take 4 different types of arguments, a File, an InputSream, an ImageInputStream, or a URL. It returns a BufferedImage. For computer-based applications, you will use the InputStream most often and for web-based applications, you will use URL most frequently. Let's take a look at our panel.

	private class PicturePanel extends JPanel {
		
		BufferedImage img;
		
		public PicturePanel() {
			// Load the image 
			img = getImage("images/space-2.jpg");
			
			// Make the panel as big as the image is.
			this.setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
		}
		
		public void paintComponent(Graphics g) {
			// Draw the image on the panel
			g.drawImage(img, 0,0,null);
		}
		
		private BufferedImage getImage(String filename) {
			// This time, you can use an InputStream to load
			try {
				// Grab the InputStream for the image.
				InputStream in = getClass().getResourceAsStream(filename);
				
				// Then read it in.
				return ImageIO.read(in);
			} catch (IOException e) {
				System.out.println("The image was not loaded.");
				System.exit(1);
			}
			return null;
		}
	}



Using ImageIO.read(), this was way easy to load and paint to a panel. Now all you have to do is make a JFrame class to use this PicturePanel. Notice the setPreferredSize(). If you call pack() on a JFrame that has added this component, then it will respect the size that the JPanel wishes to be at.

Here is the full file including imports so that you can see how it all works.
package com.thousandcodes.imagespart1;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Tutorial extends JFrame {
	
	public Tutorial() {
		
		add(new PicturePanel());
	    
	    // Standard JFrame things to do.
	    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    pack();
	    setVisible(true);
	}
	
	private class PicturePanel extends JPanel {
		
		BufferedImage img;
		
		public PicturePanel() {
			// Load the image 
			img = getImage("images/space-2.jpg");
			
			// Make the panel as big as the image is.
			this.setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
		}
		
		public void paintComponent(Graphics g) {
			// Draw the image on the panel
			g.drawImage(img, 0,0,null);
		}
		
		private BufferedImage getImage(String filename) {
			// This time, you can use an InputStream to load
			try {
				// Grab the InputStream for the image.
				InputStream in = getClass().getResourceAsStream(filename);
				
				// Then read it in.
				return ImageIO.read(in);
			} catch (IOException e) {
				System.out.println("The image was not loaded.");
				System.exit(1);
			}
			return null;
		}
	}

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



Downloading Images Using ImageIO
Remember how I said that you can use ImageIO to utilize URLs in web applications? Well, all you have to do is to use the exact same read() method, just with a URL to the Internet image that you wish to download. Let's download the guy from from Java Tutorials located here:
http://java.sun.com/...ges/penduke.gif

All you have to do is make a quick change to the PicturePanel class. Change the name of the file location in the constructor and change the InputStream to a java.net.URL.

private class PicturePanel extends JPanel {
		
		BufferedImage img;
		
		public PicturePanel() {
			// Load the image 
			img = getImage("http://java.sun.com/docs/books/tutorial/images/penduke.gif");
			
			// Make the panel as big as the image is.
			this.setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
		}
		
		public void paintComponent(Graphics g) {
			// Draw the image on the panel
			g.drawImage(img, 0,0,null);
		}
		
		private BufferedImage getImage(String filename) {
			// This time, you can use an InputStream to load
			try {
				// Grab the URL for the image
				URL url = new URL(filename);
				
				// Then read it in.
				return ImageIO.read(url);
			} catch (IOException e) {
				System.out.println("The image was not loaded.");
				System.exit(1);
			}
			return null;
		}
	}




I hope that about covers it! I hope you learned something today.
Oh, and here are the two images that I used if you're interested:
i2.png: Attached Image
space-2.jpg: Attached Image

This post has been edited by Dogstopper: 18 March 2010 - 09:03 AM


Is This A Good Question/Topic? 2
  • +

Replies To: Java Image Manipulation Part 1: Loading

#2 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2861
  • View blog
  • Posts: 10,968
  • Joined: 15-July 08

Posted 18 March 2010 - 09:11 AM

Sorry, the font tags messed up coming from the text editor...I fixed them
Was This Post Helpful? 0
  • +
  • -

#3 NeoTifa  Icon User is online

  • Whorediot
  • member icon





Reputation: 2498
  • View blog
  • Posts: 15,473
  • Joined: 24-September 08

Posted 10 August 2010 - 09:30 AM

Beautiful sir.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1