Java Converting Image to Bufferedimage

Java converting Image to BufferedImage

From a Java Game Engine:

/**
* Converts a given Image into a BufferedImage
*
* @param img The Image to be converted
* @return The converted BufferedImage
*/
public static BufferedImage toBufferedImage(Image img)
{
if (img instanceof BufferedImage)
{
return (BufferedImage) img;
}

// Create a buffered image with transparency
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);

// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();

// Return the buffered image
return bimage;
}

How to convert Image to BufferedImage in Java?

If it's important to you, you can use a MediaTracker to "wait" for the image to be loaded, then you don't need to care about supplying a ImageObserver

try {
MediaTracker mt = new MediaTracker(new JPanel());
Image image = Toolkit.getDefaultToolkit().createImage("...");
mt.addImage(image, 0);
System.out.println("Wait for...");
mt.waitForAll();
System.out.println("I be loaded");

BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bi.createGraphics();
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
} catch (InterruptedException ex) {
ex.printStackTrace();
}

Have a look at MediaTracker JavaDocs for more details

I don't wish to add any GUI, I just need to download image or fail

Okay, if you "need to download" the image, then you can just use ImageIO.read(URL), have a look at Reading/Loading an Image for more details ... then you won't need to care about Image or MediaTracker, as ImageIO returns a BufferedImage

Converting Image to BufferedImage

use ImageIO.read(File) . It returns BufferedImage :

BufferedImage image = ImageIO.read(new File(filename));

How to convert buffered image to image and vice-versa?

BufferedImage is a(n) Image, so the implicit cast that you're doing in the second line is able to be compiled directly. If you knew an Image was really a BufferedImage, you would have to cast it explicitly like so:

Image image = ImageIO.read(new File(file));
BufferedImage buffered = (BufferedImage) image;

Because BufferedImage extends Image, it can fit in an Image container. However, any Image can fit there, including ones that are not a BufferedImage, and as such you may get a ClassCastException at runtime if the type does not match, because a BufferedImage cannot hold any other type unless it extends BufferedImage.

Converting ImageIcon to BufferedImage (how to set image type)

If you don't need transparency, you can use BufferedImage.TYPE_INT_RGB that will solve your problem.

If you wish to have tranparency, then you need to set the way you wish to draw a copy of your image into destination by:

 Graphics2D bgr = bimage.createGraphics();
bgr.setComposite(AlphaComposite.SRC); // read the doc of this

the problem you have is probably because when you create a new BufferedImage of type TYPE_INT_ARGB all pixels in that image are transparent, so when yoou draw your src image to it it will mix with these tranparent pixels and all image will be transparent. The resolution is to use other mode of merging src and dst images by setting the apropriate AplhaComposite.

Convert JavaFX image To BufferedImage

Try your luck with SwingFXUtils.
There is a method for that purpose:

BufferedImage fromFXImage(Image img, BufferedImage bimg)

You can call it with second parameter null, as it is optional (exists for memory reuse reason):

BufferedImage image = SwingFXUtils.fromFXImage(fxImage, null);

How to change the image type of a BufferedImage which is loaded from file?

Create a new Buffered image with the type you want

BufferedImage in = ImageIO.read(img);
BufferedImage newImage = new BufferedImage(in.getWidth(), in.getHeight(), BufferedImage.TYPE_INT_ARGB);

Graphics2D g = newImage.createGraphics();
g.drawImage(in, 0, 0, in.getWidth(), in.getHeight(), null);
g.dispose();

BufferedImage/Image Conversion

A BufferedImage is an Image, in other words it extends from the Image abstract class. You don't need to convert anything.

Please check out the BufferedImage API for the details.


Edit
You state in comment:

When I run this code, I get spammed with errors in my console. Why would it do this? When the java file is converted into a class it has no errors found.

Then you'll want to post any error/exception messages that you receive, and also indicate for us which line(s) throw them.

Also as an aside, you will never want to read in an image from within a paintComponent method. This method should be lean, mean, and fast as hell, and it should concern itself with painting and painting only. Why read in the image multiple times when you only need to read it into a variable once say in the constructor?


Edit 2
Your error is a NullPointerException that occurs on engine.java:51, on line 51 of your engine.java class. Note that this has nothing to do with use of BufferedImage vs. Image, and everything to do with trying to use a null reference variable. As I suspected, the key to the problem is in the exception message. In your future questions, you will want to post any and all exception messages and indicate which line throws them.


Edit 3
NEVER do this:

try{
image = ImageIO.read(new File("spells.png"));
} catch(IOException e) {

}

never leave your catch block blank. At least print the stack trace. Otherwise you will have no clue if something wrong occurs.


Edit 4
You state in comment:

Note on your edit: when declarations of the spritesheet and the sprites are put outside the paintComponent method. 20 parts of the code have unnecessary errors at variables and sometimes curly brackets saying "engine.java:<line>: class, interface, or enum expected"

From your error, I'm guessing that you've got code that calls methods, sitting out naked in the class outside of any constructor or method, where it doesn't belong. I suggest that you declare your Image variable in the class, and initialize it in your constructor (which right now is empty).

And again, you need to indicate for us which line is throwing the exception.


Edit 5
You state in comment:

line 51 is spells[k][1] = image.getSubimage((34*2*k)-34*2,0,34,34);

And this is as I guessed in my last comment. This means that image is null, that your attempt to read it in is wrong. Often this is due to looking for the file in the wrong place, or if in a jar file, trying to use a file in the first place. You will want to consider getting the Image as a resource, not a file.

To debug this, try to simplify your program -- just create a very small program that reads in an Image, creates an ImageIcon from it, and displays the ImageIcon in a JOptionPane.showMessageDialog(null, yourIconHere).


Edit 6
For example, try testing your code with something like this:

import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;

public class SimpleTestImage {
public static void main(String[] args) {
String path = "spells.png";
InputStream inputStream = SimpleTestImage.class.getResourceAsStream(path);
try {
BufferedImage img = ImageIO.read(inputStream);
ImageIcon icon = new ImageIcon(img);
JOptionPane.showMessageDialog(null, icon);
} catch (IOException e) {
e.printStackTrace();
}
}
}

In this example, I don't use a File to get the Image but rather get an InputStream as a class resource. When doing this, Java will start looking for the image in the same location that you have your class files.

And again, read in the Image in your class's constructor.



Related Topics



Leave a reply



Submit