java的一个图片处理小程序

java的一个图片处理小程序
package com.img;

import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;

import javax.imageio.ImageIO;

public class ABMImage {
      /**
       * 剪切图片
       * @param source 源图片
       * @param dest 目标图片
       * @param x 切点x
       * @param y 切点y
       * @param width 要切的宽度
       * @param height 要切的高度
       */
      public static void cutFile(File source, File dest,
              int x, int y, int width, int height) throws Exception{
          if (!dest.exists())
              dest.createNewFile();
          BufferedImage bis = ImageIO.read(source);
          int w = bis.getWidth();
          int h = bis.getHeight();
          if (w < width+x) {
              width = w - x;
          }
          if (h < height+y) {
              height = h - y;
          }
          BufferedImage bf = bis.getSubimage(x,y,width,height);
          ImageIO.write(bf, "jpeg" , dest);
      }
   
      /**
       * 缩放图片
       * @param source 源图片
       * @param dest 目标图片
       * @param width 缩放后的宽度
       * @param height 缩放后的高度
       */
      public static void reduceImage(File source, File dest, int width, int height)
          throws Exception{
          BufferedImage bis = ImageIO.read(source);
          int w = bis.getWidth();
          int h = bis.getHeight();
          double scale = (double)width/w;
          int disW = 0;
          int disH = 0;
          if ((double)height/h > scale) {
              scale = (double)height/h;
              disW = (int) ((w*scale - width)/2);
          } else {
              disH = (int) ((h*scale - height)/2);
          }
          AffineTransform transform = new AffineTransform();
          transform.setToScale(scale, scale);
          System.out.println(scale);
          AffineTransformOp ato = new AffineTransformOp(transform, null);
          BufferedImage bid = new BufferedImage(width+disW*2, height+disH*2, BufferedImage.TYPE_3BYTE_BGR);
          ato.filter(bis, bid);
          if (width+disW*2>bid.getWidth())
              width = bid.getWidth()-disW*2;
          if (height+disH*2>bid.getHeight())
              height = bid.getHeight()-disH*2;
          BufferedImage bf = bid.getSubimage(disW, disH, width, height);
          ImageIO.write(bf, "jpeg" , dest);
      }
   
      public static void main(String args[]) {
          File f = new File("c:/样品.jpg");
          File f2 = new File("c:/1234.jpg");
          try {
              ABMImage.reduceImage(f, f2, 250, 150);
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
}



</script>

你可能感兴趣的:(java的一个图片处理小程序)