Java 图片切割

来源:互联网 发布:淘宝店分销怎么做 编辑:程序博客网 时间:2024/04/28 18:04

将图片横切或者竖切为两张

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();}}


原创粉丝点击