论坛首页 Java企业应用论坛

改变图像的宽和高,但不改变长宽比

浏览 2977 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-10-19  

 /**
  * change image's width and height
  *
  * @param origin
  *            source image's path
  * @param dest
  *            target image's path
  * @param width
  *            expected width
  * @param height
  *            expected height
  * @return true:success || false:failed
  */
 public static boolean resizeImg(String origin, String dest, int width, int height) {
  try {
   BufferedImage img = ImageIO.read(new File(origin));

   // origin width and height
   int imgWidth = img.getWidth();
   int imgHeight = img.getHeight();

   // check width and height
   if (imgWidth > width || imgHeight > height) {
    float widthRate = (float)imgWidth / (float)width;
    float heightRate = (float)imgHeight / (float)height;
    float rate = widthRate > heightRate ? widthRate : heightRate;
    rewriteImg(origin, dest, 0, 0, (int)(imgWidth / rate), (int)(imgHeight / rate), BufferedImage.TYPE_INT_RGB);
   }

   return true;
  } catch (Exception e) {
   return false;
  }
 }

 

 public static boolean rewriteImg(String origin, String dest, int x, int y,
   int width, int height, Integer scaleType) {
  try {
   // img's suffix
   String suffix = origin.substring(origin.lastIndexOf(".") + 1);

   // source image
   Image image = ImageIO.read(new File(origin));
   
   // get target
   BufferedImage tag = new BufferedImage(width, height, scaleType);
   Graphics g = tag.getGraphics();
   g.drawImage(image, x, y, width, height, null);
   g.dispose();
   
   // Graphics to ByteArrayOutputStream
   ByteArrayOutputStream bos = new ByteArrayOutputStream();
   ImageIO.write(tag, suffix, bos);
   
   // write file
   FileOutputStream fos = new FileOutputStream(dest);
   fos.write(bos.toByteArray());
   fos.flush();
   fos.close();
   
   return true;
  } catch (Exception e) {
   return false;
  }
 }

   发表时间:2012-10-20  
rewriteImg这个方法没有加注释哟。
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics