Class ImageUtil

java.lang.Object
com.sure.tool.image.ImageUtil

public class ImageUtil extends Object
图像工具类:基于 JDK ImageIO 的读写、缩放、裁剪、灰度、旋转、格式转换,零依赖。
Since:
0.2.0
Author:
suretool
  • Method Details

    • read

      public static BufferedImage read(Path path) throws IOException
      读取图像文件。
      Parameters:
      path - 图像文件路径
      Returns:
      图像;文件不是有效图像返回 null
      Throws:
      IOException - IO 异常
    • write

      public static void write(BufferedImage image, Path path, String format) throws IOException
      写入图像到文件(按扩展名推断格式,如 png/jpg)。
      Parameters:
      image - 图像
      path - 目标路径
      format - 格式(png/jpg/bmp/gif)
      Throws:
      IOException - IO 异常
    • scale

      public static BufferedImage scale(BufferedImage source, int width, int height)
      缩放图像(保持宽高比,按目标宽度计算高度;quality 高质量插值)。
      Parameters:
      source - 源图像
      width - 目标宽度
      height - 目标高度
      Returns:
      缩放后图像
    • crop

      public static BufferedImage crop(BufferedImage source, int x, int y, int width, int height)
      裁剪图像。
      Parameters:
      source - 源图像
      x - 起始 X
      y - 起始 Y
      width - 宽度
      height - 高度
      Returns:
      裁剪后图像
    • gray

      public static BufferedImage gray(BufferedImage source)
      转为灰度图。
      Parameters:
      source - 源图像
      Returns:
      灰度图
    • rotate

      public static BufferedImage rotate(BufferedImage source, int degrees)
      旋转图像(90 度整数倍)。
      Parameters:
      source - 源图像
      degrees - 旋转角度(90 的倍数)
      Returns:
      旋转后图像
    • size

      public static String size(BufferedImage image)
      图像尺寸信息(宽 x 高)。
      Parameters:
      image - 图像
      Returns:
      如 1920x1080
    • toBase64

      public static String toBase64(BufferedImage image, String format) throws IOException
      将图片编码为 Base64 字符串。
      Parameters:
      image - 图片
      format - 格式(png/jpg 等)
      Returns:
      Base64 字符串
      Throws:
      IOException - IO 异常
    • toDataUri

      public static String toDataUri(BufferedImage image, String format) throws IOException
      将图片编码为 Data URI(可直接用于 <img src>)。
      Parameters:
      image - 图片
      format - 格式(png/jpg 等)
      Returns:
      data:image/png;base64,...
      Throws:
      IOException - IO 异常