切分和组合图片
切割图片
1. load 要切分的图片
2. 确定要切分成多少块
3. 计算小图片的高度和宽度
4. 切分图片
5. 保存图片
要切分图片:
File file = new File("btg.jpg"); // 项目目录下有名为btg.jpg的图片 FileInputStream fis = new FileInputStream(file); BufferedImage image = ImageIO.read(fis); //把文件读到图片缓冲流中 int rows = 4; //定义图片要切分成多少块 int cols = 4; int chunks = rows * cols; int chunkWidth = image.getWidth() / cols; // 计算每一块小图片的高度和宽度 int chunkHeight = image.getHeight() / rows; int count = 0; BufferedImage imgs[] = new BufferedImage[chunks]; for (int x = 0; x < rows; x++) { for (int y = 0; y < cols; y++) { //初始化BufferedImage imgs[count] = new BufferedImage(chunkWidth, chunkHeight, image.getType()); //画出每一小块图片 Graphics2D gr = imgs[count++].createGraphics(); gr.drawImage(image, 0, 0, chunkWidth, chunkHeight, chunkWidth * y, chunkHeight * x, chunkWidth * y + chunkWidth, chunkHeight * x + chunkHeight, null); gr.dispose(); } } System.out.println("切分完成"); //保存小图片到文件中 for (int i = 0; i < imgs.length; i++) { ImageIO.write(imgs[i], "jpg", new File("img" + i + ".jpg")); } System.out.println("小图片创建完成");
切分完成: