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;
        }
        
      }


  • 相关阅读:
    iOS 10 的杂碎资料
    MAC SVN Merge 操作
    iOS中AFNetworking2.0和AFNetworking3.0 的HTTPS的配置
    从字符串中获取指定字符内的内容
    判断是否是是全汉字、全字母、全数字、数字和字母等
    解析URL 获取某一个参数值
    长按TextField或TextView显示中文的粘贴复制
    TextField和TextView的限制输入长度
    抢购、距活动结束,剩余时间倒计时。
    Cell右滑 多个编辑选项栏
  • 原文地址:https://www.cnblogs.com/riskyer/p/3423984.html
Copyright © 2011-2022 走看看