| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
cnp5
9年前发布

java图片压缩

/**      * 改变图片的大小到宽为size,然后高随着宽等比例变化      * @param is 上传的图片的输入流      * @param os 改变了图片的大小后,把图片的流输出到目标OutputStream      * @param size 新图片的宽      * @param format 新图片的格式      * @throws IOException      */     public static void resizeImage1(InputStream is, OutputStream os, int size, String format) {          try {      BufferedImage prevImage = ImageIO.read(is);         double width = prevImage.getWidth();         double height = prevImage.getHeight();         double percent = size/width;         int newWidth = (int)(width * percent);         int newHeight = (int)(height * percent);         BufferedImage image = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_BGR);         //以下代码在压缩图片透明背景会变成变黑色      /* Graphics graphics = image.createGraphics();         graphics.drawImage(prevImage, 0, 0, newWidth, newHeight, null);         ImageIO.write(image, format, os);*/         /////////////////////////////////////////             //以下代码解决在压缩png格式的图片透明背景会变成变黑色的问题       Graphics2D g2d = image.createGraphics();        image = g2d.getDeviceConfiguration().createCompatibleImage(newWidth,newHeight,Transparency.TRANSLUCENT);           g2d.dispose();           g2d = image.createGraphics();           Image from = prevImage.getScaledInstance(newWidth, newHeight, prevImage.SCALE_AREA_AVERAGING);           g2d.drawImage(from, 0, 0, null);          g2d.dispose();           ImageIO.write(image, format,os);        os.flush();         is.close();         os.close();     } catch (Exception e) {      // TODO Auto-generated catch block      e.printStackTrace();     }      }