使用ImageIO压缩图片

<span style="font-size:18px;">   最近项目中有个需求,需要批量对图片服务器上的图片进行压缩,并将压缩后的文件上传到图片服务器上,对图片的压缩处理方面决定采用ImageIO来进行。</span>

  javax.imageio.ImageIO,提供了常用的图片I/O操作,包括图片的读取,图片的解析,图片的绘制等,更多详细功能可阅读其源码,参考代码如下:

    ByteArrayOutputStream bs = null;<span style="font-family: Arial, Helvetica, sans-serif;">//加载图片</span>
    ImageOutputStream imOut = null;
    InputStream inputStream = null;
    try {
      URL url = new URL(imgUrl);
      BufferedImage bufferedImage = null;
      try {
        bufferedImage = ImageIO.read(url);//此处使用URL来获取图片服务器上的图片信息
      } catch (Exception e1) {
        //在获取图片的时候有小部分图片出现<span style="font-family: FangSong_GB2312;">Unsupported Image Type异常,暂时没做处理</span>
        //解决Unsupported Image Type的异常
        if (e1.getMessage().contains("Unsupported Image Type")) {
          //todo 图片的格式异常,需要做下处理
          throw e1;
        } else {
          throw e1;
        }
      }
      int picWidth = bufferedImage.getWidth();   //得到图片的宽度
      int picHeight = bufferedImage.getHeight();  //得到图片的高度
      //2、设置缩放后的宽和高(如果宽高都小于等于800像素则不进行操作)
      if (picWidth <= maxSize && picHeight <= maxSize) {
        //如果都小于800则不需要切图
        //不需要操作
      }
      //分两种情况,宽大于高||宽小于高
      double scale = 0D;//设定压缩比例
      if (picWidth >= picHeight) { //1、宽>=高
        scale = picWidth / maxSize;
      }
      if (picWidth < picHeight) { //2、宽<高
        scale = picHeight / maxSize;
      }
      int newPicWidth = 0;//新图片的宽
      newPicWidth = new Double(picWidth / scale).intValue();
      int newPicHeight = 0;//新图片的高
      newPicHeight = new Double(picHeight / scale).intValue();
      //3、重新绘制压缩图
      Image image = bufferedImage.getScaledInstance(newPicWidth, newPicHeight, Image.SCALE_SMOOTH);
      BufferedImage outputImage =
          new BufferedImage(newPicWidth, newPicHeight, BufferedImage.TYPE_INT_RGB);
      Graphics graphics = outputImage.getGraphics();
      graphics.drawImage(image, 0, 0, null);
      graphics.dispose();
      //4、从重新绘制的图片中获取inputstream,并上传到fastDFS服务器上
      String filePrefix = imgUrl.substring(imgUrl.lastIndexOf(".") + 1);
      bs = new ByteArrayOutputStream();
      imOut = ImageIO.createImageOutputStream(bs);
      ImageIO.write(outputImage, filePrefix, imOut);
      inputStream = new ByteArrayInputStream(bs.toByteArray());
      //对压缩后的图片上传fastDFS服务器(此处可自行进行操作)
      fdfsClientFactory.getFastdfsClient()
          .upload("", inputStream, imOut.length(), filePrefix, null);
    } catch (Exception e1) {
      logger.error("压缩图片出现问题,压缩的图片为{}",imgUrl);
      logger.error("",e1);
    } finally {
      try {
        if (bs != null) {
          bs.close();
        }
        if (imOut != null) {
          imOut.close();
        }
        if (inputStream != null) {
          inputStream.close();
        }
      } catch (Exception e2) {
        logger.error("关闭stream流失败",e2);
      }
    }

 

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java ImageIO提供了压缩图片的功能,可以将高分辨率的图片压缩成低分辨率的图片以减少图片的大小。以下是一个示例代码,演示如何使用ImageIO压缩图片: ```java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class ImageCompressor { public static void main(String[] args) throws IOException { File inputFile = new File("input.jpg"); File outputFile = new File("output.jpg"); BufferedImage inputImage = ImageIO.read(inputFile); // 压缩比例 float compressionRatio = 0.5f; // 计算压缩后的尺寸 int newWidth = (int) (inputImage.getWidth() * compressionRatio); int newHeight = (int) (inputImage.getHeight() * compressionRatio); // 创建压缩后的图片 BufferedImage outputImage = new BufferedImage(newWidth, newHeight, inputImage.getType()); // 绘制压缩后的图片 outputImage.createGraphics().drawImage( inputImage.getScaledInstance(newWidth, newHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null ); // 写入文件 ImageIO.write(outputImage, "jpg", outputFile); } } ``` 在上面的代码中,我们首先读取一个输入图片文件,并指定一个输出图片文件。然后我们计算压缩比例,根据压缩比例计算出新的图片尺寸。接着我们创建一个新的BufferedImage对象,指定新的尺寸和图片类型。最后我们使用`createGraphics()`方法获取到一个Graphics2D对象,并使用`drawImage()`方法将原始图片缩放到新的尺寸上,并绘制到新的BufferedImage对象上。最后我们使用`ImageIO.write()`方法将新的BufferedImage对象写入到输出文件中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值