zoukankan      html  css  js  c++  java
  • java 图片压缩 缩放

    废话不多说,直接上代码,静态方法可直接调用,中间用流来处理的


     /**
       * 图片缩放(未考虑多种图片格式和等比例缩放)
       * @param filePath 图片路径
       * @param height 高度
       * @param width 宽度
       * @param picType 图片格式
       * @param bb 比例不对时是否需要补白
      */
      @Deprecated
      public static byte[] resize(byte[] imageBuffer, int height, int width, String picType, boolean bb) {
        byte[] targetBuffer = null;
        try {
          BufferedImage fromImage = ImageIO.read(new ByteArrayInputStream(imageBuffer));
          BufferedImage scaleImage = zoomImage(fromImage, width, height);
          targetBuffer = writeHighQuality(scaleImage);
        } catch (IOException e) {
          logger.error("ImageUtils Resize Exception." , e);
        }
        return targetBuffer;
      }
    
    
    /**
       * @param im
       *            原始图像
       * @param resizeTimes
       *            倍数,比如0.5就是缩小一半,0.98等等double类型
       * @return 返回处理后的图像
       */
      public static BufferedImage zoomImage(BufferedImage im, int toWidth, int toHeight) {
        /* 原始图像的宽度和高度 */
        int width = im.getWidth();
        int height = im.getHeight();
    
        /* 调整后的图片的宽度和高度 */
        //    int toWidth = (int) (Float.parseFloat(String.valueOf(width)) * resizeTimes);
        //    int toHeight = (int) (Float.parseFloat(String.valueOf(height)) * resizeTimes);
    
        /* 新生成结果图片 */
        BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB);
    
        result.getGraphics().drawImage(im.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
        return result;
      }
      
      
      
      public static byte[] writeHighQuality(BufferedImage im) {
        try {
          ByteArrayOutputStream imageStream = new ByteArrayOutputStream();
          JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(imageStream);
          JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(im);
          /* 压缩质量 */
          jep.setQuality(1f, true);
          encoder.encode(im, jep);
          /* 近JPEG编码 */
          imageStream.close();
          return imageStream.toByteArray();
        } catch (Exception e) {
          e.printStackTrace();
          return null;
        }
        
      }


  • 相关阅读:
    【NLP CS224N笔记】汇总
    【NLP CS224N笔记】Lecture 2
    论文摘记 2017.5
    FAST UA API
    FAST Hello World
    NetMagic Simple Overview
    论文摘记 2017.4.25-4.30
    LLDP协议、STP协议 笔记
    FAST:通过Floodlight控制器下发流表
    FAST:NetMagic交换机 与 Floodlight控制器 连接实战
  • 原文地址:https://www.cnblogs.com/riskyer/p/3423984.html
Copyright © 2011-2022 走看看