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

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

猜你喜欢

转载自xieyan30.iteye.com/blog/1701607