To scale an image in Java using the BufferedImage
class, you can use the getScaledInstance()
method of the java.awt.Image
class. The getScaledInstance()
method returns a scaled version of the original BufferedImage
object.
Here is an example of how to scale an image in Java using the BufferedImage
class:
import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class ImageScalingExample { public static void main(String[] args) throws IOException { // read the original image BufferedImage originalImage = ImageIO.read(new File("original.jpg")); // scale the image int width = originalImage.getWidth() / 2; int height = originalImage.getHeight() / 2; Image scaledImage = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH); // create a new BufferedImage with the scaled image BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); resizedImage.getGraphics().drawImage(scaledImage, 0, 0, null); // write the resized image to a file ImageIO.write(resizedImage, "jpg", new File("scaled.jpg")); } }
In this example, the main()
method reads an image from a file using the ImageIO.read()
method, scales it using the getScaledInstance()
method, and creates a new BufferedImage
object with the scaled image. The scaled image is then written to a file using the ImageIO.write()
method.
To run the example, create a new Java class and copy the code into it. Replace "original.jpg" with the path to the original image file, and "scaled.jpg" with the path to the output file. Run the class using the java
command. The output file should contain the scaled version of the original image.
You can also use the java.awt.Graphics2D
class and the drawImage()
method to scale an image in Java. For example:
import java.awt.Graphics2D; import java.awt.image.BufferedImage; ... BufferedImage originalImage = ...; int width = originalImage.getWidth() / 2; int height = originalImage.getHeight() / 2; BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = resizedImage.createGraphics(); g2d.drawImage(originalImage, 0, 0, width, height, null); g2d.dispose();
This code creates a new BufferedImage
object with the specified width and height, and scales the original image using the drawImage()
method of the Graphics2D
class. The scaled image is then drawn onto the resizedImage
object.