import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import javax.imageio.ImageIO;
public class ImageChange {
public static void main(String[] args) throws IOException {
// 缩小图片,输出base64字符串
String imgPath = "/Users/pic/003.png";
ImageChange.scaleImageAndEncodeToBase64(imgPath);
// 缩小图片,导出新图
String imagePath = "/Users/pic/002.png";
String newImagePath = "/Users/pic/002-cp.png";
ImageChange.FileSmall(imagePath, newImagePath);
}
public static String scaleImageAndEncodeToBase64(String imagePath) throws IOException {
File imageFile = new File(imagePath);
BufferedImage originalImage = ImageIO.read(imageFile);
// 计算缩放比例
int width = originalImage.getWidth();
int height = originalImage.getHeight();
int targetWidth = width/3; // 设置新的宽度
int targetHeight = (targetWidth * height) / width; // 计算新的高度
// 创建新的图像
BufferedImage scaledImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
// 将BufferedImage转换为Base64
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(scaledImage, "png", outputStream); // 假设目标格式为jpg
byte[] imageBytes = outputStream.toByteArray();
String base64String = Base64.getEncoder().encodeToString(imageBytes);
System.out.println("Successfully!");
return base64String;
}
public static void FileSmall(String imgPath, String newImagePath){
try {
File file = new File(imgPath);
BufferedImage image = ImageIO.read(file);
// 计算缩放比例
int width = image.getWidth();
int height = image.getHeight();
int newWidth = width/3; // 设置新的宽度
int newHeight = (newWidth * height) / width; // 计算新的高度
// 创建新的图像
BufferedImage scaledImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
// 获取 Graphics 对象以进行绘制
Graphics g = scaledImage.createGraphics();
g.drawImage(image, 0, 0, newWidth, newHeight, null);
g.dispose();
ImageIO.write(scaledImage, "png", new File(newImagePath));
System.out.println("Successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
java-图片修改尺寸(缩小)
最新推荐文章于 2024-05-18 16:42:38 发布