java 截取图片的中央部分

  import  java.awt.Graphics;   
  • import java.awt.image.BufferedImage;   
  • import java.io.File;   
  • import java.io.FileInputStream;   
  • import java.io.IOException;   
  • import java.io.InputStream;   
  • import javax.imageio.ImageIO;   
  • /**  
  •  * 截取一个图片的中央  
  •  * @author pengchengji  
  •  */  
  • public class ImageUtil {   
  •     /**  
  •      * 截取一个图像的中央区域  
  •      * @param image 图像File  
  •      * @param w 需要截图的宽度  
  •      * @param h 需要截图的高度  
  •      * @return 返回一个  
  •      * @throws IOException  
  •      */  
  •     public static void cutImage(File image, int w, int h) throws IOException {   
  •            
  •         // 判断参数是否合法   
  •         if (null == image || 0 == w || 0 == h) {   
  •             new Exception ("哎呀,截图出错!!!");   
  •         }   
  •         InputStream inputStream = new FileInputStream(image);   
  •         // 用ImageIO读取字节流   
  •         BufferedImage bufferedImage = ImageIO.read(inputStream);   
  •         BufferedImage distin = null;   
  •         // 返回源图片的宽度。   
  •         int srcW = bufferedImage.getWidth();   
  •         // 返回源图片的高度。   
  •         int srcH = bufferedImage.getHeight();   
  •         int x = 0, y = 0;   
  •         // 使截图区域居中   
  •         x = srcW / 2 - w / 2;   
  •         y = srcH / 2 - h / 2;   
  •         srcW = srcW / 2 + w / 2;   
  •         srcH = srcH / 2 + h / 2;   
  •         // 生成图片   
  •         distin = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);   
  •         Graphics g = distin.getGraphics();   
  •         g.drawImage(bufferedImage, 00, w, h, x, y, srcW, srcH, null);   
  •         ImageIO.write(distin, "jpg"new File("D:\\pic\\33.jpg"));   
  •     }   
  •   
  •     public static void main(String[] args) throws Exception {   
  •         File file = new File("D:\\pic\\22.jpg");   
  •         cutImage(file, 200200);   
  •     }   
  • }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值