Java как изменить размер изображения

В этом руководстве показаны методы изменения размера изображения в Java.
  1. Изменение размера и отображение изображения в Java с помощью BufferedImage.getScaledInstance()
  2. Измените размер изображения и сохраните его в локальном каталоге в Java с помощью Graphics2D и ImageIO

Изменить размер изображения в Java

Java может выполнять несколько операций разных типов, таких как чтение, запись или удаление файла. В следующих примерах мы продемонстрируем, как изменить размер изображения в Java, используя три метода.

Изменение размера и отображение изображения в Java с помощью BufferedImage.getScaledInstance()

В первом примере мы изменяем размер изображения и показываем его внутри кадра, никуда не сохраняя. Здесь мы создаем объект bufferedImage класса BufferedImage. Класс BufferedImage расширяет класс Image, представляющий графические изображения в виде массива прямоугольных пикселей. Для чтения изображения воспользуемся функцией ImageIO.read(). Здесь ImageIO — это класс, который содержит статические методы, такие как read и write, для выполнения операций ввода и вывода.

Мы получаем наше изображение с помощью метода new File(), который вызывает конструктор класса File и передает в него местоположение изображения в качестве аргумента. Получив объект bufferedImage, мы используем его для вызова метода getScaledInstance(), который создает масштабированную версию изображения.

Функция getScaledInstance принимает три аргумента: первые два — это ширина и высота в пикселях, которые мы хотим передать изображению, а последний аргумент — это алгоритм, используемый для масштабирования. Здесь мы используем функцию Image.SCALE_DEFAULT, которая сообщает классу использовать алгоритм выборки по умолчанию.

Как только это будет сделано, мы создадим окно для показа изображения с помощью объекта JFrame. Мы устанавливаем макет объекта рамка как FlowLayout, который выстраивает компоненты в линию. Затем мы устанавливаем размер окна; обратите внимание, что этот размер должен быть больше, чем высота и ширина изображения, чтобы изображение отображалось полностью.

Наконец, чтобы показать изображение, мы создаем объект JLabel и вызываем класс section, который устанавливает изображение как значок. Наконец, мы добавляем объект jLabel к объекту frame и устанавливаем видимость true.

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 ResizeImageExample {
    public static void main(String[] args) throws IOException {

        new ResizeImageExample();
    }

    public ResizeImageExample() throws IOException {
        BufferedImage bufferedImage = ImageIO.read(new File("C:\Users\User1\Pictures\java.png"));
        Image image = bufferedImage.getScaledInstance(600, 400, Image.SCALE_DEFAULT);

        ImageIcon icon = new ImageIcon(image);
        JFrame frame = new JFrame();
        frame.setLayout(new FlowLayout());
        frame.setSize(800, 600);

        JLabel jLabel = new JLabel();
        jLabel.setIcon(icon);
        frame.add(jLabel);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Выход:

java изменить размер изображения 1

Измените размер изображения и сохраните его в локальном каталоге в Java с помощью Graphics2D и ImageIO

Во втором методе мы используем класс Graphics2D для создания графики. Первый шаг — получить файл изображения с помощью метода ImageIo.read(), который принимает объект File в качестве аргумента, который содержит путь к изображению. ImageIo.read() возвращает объект BufferedImage, bufferedImageInput. Мы создаем еще один объект BufferedImage, который будет использоваться при написании изображения. Он принимает три аргумента: высоту, ширину и тип изображения.

Теперь мы вызываем метод createGraphics(), используя объект bufferdImageOutput, который возвращает объект Graphics2D, g2d. Затем мы создаем изображение с помощью метода drawImage(), который принимает шесть аргументов. Первый — это объект BufferedImage, второй и третий — координаты x и y, которые увеличиваются в соответствии с размером, если оба значения равны нулю. Четвертый и пятый аргументы представляют новую высоту и ширину, которые мы хотим дать изображению, а последний аргумент — это ImageObserver, который в нашем случае имеет значение null.

Прежде чем продолжить, мы избавляемся от всего контекста и ресурсов, используемых g2d, с помощью функции g2d.dispose(). Чтобы сохранить изображение с измененным размером в локальном каталоге, мы используем функцию ImageIo.write(), которая принимает объект bufferedImageOutput, имя, которое будет присвоено новому файлу изображения, и конструктор File с путем к файлу.

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

public class ResizeImageExample {
    public static void main(String[] args) throws IOException {
        resizeFile("C:\Users\Rupam Saini\Pictures\java.png",
                "C:\Users\Rupam Saini\Pictures\java-resized.png",
                500, 500);

    }

    public static void resizeFile(String imagePathToRead,
                              String imagePathToWrite, int resizeWidth, int resizeHeight)
            throws IOException {

        File fileToRead = new File(imagePathToRead);
        BufferedImage bufferedImageInput = ImageIO.read(fileToRead);

        BufferedImage bufferedImageOutput = new BufferedImage(resizeWidth,
                resizeHeight, bufferedImageInput.getType());

        Graphics2D g2d = bufferedImageOutput.createGraphics();
        g2d.drawImage(bufferedImageInput, 0, 0, resizeWidth, resizeHeight, null);
        g2d.dispose();

        String formatName = imagePathToWrite.substring(imagePathToWrite
                .lastIndexOf(".") + 1);

        ImageIO.write(bufferedImageOutput, formatName, new File(imagePathToWrite));
    }
}

Изображение до изменения размера:

Java изменить размер изображения 2

Изображение после изменения размера:

Java изменить размер изображения 3

There are a couple of ways to resize & crop images in Java. This article will briefly compare different methods of resizing images in Java, along with pros and cons.

More importantly, after you finish reading, you will learn a novel approach to resizing images in Java applications, which doesn’t require writing any image resizing code or maintaining servers to handle a large volume of image manipulation requests.

There are broadly four ways to resize images in Java:-

  • Native Java It does not require any third-party libraries.
  • Open-source image manipulation libraries — For example, ImageMagick.
  • Open source imaging service like Thumbor.
  • Free and paid Image CDN e.g. ImageKit.io.
Method Pros Cons
Native Java functions — No third party library is required. You will have to deal with a lot of low-level image processing and file operation.
Open source image processing libraries — High image quality.
— More control over resizing and cropping options.
— Advance features e.g. watermarking and text overlay.
You will have to install third-party libraries and find relevant options to get the desired results.
Open source thumbnail general service — Expressive API to resize & crop images for web pages.
— High image quality.
— More control over resizing and cropping options.
You will have to install a third-party service and maintain the infrastructure.
Free or paid image CDN — No third party image processing library required.
— Since you are not running the service, you don’t have to maintain the infrastructure.
— Get started within a few minutes.
— Expressive API to resize & crop images for web pages.
— Advance features such as smart cropping and face detection.
— More control over resizing and cropping options.
— High image quality.
An overkill if you want to resize a handful of images. If you are serving images on the web, then you should be using an image CDN.

In this post, we will deep dive into different methods of resizing and cropping using ImageKit.io URL-parameters.

Image resizing in Java using ImageKit.io

We will learn the following image manipulation in Java using ImageKit.io. It doesn’t require you to install any third-party image processing library. You can scale from zero to millions of image requests per minute without having to worry about scaling or maintaining infrastructure.

  • Basic image resizing, height and width manipulation
  • Cropping & preserving aspect ratio while resizing images
  • Add watermark in images
  • Adding text over images
  • Generating encrypted secured image URLs
  • Converting image format

You can manipulate the height and width of an image using simple URL parameters. Your backend can generate these URLs in Java or in the frontend itself.

For example, the original image is 1280x853px.

https://ik.imagekit.io/ikmedia/woman.jpg

Original 1280×853 image

To get a 200px wide image, use `tr=w-200` query parameter

https://ik.imagekit.io/ikmedia/woman.jpg?tr=w-200

200px wide image

To resize image to 400 width and 200 height, you can use tr=w-400,h-200

https://ik.imagekit.io/ikmedia/woman.jpg?tr=w-400,h-200

400×200 image

Using ImageKit.io Java SDK, you can quickly generate image URLs like this:

List<Map<String, String>> transformation = new ArrayList<Map<String, String>>();
Map<String, String> scale = new HashMap<>();
scale.put("height","200");
scale.put("width","400");
transformation.add(scale);
   
Map<String, Object> options = new HashMap();
options.put("urlEndpoint","https://ik.imagekit.io/ikmedia/");
options.put("path","/woman.jpg");
options.put("transformation", transformation);

String url = ImageKit.getInstance().getUrl(options);
// https://ik.imagekit.io/ikmedia/tr:w-400,h-200/woman.jpg?ik-sdk-version=java-VERSION

Cropping & preserving aspect ratio while resizing images in Java

If only one of the height(h) or width(w) is specified, then ImageKit.io adjusts the other dimension accordingly to preserve the aspect ratio, and no cropping occurs.

But when you specify both height(h) and width(w) dimension and want to preserve the aspect ratio — you have the following three options:

  • Crop some part of the image. You can choose which area to crop, where to focus etc.
  • Add padding around the image. You can control the background color of the padding to match the layout.
  • Let ImageKit change either height or width so that the whole image is visible. In this case, only one of the height or width matches the request dimension.

Let’s understand different cropping options with examples.

No cropping, force-fit image in requested dimensions

If you need an image in exact dimension as requested even if the aspect ratio is not preserved, use forced crop strategy.

https://ik.imagekit.io/ikmedia/woman.jpg?tr=w-200,h-200,c-force

Force fit

Default center cropping

If you don’t choose any cropping strategy, ImageKit.io will crop the edges by default and show the center of the image.

https://ik.imagekit.io/ikmedia/woman.jpg?tr=w-200,h-200

Default center crop

Fit inside the container (no cropping)

If you want the image to fit inside the container as per request height and width, use c-at_max. The full image content is preserved (no cropping), the aspect ratio is maintained, but the resulting height & width might differ from what is requested.

The output image is less than or equal to the dimensions specified in the URL, i.e., at least one dimension will exactly match the output dimension requested, and the other dimension will be equal to or smaller than the corresponding output dimension requested.

It is equivalent to object-fit:contain or background-size:contain CSS properties.

https://ik.imagekit.io/ikmedia/woman.jpg?tr=w-400,h-200,c-at_max

300×200 image fits inside 400×200 container

Fill container (no cropping)

If you want the image to cover the whole container as per the requested height and width, use c-at_least. The entire image content is preserved i.e. no cropping, the aspect ratio is maintained, but the resulting height & width might be different from what is requested.

One of the dimensions will be the same as what is requested, while the other dimension will be equal to or larger than what is asked for.

It is roughly equivalent to object-fit:cover or background-size:cover CSS properties.

https://ik.imagekit.io/ikmedia/woman.jpg?tr=w-400,h-200,c-at_least

400×267 image covers 400×200 container

No cropping, add padding around the image

If you don’t want the image to be cropped while maintaining the aspect ratio, you can add padding around the edges to get the desired dimension. You can also control the background color of this padding.

https://ik.imagekit.io/ikmedia/woman.jpg?tr=w-200,h-100,cm-pad_resize,bg-DDDDDD

200×100 image with padding

Smart cropping

ImageKit.io can intelligently crop image such that the object of interest remains in the center using smart cropping. In the thumbnail generated below, the woman is kept in the center.

https://ik.imagekit.io/ikmedia/woman.jpg?tr=w-200,h-200,fo-auto

Smart crop

Face cropping

You can crop and focus around the human face using fo-face parameter.

Face crop

Add watermark in images in Java

You can protect your images by adding your logo over them. If you try to achieve this in Java or using open-source image processing libraries, you will have to deal with low-level file operations and library-specific technicalities.

With ImageKit, it is straightforward to add a watermark in images in Java. Let’s say we want to put our logo on an image.

Logo can be accessed at —

https://ik.imagekit.io/ikmedia/logo/light-icon_GTyhLlWNX-.svg

The image we want to watermark —

https://ik.imagekit.io/ikmedia/woman.jpg?tr=w-600

Using the overlay image (oi) transformation, we can generate a watermarked image.

https://ik.imagekit.io/ikmedia/woman.jpg?tr=oi-logo@@light-icon_GTyhLlWNX-.svg

Watermarked image

You can also control the position, size, and other manipulation options of the overlay image. Learn more about image overlay from the docs.

Adding text over images in Java

You can add text over images in Java using ImageKit.io text overlay. You can create engaging visuals in Java using URL-based parameters to add watermark and text on images dynamically.

For example — We have added ot-Sky is the limit in the URL to add a string “Sky is the limit” over the image.

https://ik.imagekit.io/ikmedia/backlit.jpg?tr=ot-Sky is the limit,otbg-FFFFFF90,otp-20,ots-70,otc-00000,ox-N0,oy-30

Text overlay

You can generate photo collage in Java using the same methods. Learn more about how to create a photo collage using ImageKit.

You can use Java SDK to simplify URL generation in your backend application.

List<Map<String, String>> transformation = new ArrayList<Map<String, String>>();
Map<String, String> overlay = new HashMap<>();
overlay.put("overlay_text","Sky is the limit");
overlay.put("otbg","FFFFFF90");
overlay.put("otp","20");
overlay.put("overlay_text_font_size","70");
overlay.put("overlay_text_color","00000");
overlay.put("overlay_x","N0");
overlay.put("overlay_y","30");
transformation.add(overlay);
    
Map<String, Object> options = new HashMap();
options.put("urlEndpoint","https://ik.imagekit.io/ikmedia/");
options.put("path","/backlit.jpg");
options.put("transformation", transformation);

String url = ImageKit.getInstance().getUrl(options);
// https://ik.imagekit.io/ikmedia/tr:ot-Sky is the limit,otbg-FFFFFF90,otp-20,ots-70,otc-00000,ox-N0,oy-30/woman.jpg?ik-sdk-version=java-VERSION

Generating encrypted secured image URLs in Java

At times, you might want to secure access to your media assets to limit misuse. Or you might want to set a time-based expiry on the image URLs to make it hard for web scarpers to use your image URLs.

To solve this, you can create signed image URLs in your backend application written in Java. A signed URL is a secure URL that can be generated only by you using your account’s private key.

For example, let’s create a signed URL that expires in 300 seconds with the default URL endpoint and other query parameters:

List<Map<String, String>> transformation=new ArrayList<Map<String, String>>();
Map<String, String> scale=new HashMap<>();
scale.put("height","600");
scale.put("width","400");

transformation.add(format);

Map<String, Object> options=new HashMap();
options.put("path","/default-image.jpg");
options.put("signed",true);
options.put("expireSeconds",300);
String url = ImageKit.getInstance().getUrl(options);
// https://ik.imagekit.io/your_imagekit_id/tr:h-600,w-400/default-image.jpg?ik-t=1567358667&ik-s=f2c7cdacbe7707b71a83d49cf1c6110e3d701054&ik-sdk-version=java-VERSION

If someone tries to modify the image transformation or use it beyond its intended expiry time of 300 seconds, a 401 Unauthorised response is returned instead of the image.

Converting image format in Java

In Java, you can convert image format using write() function provided by the class ImageIO under javax.imageio package. The supported output formats are JPG, JPEG, PNG, BMP, WBMP, and GIF.

However, you will have to deal with low-level file operations and image buffer. There is a different and easy way to convert image format in Java. Using an image CDN like ImageKit, you can easily convert image format using URL based transformation.

For example — The actual format of the following image is JPG.

https://ik.imagekit.io/ikmedia/woman.jpg

You can convert it to PNG using tr=f-png transformation.

https://ik.imagekit.io/ikmedia/woman.jpg?tr=f-png

You can covert it to WebP using tr=f-webp

https://ik.imagekit.io/ikmedia/woman.jpg?tr=f-webp

ImageKit also offers features such as automatic best format selection, quality optimization, and metadata manipulation out of the box. This reduces the final size of the output image and improves your website’s images load time while maintaining visual quality.

Summary

Here is what you need to know:

  • If you only have a handful of images, use Java’s native image manipulation using the native Java ImageIO class.
  • If you need easy to use image resizing capabilities, go for a free image CDN like ImageKit.io. With a forever free plan, you get 20GB of viewing bandwidth every month. It is sufficient for small scale businesses.

How Do You Resize Images in Java?

Java is a popular object-oriented programming language originally designed and used for distributed enterprise applications. Today it is widely used for mobile development, as the programming language for Android smartphone applications, and is commonly used for edge devices and internet of things (IoT) development.

Resizing an image means removing pixels and reducing its physical size, or “blowing up” the image by adding pixels, which will reduce image quality. If a resize operation changes the aspect ratio of an image, it will result in “squeezing” the image out of its current proportions.

Java provides several techniques for programmatic bulk image resize, including the getScaledInstance() method and the Graphics2D class. We’ll also show how to use Cloudinary to resize images in Java while automatically adjusting the image to focus on objects of interest.

In this article, we cover the following techniques to resize images in Java:

  1. Resizing an Image Using BufferedImage.getScaledInstance()
  2. Resizing an Image Using Graphics2D
  3. Automatically Resize and Crop Images in Java with Cloudinary

Techniques to Resize Images in Java

Resizing an Image Using BufferedImage.getScaledInstance()

You can resize an image in Java using the getScaledInstance() function, available in the Java Image class. We’ll use the BufferedImage class that extends the basic Image class. It stores images as an array of pixels.

First, we import the necessary Java libraries:

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

Now, we create an object from the BufferedImage class, and use the ImageIO.read() function to read an image from the file system. The File() method calls the File class constructor, taking the path of the image as an argument.

BufferedImage bufferedImage = ImageIO.read(new File("C:\example.png"));

We now have a new object containing the image, which provides the getScaledInstance() method, which we can use to get a resized version of the image. The method takes the following arguments:

  • Target width in pixels after resizing
  • Target height in pixels after resizing
  • Image scaling algorithm (if you don’t have a special preference, you can use Image.SCALE_DEFAULT which uses the default sampling algorithm)

Here is how to scale the source image to 800 x 500 pixels:

Image image = bufferedImage.getScaledInstance(800, 500, Image.SCALE_DEFAULT);

Note that this operation scales the bufferedImage object in memory, but does not save the resized image to the file system, and also does not display the image.

Let’s arrange the resized image using a JFrame. We’ll set the layout to FlowLayout, which specifies that components in the JFrame should be displayed from left to right, and set the size of the JFrame to a larger size than the image, ensuring it will be shown in its entirety.

ImageIcon icon = new ImageIcon(image);
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
frame.setSize(1200, 800);

The last step is to display the image to the user. We’ll do this using a JLabel object, adding the JLabel to the frame and setting visibility to true.

JLabel jLabel = new JLabel();
jLabel.setIcon(icon);
frame.add(jLabel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Resizing an Image Using Graphics2D

Another option for resizing an image in Java is the Graphics2D class. This class extends the Graphics class to provide fine-grained control over geometry, coordinate transformations, and color management of 2-dimensional shapes and images.

Here are the required imports:

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

Like in the previous example, we use ImageIo.read() and the File() method to read the image from the file system and store it as a BufferedImage object:

BufferedImage bufferedImage = ImageIO.read(new File("C:\example.png"));

We create another object that will store the resize operation result:

BufferedImage bufferedImageResult = new BufferedImage(
        resizeWidth,
        resizeHeight,
        bufferedImage.getType()
);

Now it’s time to use the g2d class. We’ll call the createGraphics() method, passing the bufferedImageResult object. This returns a g2d (Graphics2D) object.

Graphics2D g2d = bufferedImageResult.createGraphics();

We can now use the drawImage() function on the g2d object, which takes the following arguments:

  • A BufferedImage object
  • X and Y coordinates. For a resize operation, these should be set to 0.
  • The new height and width after resizing.
  • ImageObserver – handles notifications of image loading; not needed in this case and can be left as null.

The code looks like this:

g2d.drawImage(
        bufferedImage, 
        0, 
        0, 
        resizeWidth, 
        resizeHeight, 
        null
);

We use the following command to dispose of context and resources used by g2d, which are not necessary for the next steps:

g2d.dispose();

Finally, we save the resized image in the local directory using the ImageIo.write() function.

String formatName = imagePathToWrite.substring(
        imagePathToWrite.lastIndexOf(".") + 1
);
ImageIO.write(
        bufferedImageResult, 
        formatName, 
        new File(imagePathToWrite)
);

Automatically Resize and Crop Images in Java with Cloudinary

A cloud-based service for managing images and videos, Cloudinary offers a generous free-forever subscription plan. While on that platform, you can upload your images, and apply built-in effects, filters, and modifications. You can also resize images automatically, focusing on the most important elements with AI, or adapt them to your website design without having to manually crop or scale them.

You can set the target dimensions of your resized image by specifying width, height, and/or the target aspect ratio as qualifiers of your resize transformation.

You can change the dimensions of an uploaded image by setting the image’s height, width, and/or aspect ratio, and Cloudinary automatically resizes or crops the image to fit into the requested size.

For example, this original image is 1200 x 1200 pixels:

three ways to resize

Resizing the image to 200 x 200 pixels, using crop, scale, fill and pad results in the following images:

3 ways to resize 200px

Get started with automated resize and cropping today!

  1. Get a free Cloudinary account
  2. Install the Java SDK
  3. Deliver the crop transformations shown above as follows:

    # focus on the model in portrait crop
    cloudinary.url().transformation(new Transformation().height(200).width(200).crop("crop")).imageTag("https://res.cloudinary.com/demo/image/upload/docs/model.jpg");
    # detect the face for thumbnail crop
    cloudinary.url().transformation(new Transformation().height(200).width(200).crop("crop")).imageTag("https://res.cloudinary.com/demo/image/upload/docs/model.jpg");
    # crop to a banner automatically focusing on region of interest
    cloudinary.url().transformation(new Transformation().aspectRatio("2.5").width(450).crop("crop")).imageTag("https://res.cloudinary.com/demo/image/upload/docs/model.jpg");
    
Details
Written by  
Last Updated on 14 August 2019   |   Print  Email

In Java, to resize (or scale) an image read from an image file and save the scaled image into another image file, we can follow these steps:

    •           Create a BufferedImage object for the input image by calling the method read(File) of the ImageIO class.
    •           Create a BufferedImage object for the output image with a desired width and height.
    •           Obtain a Graphics2D object from the output image’s BufferedImage object.
    •           Draw the input image’s BufferedImageobject onto the output image’s Graphics2D object.
    •            Save the output image to a file on disk using the method write(File) of the ImageIO class.

Here is a utility class which implements two methods for resizing an image and saves the result to another image file. 

package net.codejava.graphic;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * This program demonstrates how to resize an image.
 *
 * @author www.codejava.net
 *
 */
public class ImageResizer {

	/**
	 * Resizes an image to a absolute width and height (the image may not be
	 * proportional)
	 * @param inputImagePath Path of the original image
	 * @param outputImagePath Path to save the resized image
	 * @param scaledWidth absolute width in pixels
	 * @param scaledHeight absolute height in pixels
	 * @throws IOException
	 */
	public static void resize(String inputImagePath,
			String outputImagePath, int scaledWidth, int scaledHeight)
			throws IOException {
		// reads input image
		File inputFile = new File(inputImagePath);
		BufferedImage inputImage = ImageIO.read(inputFile);

		// creates output image
		BufferedImage outputImage = new BufferedImage(scaledWidth,
				scaledHeight, inputImage.getType());

		// scales the input image to the output image
		Graphics2D g2d = outputImage.createGraphics();
		g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
		g2d.dispose();

		// extracts extension of output file
		String formatName = outputImagePath.substring(outputImagePath
				.lastIndexOf(".") + 1);

		// writes to output file
		ImageIO.write(outputImage, formatName, new File(outputImagePath));
	}

	/**
	 * Resizes an image by a percentage of original size (proportional).
	 * @param inputImagePath Path of the original image
	 * @param outputImagePath Path to save the resized image
	 * @param percent a double number specifies percentage of the output image
	 * over the input image.
	 * @throws IOException
	 */
	public static void resize(String inputImagePath,
			String outputImagePath, double percent) throws IOException {
		File inputFile = new File(inputImagePath);
		BufferedImage inputImage = ImageIO.read(inputFile);
		int scaledWidth = (int) (inputImage.getWidth() * percent);
		int scaledHeight = (int) (inputImage.getHeight() * percent);
		resize(inputImagePath, outputImagePath, scaledWidth, scaledHeight);
	}

	/**
	 * Test resizing images
	 */
	public static void main(String[] args) {
		String inputImagePath = "D:/Photo/Puppy.jpg";
		String outputImagePath1 = "D:/Photo/Puppy_Fixed.jpg";
		String outputImagePath2 = "D:/Photo/Puppy_Smaller.jpg";
		String outputImagePath3 = "D:/Photo/Puppy_Bigger.jpg";

		try {
			// resize to a fixed width (not proportional)
			int scaledWidth = 1024;
			int scaledHeight = 768;
			ImageResizer.resize(inputImagePath, outputImagePath1, scaledWidth, scaledHeight);

			// resize smaller by 50%
			double percent = 0.5;
			ImageResizer.resize(inputImagePath, outputImagePath2, percent);

			// resize bigger by 50%
			percent = 1.5;
			ImageResizer.resize(inputImagePath, outputImagePath3, percent);

		} catch (IOException ex) {
			System.out.println("Error resizing the image.");
			ex.printStackTrace();
		}
	}

}

Note:the resized images may not have same quality as the original ones.

Other Java Graphics Tutorials:

  • How to add watermark for images using Java
  • How to draw image with automatic scaling in Java
  • How to convert image format using Java
  • How to capture screenshot programmatically in Java
  • How to draw text vertically with Java Graphics2D
  • How to Create Zoomable User Interface Java Programs with Piccolo2D Framework
  • Drawing lines examples with Java Graphics2D
  • Drawing Rectangles Examples with Java Graphics2D
  • Using JFreechart to draw line chart with CategoryDataset
  • Using JFreechart to draw XY line chart with XYDataset

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Add comment

Понравилась статья? Поделить с друзьями:
  • Java wrapper error
  • Java virtual machine launcher ошибка как исправить на windows 10 тлаунчер
  • Java virtual machine launcher ошибка как исправить на windows 10 unable to access jarfile
  • Java virtual machine launcher ошибка как исправить на windows 10 minecraft
  • Java virtual machine launcher ошибка как исправить майнкрафт