Table of Contents
In this post, we will see how to convert BufferImage to Image in java.
Convert BufferedImage to Image in Java
BufferedImage is an Image, so you don’t need to do any conversion.
You can just assign it as below:
1 2 3 4 |
BufferedImage bufferedImage = ImageIO.read(file); Image img = bufferedImage; |
Convert java.awt.image.BufferedImage to javafx.scene.image.Image in java
You can use SwingFXUtils.toFXImage()
to convert image from java.awt.image.BufferedImage
to javafx.scene.image.Image
in java.
1 2 3 4 |
BufferedImage bufferedImage = ImageIO.read(file); Image img = SwingFXUtils.toFXImage(bufferedImage, null); |
Convert Image to BufferedImage in Java
Since BufferedImage is an Image, you can do explicit casting to assign image to BufferedImage.
1 2 3 4 |
Image img = ImageIO.read(file); BufferedImage bufferedImage = (BufferedImage) img; |
how To Scale BufferedImage in Java
There are multiple ways to scale BufferedImage in java.
Using BufferImage’s getScaledInstance()
You can use BufferImage's getScaledInstance()
to scale BufferedImage in java.
Here is sample code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package org.arpit.java2blog; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import javax.imageio.ImageIO; import javax.swing.ImageIcon; public class ScaledBufferedImage { public static void main(String[] args) throws IOException { final int SCALE = 2; Image img = new ImageIcon("MyFile.png").getImage(); BufferedImage bi = new BufferedImage(SCALE * img.getWidth(null), SCALE * img.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D graph2D = (Graphics2D) bi.getGraphics(); graph2D.scale(SCALE, SCALE); // everything drawn with graph from now on will get scaled. graph2D.drawImage(img, 0, 0, null); graph2D.dispose(); ImageIO.write(bi, "png", new File("MyFile1.png")); } } |
Using imgscalr library
imgscalr provides resize()
method to resize BufferedImage in java.
Add following dependency to pom.xml.
1 2 3 4 5 6 7 8 |
<!-- https://mvnrepository.com/artifact/org.imgscalr/imgscalr-lib --> <dependency> <groupId>org.imgscalr</groupId> <artifactId>imgscalr-lib</artifactId> <version>4.2</version> </dependency> |
Here is sample code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package org.arpit.java2blog; import org.imgscalr.Scalr; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class ScaleBufferedImage { public static void main(String[] args) throws IOException { int newWidth=400; int newHeight=400; File file=new File("MyFile.png"); BufferedImage bufferedImage = ImageIO.read(file); BufferedImage bufferedImageScaled = Scalr.resize(bufferedImage, Scalr.Method.BALANCED, newWidth, newHeight); ImageIO.write(bufferedImageScaled, "png", new File("MyFile_scaled.png")); } } |
That’s all about Convert BufferedImage to Image in Java.