Java 图片切割

 public void carveImage(String dir, File file, String orient, int width, int height) {  
        ImageFilter cropFilter;  
        Image img;  
        try {  
            // 读取源图像  
            BufferedImage bi = ImageIO.read(file);  
            int srcWidth = bi.getWidth(); // 源图宽度  
            int srcHeight = bi.getHeight(); // 源图高度  
  
            int destWidth, destHeight;  
            int j = 1, k = 1;  
            // 判断  
            if ("2".equals(orient)) {// 竖切  
                destWidth = srcWidth / 2;  
                destHeight = srcHeight;  
                k = 0;  
            } else if ("1".equals(orient)) {// 横切  
                destWidth = srcWidth;  
                destHeight = srcHeight / 2;  
                j = 0;  
            } else {  
                return;  
            }  
            String fileName;  
            String filePath;  
            if (srcWidth >= destWidth && srcHeight >= destHeight) {  
                Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);  
                for (int i = 0; i < 2; i++) {  
                    fileName = System.currentTimeMillis() + ".jpg";  
                    filePath = dir + "/" + fileName;  
                    cropFilter = new CropImageFilter(i * destWidth * j, i * destHeight * k, destWidth, destHeight);  
                    img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));  
                    BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);  
                    Graphics g = tag.getGraphics();  
                    new CropThread(g, img).start();  
                    ImageIO.write(tag, "JPEG", new File(filePath));  
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
            throw new RuntimeException(e);  
        }  
    }  
class CropThread extends Thread {  
    Graphics g = null;  
    Image img = null;  
  
    public CropThread(Graphics g, Image img) {  
        this.g = g;  
        this.img = img;  
    }  
  
    public void run() {  
        g.drawImage(img, 0, 0, null); // 绘制缩小后的图  
        g.dispose();  
    }  
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值