You are on page 1of 7

Java Image Manipulation Part 1: Loading - Java Tutorials | Dream.In.Code http://www.dreamincode.net/forums/topic/162748-java-image-manipulat...

Dream.In.Code> Programming Tutorials> Java Tutorials


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

Dogstopper

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


01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

1 of 7

package com.thousandcodes.imagespart1;

Follow & Share

General Discussion
Caffeine Lounge
Corner Cubicle
Student Campus
Software Development

Java Tutorials

Industry News

Swing, Passive Model-

Introduce Yourself

View-Presenter in 5

Nightmare.In.Code

minutes.
Book Review: Murach's

Programming Help

Java Servlets and JSP


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

C and C++

Phobos - A JavaFX
Games Engine: Part 2 -

public class Tutorial extends JFrame {


private JLabel imageLabel;
private ImageIcon image;

JavaFX Scene API and


the FSM
Maven Tutorial 2 Adding Dependencies

public Tutorial() {

Maven Tutorial 1 // 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);

VB.NET
Java
C#
ASP.NET
.NET Framework
VB6

Installation and Getting

PHP

Started

Ruby

Phobos - A JavaFX

Python

Games Engine: Part 1 -

ColdFusion

Intro to Threading and

Databases

DP

Other Languages

Swing to JavaFX

Game Development

Swing, Top-Down 2

Mobile Development

Swing, Top-Down (with

52 Weeks Of Code

GridBagLayout)
Basic Java: Types,

Web Development

Variables, Operators

Web Development

217 More Java

HTML & CSS

Tutorials...

JavaScript

Reference Sheets

Graphic Design
Flash & ActionScript
Blogging
SEO & Advertising
Web Servers & Hosting

15/09/2014 01:37 p.m.

Java Image Manipulation Part 1: Loading - Java Tutorials | Dream.In.Code http://www.dreamincode.net/forums/topic/162748-java-image-manipulat...

33
34
35
FAQ36
37
38
39
40
41
42
43

// Standard JFrame things to do.


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
Advertising
setVisible(true);

Site Check

| Terms of Use | Privacy Policy |

About Us

public static void main(String[] args) {


new Tutorial();
MediaGroup1
}

LLC, All Rights Reserved


Production - Version 6.0.2.1.36
Server: secure3

Code Snippets
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

C++ Snippets
Java Snippets
Visual Basic Snippets
C# Snippets
VB.NET Snippets

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.

PHP Snippets

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.

SQL Snippets

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.
01
02
03
04
05
06
07
08
09

private class PicturePanel extends JPanel {

10
11
12
13
14
15
16
17
18

Python Snippets
Ruby Snippets
ColdFusion Snippets

Assembly Snippets
Functional
Programming Snippets
Perl Snippets
HTML/CSS Snippets
Javascript Snippets
Flash/ActionScript
Snippets
Other Languages

BufferedImage img;
public PicturePanel() {
// Load the image
img = getImage("images/space-2.jpg");

Snippets

DIC Chatroom
Join our IRC Chat

// Make the panel as big as the image

Bye Bye Ads

is.

2 of 7

C Snippets

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

15/09/2014 01:37 p.m.

Java Image Manipulation Part 1: Loading - Java Tutorials | Dream.In.Code http://www.dreamincode.net/forums/topic/162748-java-image-manipulat...

filename) {
// This time, you can use an
InputStream to load
20
try {
// Grab the InputStream for the
21
image.
22
InputStream in =
getClass().getResourceAsStream(filename);
23
24
// Then read it in.
25
return ImageIO.read(in);
26
} catch (IOException e) {
27
System.out.println("The image was
not loaded.");
28
System.exit(1);
29
}
30
return null;
31
}
32 }
19

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.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

package com.thousandcodes.imagespart1;
import
import
import
import
import

java.awt.Dimension;
java.awt.Graphics;
java.awt.image.BufferedImage;
java.io.IOException;
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
{

26
27
28
29
30
31

BufferedImage img;
public PicturePanel() {
// Load the image
img = getImage("images/space2.jpg");

3 of 7

15/09/2014 01:37 p.m.

Java Image Manipulation Part 1: Loading - Java Tutorials | Dream.In.Code http://www.dreamincode.net/forums/topic/162748-java-image-manipulat...

32
33

// Make the panel as big as the


image is.

34
35
36
37

this.setPreferredSize(new
Dimension(img.getWidth(), img.getHeight()));
}
public void paintComponent(Graphics g)
{

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

// 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;
}
}

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 (http://java.sun.com
/docs/books/tutorial/images/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.
01
02
03
04
05
06
07

private class PicturePanel extends JPanel {


BufferedImage img;
public PicturePanel() {
// Load the image
img = getImage("http://java.sun.com
/docs/books/tutorial/images/penduke.gif
(http://java.sun.com/docs/books/tutorial/images
/penduke.gif) ");

08
09

// Make the panel as big as the


image is.

10
11

4 of 7

this.setPreferredSize(new
Dimension(img.getWidth(), img.getHeight()));
}

15/09/2014 01:37 p.m.

Java Image Manipulation Part 1: Loading - Java Tutorials | Dream.In.Code http://www.dreamincode.net/forums/topic/162748-java-image-manipulat...

12
13

public void paintComponent(Graphics g)


{

14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

// 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:
space-2.jpg:
Resized to 50% (was 1000 x 1000) - Click image to enlarge

5 of 7

15/09/2014 01:37 p.m.

Java Image Manipulation Part 1: Loading - Java Tutorials | Dream.In.Code http://www.dreamincode.net/forums/topic/162748-java-image-manipulat...

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


AM
Replies To: Java Image Manipulation Part 1: Loading

Dogstopper

Posted 18 March 2010 - 09:11 AM


Sorry, the font tags messed up coming from the text
editor...I fixed them

NeoTifa

Posted 10 August 2010 - 09:30 AM


Beautiful sir.
Page 1 of 1

Related Java Topicsbeta


Java Image Manipulation Part 3: Math And
SwingWorker Tutorial
Java Image Manipulation - Part 4: RescaleOp Filter
- Applying Image Filters Tutorial
Java Image Manipulation Part 2: Resizing Tutorial
Loading Image In To Java - Hi I Have An
Assignment Where I Am Gonna Load Images In To
My Program
Make Slideshow In JAVA - How To Create A
Slideshow In Java With Buttons?

6 of 7

15/09/2014 01:37 p.m.

Java Image Manipulation Part 1: Loading - Java Tutorials | Dream.In.Code http://www.dreamincode.net/forums/topic/162748-java-image-manipulat...

Java GUI - Click Button To Display Image


How To Display A Buffered Image
Java Media Framework (JMF) Problem Playing
Mp3 From A JAR
Image Input Exception?
Executable Jar File - Executable Jar File Not Picking
Image

7 of 7

15/09/2014 01:37 p.m.

You might also like