要使用Java ImageIO.read实现图像的缩放操作,你可以使用以下步骤:
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.ImageIO;
public static BufferedImage readImage(String imagePath) {
try {
return ImageIO.read(new File(imagePath));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static BufferedImage scaleImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
Image scaledImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = outputImage.createGraphics();
g2d.drawImage(scaledImage, 0, 0, null);
g2d.dispose();
return outputImage;
}
public static void saveScaledImage(BufferedImage scaledImage, String outputPath) {
try {
ImageIO.write(scaledImage, "jpg", new File(outputPath));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String inputImagePath = "path/to/your/input/image.jpg";
String outputImagePath = "path/to/your/output/image.jpg";
int targetWidth = 100;
int targetHeight = 100;
BufferedImage originalImage = readImage(inputImagePath);
BufferedImage scaledImage = scaleImage(originalImage, targetWidth, targetHeight);
saveScaledImage(scaledImage, outputImagePath);
}
这样,你就可以使用Java ImageIO.read实现图像的缩放操作了。请确保将inputImagePath
和outputImagePath
变量设置为你的输入和输出图像文件的路径。