要使用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
變量設置為你的輸入和輸出圖像文件的路徑。