Class ImageCompressor

java.lang.Object
com.sankcrm.erp.contract.jzq.infrastructure.ImageCompressor

public class ImageCompressor extends Object
Java 21图片压缩工具类 支持按尺寸缩放、按质量压缩、指定输出格式等功能
  • Constructor Details

    • ImageCompressor

      public ImageCompressor()
  • Method Details

    • compressImage

      public static void compressImage(InputStream inputStream, OutputStream outputStream, int targetWidth, int targetHeight, float quality, String format) throws IOException
      压缩图片(按质量和尺寸双重压缩)
      Parameters:
      inputStream - 原始图片输入流
      outputStream - 压缩后图片输出流
      targetWidth - 目标宽度(像素)
      targetHeight - 目标高度(像素)
      quality - 压缩质量(0.0-1.0,1.0为最高质量)
      format - 输出图片格式(如"jpeg"、"png")
      Throws:
      IOException - 处理过程中的IO异常
    • compressImage

      public static InputStream compressImage(File file, int targetWidth, int targetHeight) throws IOException
      压缩图片(按质量和尺寸双重压缩)
      Parameters:
      targetWidth - 目标宽度(像素)
      targetHeight - 目标高度(像素)
      Throws:
      IOException - 处理过程中的IO异常
    • compressImage

      public static InputStream compressImage(byte[] bytes, int targetWidth, int targetHeight, URI uri) throws IOException
      压缩图片(按质量和尺寸双重压缩)
      Parameters:
      targetWidth - 目标宽度(像素)
      targetHeight - 目标高度(像素)
      Throws:
      IOException - 处理过程中的IO异常
    • isLargerThan2MB

      public static boolean isLargerThan2MB(File file)
    • convertToInputStream

      public static InputStream convertToInputStream(BufferedImage image, String format) throws IOException
      将BufferedImage转换为InputStream
      Parameters:
      image - 待转换的图片对象(如scaledImage)
      format - 图片格式(如"jpeg"、"png"、"gif")
      Returns:
      转换后的InputStream
      Throws:
      IOException - 转换过程中发生IO异常
    • compressImageByQuality

      public static void compressImageByQuality(InputStream inputStream, OutputStream outputStream, float quality, String format) throws IOException
      仅按质量压缩图片(不改变尺寸)
      Throws:
      IOException
    • scaleImage

      public static void scaleImage(InputStream inputStream, OutputStream outputStream, int targetWidth, int targetHeight, String format) throws IOException
      仅按尺寸缩放图片(不改变质量)
      Throws:
      IOException
    • main

      public static void main(String[] args)
    • getFileExtension

      public static String getFileExtension(File file)
    • getFileName

      public static String getFileName(URI uri)
      从 URI 中提取文件名(含扩展名)
      Parameters:
      uri - 目标 URI
      Returns:
      文件名(如 "image.jpg");若无法提取则返回 null
    • getFileFormat

      public static String getFileFormat(URI uri)
      从 URI 中提取文件格式(扩展名,不含 ".")
      Parameters:
      uri - 目标 URI
      Returns:
      格式(如 "jpg");若无扩展名则返回 null