image

Create Java BufferedImage from an Image

In this tutorial, we are going to show you how to create a BufferedImage in Java from a source Image. This is a basic operation if you want to perform several enhancements and transformations to your buffered image in java and this is fundamental for image processing.

1. Introduction

Buffered image in java class extends the Image class. There are 3 constructors available to create the BufferedImage object.

  • BufferedImage(ColorModel cm, WritableRaster raster, boolean isRasterPremultiplied, Hashtable properties): To create a new BufferedImage with a specified ColorModel, Raster and a set of properties.
  • BufferedImage(int width, int height, int imageType): To create a new BufferedImage of one of the predefined image types.
  • BufferedImage(int width, int height, int imageType, IndexColorModel cm): To create a BufferedImage of one of the predefined image types: TYPE_BYTE_BINARY or TYPE_BYTE_INDEXED.
Java BufferedImage

2. Steps to create BufferedImage in Java from Image

In order to create a BufferedImage from Image you should take the following steps:

  • Load an image from a source using Toolkit.getDefaultToolkit().getImage method
  • Use an ImageObserver to monitor the loading of the image. When the image is fully loaded the user will be notified
  • Create a buffered image from the source image with a format closer to the custom display environment using GraphicsEnvironmentGraphicsDevice and GraphicsConfiguration to perform several image configurations
  • Use graphics.drawImage(sourceImage, 0, 0, null) to draw the source image into the buffer and create the BuffferedImage
  • And simply paint the buffered image in a new Frame

Let us take a look at the code snippet that follows. Note that the imageURL object will need to be replaced with an appropriate URL from your filesystem.

ImageToBufferedImage.java

package com.javacodegeeks.snippets.desktop;

import java.awt.Component;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;

public class ImageToBufferedImage {

    static BufferedImage image;
    static boolean imageLoaded = false;
    public static void main(String[] args) {
// The ImageObserver implementation to observe loading of the image
        ImageObserver myImageObserver = new ImageObserver() {
            public boolean imageUpdate(Image image, int flags, int x, int y, int width, int height) {
                if ((flags & ALLBITS) != 0) {
                    imageLoaded = true;
                    System.out.println("Image loading finished!");
                    return false;
                }
                return true;
            }
        };

// The image URL - change to where your image file is located!
        String imageURL = "pic.jpg";
/**
 * This call returns immediately and pixels are loaded in the background
 * We use an ImageObserver to be notified when the loading of the image
 * is complete

 */
        Image sourceImage = Toolkit.getDefaultToolkit().getImage(imageURL);
        sourceImage.getWidth(myImageObserver);
// We wait until the image is fully loaded
        while (!imageLoaded) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                System.out.println("Exception: "+e.getStackTrace());
            }

        }
// Create a buffered image from the source image with a format that's compatible with the screen
        GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice graphicsDevice = graphicsEnvironment.getDefaultScreenDevice();
        GraphicsConfiguration graphicsConfiguration = graphicsDevice.getDefaultConfiguration();
// If the source image has no alpha info use Transparency.OPAQUE instead
        image = graphicsConfiguration.createCompatibleImage(sourceImage.getWidth(null), sourceImage.getHeight(null), Transparency.BITMASK);
// Copy image to buffered image
        Graphics graphics = image.createGraphics();
// Paint the image onto the buffered image
        graphics.drawImage(sourceImage, 0, 0, null);
        graphics.dispose();
// Create frame with specific title
        Frame frame = new Frame("Example Frame");
// Add a component with a custom paint method
        frame.add(new CustomPaintComponent());
// Display the frame
        int frameWidth = 300;
        int frameHeight = 300;
        frame.setSize(frameWidth, frameHeight);
        frame.setVisible(true);
    }

    /**
     * To draw on the screen, it is first necessary to subclass a Component and
     * override its paint() method. The paint() method is automatically called
     * by the windowing system whenever component's area needs to be repainted.
     */
    static class CustomPaintComponent extends Component {
        public void paint(Graphics g) {
            // Retrieve the graphics context; this object is used to paint
            // shapes
            Graphics2D g2d = (Graphics2D) g;
            /**
             * Draw an Image object The coordinate system of a graphics context
             * is such that the origin is at the northwest corner and x-axis
             * increases toward the right while the y-axis increases toward the
             * bottom.
             */
            int x = 0;
            int y = 0;
            g2d.drawImage(image, x, y, this);
        }
    }
}

3. Methods used in BufferedImage

In this section, we will review some methods of the BufferedImage class used in the above example, as well as the upcoming example.

  • public Graphics2D createGraphics(): This method creates and returns a Graphics2D object, which is then used to draw the image on a Frame
  • public BufferedImage getSubimage(int x,int y, int w, int h): This method is used to return a part of the image starting from the coordinates x and y, and extending to a width and height specified by w and h, respectively. The returned object is of type BufferedImage.

4. BufferedImageExample2

In this section, we will see another example for creating a BufferedImage from Image. Here, we will use the ImageIO.read(File file) method to read and load the image file from a specified URL. Also, we will use the getSubImage() method explained above, to get a part of the image, and draw that onto the Frame. Again, the value of imageURL will need to be replaced appropriately.

BufferedImageExample2.java

package com.javacodegeeks.snippets.desktop;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;

public class BufferedImageExample2 {
    public static String imageURL = "img1.jpg";
    public static boolean imageLoaded = false;
    public static BufferedImage bufferedImage = null;
    public static BufferedImage subImage = null;

    public static void main(String[] args) {
        try {
            Image sourceImage = ImageIO.read(new File(imageURL));

            ImageObserver myImageObserver = new ImageObserver() {
                public boolean imageUpdate(Image image, int flags, int x, int y, int width, int height) {
                    if ((flags & ALLBITS) != 0) {
                        imageLoaded = true;
                        System.out.println("Image loading finished!");
                        return false;
                    }
                    return true;
                }
            };
            bufferedImage = new BufferedImage(sourceImage.getWidth(null), sourceImage.getHeight(null), BufferedImage.TYPE_INT_ARGB);
            Graphics graphics = bufferedImage.createGraphics();
// Paint the image onto the buffered image
            graphics.drawImage(sourceImage, 0, 0, null);
            graphics.dispose();
            subImage = bufferedImage.getSubimage(230,0,100,bufferedImage.getHeight());
// Create frame with specific title
            Frame frame = new Frame("Example Frame");
// Add a component with a custom paint method
            frame.add(new SubImagePaintComponent());
// Display the frame
            int frameWidth = 300;
            int frameHeight = 300;
            frame.setSize(frameWidth, frameHeight);
            frame.setVisible(true);

        } catch (IOException ioe) {
            System.out.println("IOException in BufferedImageExample2 : " + ioe.getStackTrace());
        }
    }
        /**
         * To draw on the screen, it is first necessary to subclass a Component and
         * override its paint() method. The paint() method is automatically called
         * by the windowing system whenever component's area needs to be repainted.
         */
        static class SubImagePaintComponent extends Component {
            public void paint(Graphics g) {
                // Retrieve the graphics context; this object is used to paint
                // shapes
                Graphics2D g2d = (Graphics2D) g;
                /**
                 * Draw an Image object The coordinate system of a graphics context
                 * is such that the origin is at the northwest corner and x-axis
                 * increases toward the right while the y-axis increases toward the
                 * bottom.
                 */
                int x = 0;
                int y = 0;
                g2d.drawImage(subImage, x, y, this);
            }
        }
}

5. Summary

In this article, we reviewed specific details on how to create a BufferedImage Java object from an Image object. We also saw 2 Java examples to review the different methods used within the BufferedImage class.

6. Download the Source Code

This was an example of how to create a BufferedImage in Java from an Image.

Download
You can download the full source code of this example here: Create Java BufferedImage from an Image

Last updated on Jun. 22nd, 2020

Sowmya Shankar

Sowmya works as a Senior Web Applications Programmer in the higher educational sector, where she leads projects based on Java. She graduated from Anna University's Computer Sciences department, followed by a Masters degree in Computer and Information Sciences from the University of Delaware. Her project portfolio features diverse web applications using frameworks such as Struts2, Spring, Spring Boot, as well as her recent experiments in the world of Microservices and the React JS framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button