java 批量修改图片大小
时间: 2023-12-13 13:33:43 浏览: 68
批量修改图片大小
以下是使用Java自带类进行批量修改图片大小的方法:
1. 使用ImageIO读取图片,获取图片的宽度和高度。
2. 创建一个BufferedImage对象,将原始图片绘制到该对象上。
3. 创建新的BufferedImage对象,设置新的宽度和高度。
4. 将原始图片绘制到新的BufferedImage对象上,并将其保存为新的图片文件。
```java
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageResizer {
public static void resize(String inputImagePath, String outputImagePath, int scaledWidth, int scaledHeight)
throws IOException {
// Read the source image
File inputFile = new File(inputImagePath);
BufferedImage inputImage = ImageIO.read(inputFile);
// Create the output image
BufferedImage outputImage = new BufferedImage(scaledWidth, scaledHeight, inputImage.getType());
// Scale the input image to the output image
Graphics2D g2d = outputImage.createGraphics();
g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
g2d.dispose();
// Save the scaled image as a JPEG
File outputFile = new File(outputImagePath);
ImageIO.write(outputImage, "jpg", outputFile);
}
}
```
调用上述方法,可以批量修改图片大小:
```java
public class BatchImageResizer {
public static void main(String[] args) {
String inputDir = "input";
String outputDir = "output";
int scaledWidth = 800;
int scaledHeight = 600;
File inputFolder = new File(inputDir);
File[] inputFiles = inputFolder.listFiles();
for (File inputFile : inputFiles) {
String inputFileName = inputFile.getName();
String outputFileName = inputFileName.substring(0, inputFileName.lastIndexOf(".")) + ".jpg";
String inputFilePath = inputDir + File.separator + inputFileName;
String outputFilePath = outputDir + File.separator + outputFileName;
try {
ImageResizer.resize(inputFilePath, outputFilePath, scaledWidth, scaledHeight);
} catch (IOException ex) {
System.out.println("Error resizing the image: " + inputFileName);
ex.printStackTrace();
}
}
}
}
```
阅读全文