java图像_Java调整大小图像

2020-08-13 00:00:00 java 图像

java图像

Today we will look into java resize image program. Recently I had to upload a lot of images to an FTP server but the images size were huge. Since I was going to use them only on web pages, it was wise to resize them to a smaller size and then upload it.

今天,我们将研究java调整大小图像程序。 最近,我不得不将很多图像上传到FTP服务器,但是图像尺寸很大。 由于我只打算在网页上使用它们,因此明智的做法是将它们调整为较小的大小然后上传。

A few days back I provided a list of online tools to reduce image size. But when you have hundreds of images, it’s better to invest some time and write a program that does this work for you. So let’s see how we can resize an image in java.

几天前,我提供了一些在线工具以减小图像大小 。 但是,当您拥有数百张图像时,最好花一些时间并编写一个可以为您工作的程序。 因此,让我们看看如何在Java中调整图像大小。

Java调整大小图像 (Java Resize Image)

We can use java.awt.Graphics2D class to resize image in java.

我们可以使用java.awt.Graphics2D类来调整Java中图像的大小。

Below is the program that searches all the files in a directory and resizes them to the given size and saves it to a different directory.

以下是搜索目录中所有文件并将其大小调整为给定大小并将其保存到其他目录的程序。

The sample program here saves images in both PNG and JPG format but you can easily change it to serve your specific requirement.

这里的示例程序将图像保存为PNG和JPG格式,但是您可以轻松地对其进行更改以满足您的特定要求。

Java图像调整程序 (Java Image Resize Program)

package com.journaldev.util;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
/**
 * This class will resize all the images in a given folder
 * @author pankaj
 *
 */
public class JavaImageResizer {

	public static void main(String[] args) throws IOException {

		File folder = new File("/Users/pankaj/Desktop/images");
	    File[] listOfFiles = folder.listFiles();
		System.out.println("Total No of Files:"+listOfFiles.length);
		Image img = null;
		BufferedImage tempPNG = null;
		BufferedImage tempJPG = null;
		File newFilePNG = null;
		File newFileJPG = null;
		for (int i = 0; i < listOfFiles.length; i++) {
		      if (listOfFiles[i].isFile()) {
		        System.out.println("File " + listOfFiles[i].getName());
		        img = ImageIO.read(new File("/Users/pankaj/Desktop/images/"+listOfFiles[i].getName()));
		        tempPNG = resizeImage(img, 100, 100);
		        tempJPG = resizeImage(img, 100, 100);
		        newFilePNG = new File("/Users/pankaj/Desktop/images/resize/"+listOfFiles[i].getName()+"_New.png");
		        newFileJPG = new File("/Users/pankaj/Desktop/images/resize/"+listOfFiles[i].getName()+"_New.jpg");
		        ImageIO.write(tempPNG, "png", newFilePNG);
		        ImageIO.write(tempJPG, "jpg", newFileJPG);
		      }
		}
		System.out.println("DONE");
	}

	/**
	 * This function resize the image file and returns the BufferedImage object that can be saved to file system.
	 */
	public static BufferedImage resizeImage(final Image image, int width, int height) {
        final BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        final Graphics2D graphics2D = bufferedImage.createGraphics();
        graphics2D.setComposite(AlphaComposite.Src);
        //below three lines are for RenderingHints for better image quality at cost of higher processing time
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
        graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        graphics2D.drawImage(image, 0, 0, width, height, null);
        graphics2D.dispose();
        return bufferedImage;
    }
}
  • First few lines uses Java IO to retrieve the list of files from the directory and then in the for loop, each file is processed.

    前几行使用Java IO从目录中检索文件列表,然后在for循环中处理每个文件。

  • resizeImage is the method where Graphics2D is used to resize image and return it as BufferedImage object.

    resizeImage是使用Graphics2D调整图像大小并将其作为BufferedImage对象返回的方法。

  • Again we use ImageIO to write it into the file system in both PNG and JPG format.

    同样,我们使用ImageIO将其以PNG和JPG格式写入文件系统。

Java调整图像大小要点 (Java Resize Image Important Points)

  1. You can use RenderingHints to get high quality image at the cost of processing time. If you are not reducing images to a very small size, you might want to avoid them for faster processing. It depends on your situation that you need fast processing or better quality.

    您可以使用RenderingHints来获得高质量的图像,但要花费处理时间。 如果您没有将图像缩小到非常小的尺寸,则可能要避免使用它们以加快处理速度。 根据您的情况,您需要快速处理还是需要更好的质量。

  2. The method doesn’t throw any Exception even if there are any files that are not image file like text, doc or pdf files. In that case, it will resize it and you will get a black colored image. You can easily extend the code to skip these files by filtering through their name.

    即使存在不是图像文件的任何文件(例如文本,doc或pdf文件),该方法也不会引发任何异常 。 在这种情况下,它将调整其大小,您将获得黑色图像。 您可以通过过滤名称来轻松地扩展代码以跳过这些文件。

  3. PNG image size is more than JPG image size for same resolution and it’s significant. So if you want to resize the image for web pages, you might want to use JPG format to save page loading time.

    对于相同的分辨率,PNG图像尺寸大于JPG图像尺寸,并且意义重大。 因此,如果要调整网页图像的大小,则可能要使用JPG格式来节省页面加载时间。

Java Image Resizer程序结果 (Java Image Resizer Program Results)

I placed one PNG and one PDF file in the image directory and executed the program.

我在图像目录中放置了一个PNG和一个PDF文件,并执行了该程序。

Input image is Eclipse Juno image of size 168KB:

输入图像是大小为168KB的Eclipse Juno图像:

Here are the output images with size:

这是带有大小的输出图像:

《java图像_Java调整大小图像》

PNG image without Hints 23KB

没有提示的PNG图片23KB

《java图像_Java调整大小图像》

JPG image without Hints 4KB

不含提示的JPG图片4KB

《java图像_Java调整大小图像》

PNG image with Hints 24KB

带有提示的PNG图片24KB

《java图像_Java调整大小图像》

JPG image with Hints 4KB

带有提示的JPG图像4KB

《java图像_Java调整大小图像》

Non image file output in PNG and JPG

非图像文件以PNG和JPG输出

 

I hope the given program help you in resizing images quickly.

我希望给定的程序可以帮助您快速调整图像大小。

Java用宽高比调整图像大小 (Java Resize Image with Aspect Ratio)

In a normal scenario, you want to keep the image aspect ratio else it will look stretched from one side. Here is the code snippet that will help you in maintaining the aspect ratio.

在正常情况下,您要保持图像的宽高比,否则它将从一侧延伸。 这是可帮助您保持宽高比的代码段。

double aspectRatio = (double) img.getWidth(null)/(double) img.getHeight(null);
tempPNG = resizeImage(img, 100, (int) (100/aspectRatio));

Note that in this case, you would have to make sure that there are only images in the directory else it will throw exception.

请注意,在这种情况下,您必须确保目录中只有图像,否则它将抛出exception 。

Further Reading: Here is another program to upload files on server using Apache Commons Net FTP API.

进一步阅读:这是另一个使用Apache Commons Net FTP API在服务器上上传文件的程序。

Reference: Graphics2D API Doc

参考: Graphics2D API文档

翻译自: https://www.journaldev.com/615/java-resize-image

java图像

    原文作者:cunchi4221
    原文地址: https://blog.csdn.net/cunchi4221/article/details/107470878
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章