当前位置: 首页 > news >正文

【工具类】——图片缩放

在java中对于图片的处理一般都是使用Graphics2D类来实现。
Graphics2D 是 Java 2D API 的核心类,用于在 Java 平台上渲染二维形状、文本和图像。它是 Graphics 类的扩展,提供了更复杂的图形操作功能,包括几何变换、颜色管理、文本布局等。
用来实现图片的指定尺寸缩放
工具类代码
public class ImageResizer {

public static byte[] imageResizer(byte[] imageBytes, int width, int height) {try {ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);BufferedImage originalImage = ImageIO.read(bais);// 创建缩放后的图像BufferedImage resizedImage = new BufferedImage(width, height, originalImage.getType());Graphics2D graphics = resizedImage.createGraphics();// 改善图像质量graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);// 设置透明度,保持原始图像的透明度graphics.setComposite(AlphaComposite.Src);// 绘制图像graphics.drawImage(originalImage, 0, 0, width, height, null);graphics.dispose();ByteArrayOutputStream baos = new ByteArrayOutputStream();ImageIO.write(resizedImage, "png", baos);return baos.toByteArray();} catch (Exception e) {return null;}
}

}

测试类

public static void main(String[] args) {// 指定原始图像文件路径和目标尺寸String inputImagePath = "/Users/qweasdzxc/Downloads/test0.jpeg"; // 替换为实际路径int targetWidth = 100; // 目标宽度int targetHeight = 100; // 目标高度// 读取原始图像文件try {File inputFile = new File(inputImagePath);BufferedImage originalImage = ImageIO.read(inputFile);// 将原始图像转换为字节数组ByteArrayOutputStream baos = new ByteArrayOutputStream();ImageIO.write(originalImage, "png", baos);byte[] imageBytes = baos.toByteArray();// 调整图像大小byte[] resizedImageBytes = imageResizer(imageBytes, targetWidth, targetHeight);// 将调整大小后的图像保存到新文件if (resizedImageBytes != null) {ByteArrayInputStream bais = new ByteArrayInputStream(resizedImageBytes);BufferedImage resizedImage = ImageIO.read(bais);ImageIO.write(resizedImage, "png", new File("/Users/qweasdzxc/Downloads/test1.jpeg")); // 替换为实际路径System.out.println("Image resized successfully.");} else {System.out.println("Failed to resize image.");}} catch (IOException e) {e.printStackTrace();}
}

http://www.mrgr.cn/news/35250.html

相关文章:

  • 828华为云征文|Flexus云服务器X实例:在Docker环境下搭建java开发环境
  • 拦截器filter
  • 如何使用ssm实现基于VUE.js的在线教育系统+vue
  • for循环的应用
  • 0基础学前端 day2
  • git基础 -- 查找文件内容
  • MyBatis的一二级缓存
  • 云管理平台实践指南
  • ②大缓存ModbusRTU485数据集中采集器寄存器线圈重映射从站并发采集Modbus 串口RS485 转 RS485
  • 2024年蓝牙网关市场热门产品选购宝典
  • 洛谷P4551 最长异或路径(字典树,异或)
  • Node.JS有什么用?给谁用?怎么学?通俗易懂,超级详细!
  • vue脚手架Vue CLI 2.9.6创建工程,并引入elementUI的方法
  • C++STL--------string
  • Linux usb主机控制器HC阅读
  • scrapy spider框架download下来就可以用
  • DBeaver中如何导入excel中的大量数据
  • JS 特殊运算符有哪些?
  • 语言的变量交换
  • yolov10算法原理