Java Image Manipulation Part1

  • Upload
    axolnom

  • View
    219

  • Download
    0

Embed Size (px)

DESCRIPTION

Java Image Manipulation

Citation preview

  • Dream.In.Code> Programming Tutorials> Java TutorialsPage 1 of 1Java 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 necessaryto do in Java for various reasons, whether that reason beso that you can have images on icons for Jbuttons orJlabels, or have images for games. Either way, they bothstart the same way: you have to load them. Now, I hopethat in today's lesson, I can also demonstrate theimportance of packages when using resources (not solelyfor images). With correct packaging, one does not have toworry about JAR files behaving differently than juststandard class files do.

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

    *Notice the package

    General Discussion

    Caffeine Lounge

    Corner Cubicle

    Student Campus

    Software Development

    Industry News

    Introduce Yourself

    Nightmare.In.Code

    Programming Help

    C and C++

    VB.NET

    Java

    C#

    ASP.NET

    .NET Framework

    VB6

    PHP

    Ruby

    Python

    ColdFusion

    Databases

    Other Languages

    Game Development

    Mobile Development

    52 Weeks Of Code

    Web Development

    Web Development

    HTML & CSS

    JavaScript

    Graphic Design

    Flash & ActionScript

    Blogging

    SEO & Advertising

    Web Servers & Hosting

    Follow & Share

    Java TutorialsSwing, Passive Model-

    View-Presenter in 5

    minutes.

    Book Review: Murach's

    Java Servlets and JSP

    Phobos - A JavaFX

    Games Engine: Part 2 -

    JavaFX Scene API and

    the FSM

    Maven Tutorial 2 -

    Adding Dependencies

    Maven Tutorial 1 -

    Installation and Getting

    Started

    Phobos - A JavaFX

    Games Engine: Part 1 -

    Intro to Threading and

    DP

    Swing to JavaFX

    Swing, Top-Down 2

    Swing, Top-Down (with

    GridBagLayout)

    Basic Java: Types,

    Variables, Operators

    217 More Java

    Tutorials...

    Reference Sheets

    01 package com.thousandcodes.imagespart1;

    02

    03 import java.net.URL;

    04 import javax.swing.*;

    05

    06 public class Tutorial extends JFrame {

    07

    08 private JLabel imageLabel;

    09 private ImageIcon image;

    10

    11 public Tutorial() {

    12

    13 // Get a URL to our image, which is

    going to be in a

    14 // subdirectory called images.

    15 URL imgURL =

    getClass().getResource("images/i2.png");

    16

    17 // If our URL exists

    18 if (imgURL != null) {

    19 // Then make a new icon. Notice

    the second argument

    20 // is for those people that are

    visually impaired

    21 image = new ImageIcon(imgURL,

    "This is our icon");

    22

    23 // Otherwise, if the image cannot be

    found, then quit.

    24 } else {

    25 System.out.println("There was an

    error. The image was not loaded");

    26 System.exit(1);

    27 }

    28

    29 // Make a JLabel with the image on it

    and add it.

    30 imageLabel = new JLabel(image);

    31 add(imageLabel);

    32

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

    1 of 7 15/09/2014 01:37 p.m.

  • Now, the image is called i2.png and is located in thepackage com.thousandcodes.imagespart1.images. Withthis setup, the image can be accessed assuming it is allpackaged together into the same JAR file. The URL isessentially a file location that makes file access easybecause one doesn't have to worry about forward orbackslashes 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 JLabelwith the image, and adding the JLabel to the JFrame.

    Loading Images and BufferedImageSo see how easy the loading was with an ImageIcon?Well, that's nice, but not all the time can an ImageIcon beused. Usually, in gaming or image viewing applicationsand such similar things there is a need for something abit...more...Thus comes the abstract class Image andconcrete class BufferedImage. These two classes aregoing to be the focus of later image manipulationtutorials.

    Now, loading a BufferedImage is a little bit more tricky asthe loading is not quite so pretty. In this next example, Iwill use an InputStream to load the file. This involvesgrabbing the current class and then loading in the imageas 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 typesof arguments, a File, an InputSream, anImageInputStream, or a URL. It returns a BufferedImage.For computer-based applications, you will use theInputStream most often and for web-based applications,you will use URL most frequently. Let's take a look at ourpanel.

    Site Check

    Code SnippetsC Snippets

    C++ Snippets

    Java Snippets

    Visual Basic Snippets

    C# Snippets

    VB.NET Snippets

    PHP Snippets

    Python Snippets

    Ruby Snippets

    ColdFusion Snippets

    SQL Snippets

    Assembly Snippets

    Functional

    Programming Snippets

    Perl Snippets

    HTML/CSS Snippets

    Javascript Snippets

    Flash/ActionScript

    Snippets

    Other Languages

    Snippets

    DIC ChatroomJoin our IRC Chat

    Bye Bye Ads

    FAQ Advertising | Terms of Use | Privacy Policy |About Us

    MediaGroup1 LLC, All Rights Reserved Production - Version 6.0.2.1.36

    Server: secure3

    33 // Standard JFrame things to do.

    34 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    35 pack();

    36 setVisible(true);

    37 }

    38

    39 public static void main(String[] args) {

    40 new Tutorial();

    41 }

    42

    43 }

    01 private class PicturePanel extends JPanel {

    02

    03 BufferedImage img;

    04

    05 public PicturePanel() {

    06 // Load the image

    07 img = getImage("images/space-2.jpg");

    08

    09 // Make the panel as big as the image

    is.

    10 this.setPreferredSize(new

    Dimension(img.getWidth(), img.getHeight()));

    11 }

    12

    13 public void paintComponent(Graphics g) {

    14 // Draw the image on the panel

    15 g.drawImage(img, 0,0,null);

    16 }

    17

    18 private BufferedImage getImage(String

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

    2 of 7 15/09/2014 01:37 p.m.

  • Using ImageIO.read(), this was way easy to load andpaint to a panel. Now all you have to do is make a JFrameclass to use this PicturePanel. Notice thesetPreferredSize(). If you call pack() on a JFrame that hasadded this component, then it will respect the size thatthe JPanel wishes to be at.

    Here is the full file including imports so that you can seehow it all works.

    filename) {

    19 // This time, you can use an

    InputStream to load

    20 try {

    21 // Grab the InputStream for the

    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 }

    01 package com.thousandcodes.imagespart1;

    02

    03 import java.awt.Dimension;

    04 import java.awt.Graphics;

    05 import java.awt.image.BufferedImage;

    06 import java.io.IOException;

    07 import java.io.InputStream;

    08

    09 import javax.imageio.ImageIO;

    10 import javax.swing.JFrame;

    11 import javax.swing.JPanel;

    12

    13 public class Tutorial extends JFrame {

    14

    15 public Tutorial() {

    16

    17 add(new PicturePanel());

    18

    19 // Standard JFrame things to do.

    20 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    21 pack();

    22 setVisible(true);

    23 }

    24

    25 private class PicturePanel extends JPanel

    {

    26

    27 BufferedImage img;

    28

    29 public PicturePanel() {

    30 // Load the image

    31 img = getImage("images/space-

    2.jpg");

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

    3 of 7 15/09/2014 01:37 p.m.

  • Downloading Images Using ImageIORemember how I said that you can use ImageIO to utilizeURLs in web applications? Well, all you have to do is touse the exact same read() method, just with a URL to theInternet image that you wish to download. Let's downloadthe 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 thePicturePanel class. Change the name of the file location inthe constructor and change the InputStream to ajava.net.URL.

    32

    33 // Make the panel as big as the

    image is.

    34 this.setPreferredSize(new

    Dimension(img.getWidth(), img.getHeight()));

    35 }

    36

    37 public void paintComponent(Graphics g)

    {

    38 // Draw the image on the panel

    39 g.drawImage(img, 0,0,null);

    40 }

    41

    42 private BufferedImage getImage(String

    filename) {

    43 // This time, you can use an

    InputStream to load

    44 try {

    45 // Grab the InputStream for

    the image.

    46 InputStream in =

    getClass().getResourceAsStream(filename);

    47

    48 // Then read it in.

    49 return ImageIO.read(in);

    50 } catch (IOException e) {

    51 System.out.println("The image

    was not loaded.");

    52 System.exit(1);

    53 }

    54 return null;

    55 }

    56 }

    01 private class PicturePanel extends JPanel {

    02

    03 BufferedImage img;

    04

    05 public PicturePanel() {

    06 // Load the image

    07 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 this.setPreferredSize(new

    Dimension(img.getWidth(), img.getHeight()));

    11 }

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

    4 of 7 15/09/2014 01:37 p.m.

  • I hope that about covers it! I hope you learned somethingtoday.Oh, and here are the two images that I used if you'reinterested:

    i2.png: space-2.jpg:Resized to 50% (was 1000 x 1000) - Click image to enlarge

    12

    13 public void paintComponent(Graphics g)

    {

    14 // Draw the image on the panel

    15 g.drawImage(img, 0,0,null);

    16 }

    17

    18 private BufferedImage getImage(String

    filename) {

    19 // This time, you can use an

    InputStream to load

    20 try {

    21 // Grab the URL for the image

    22 URL url = new URL(filename);

    23

    24 // Then read it in.

    25 return ImageIO.read(url);

    26 } catch (IOException e) {

    27 System.out.println("The image

    was not loaded.");

    28 System.exit(1);

    29 }

    30 return null;

    31 }

    32 }

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

    5 of 7 15/09/2014 01:37 p.m.

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

    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 texteditor...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?

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

    6 of 7 15/09/2014 01:37 p.m.

  • 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

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

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