本贴完善中。。。

图片分割

    /**
     * 切割图片
     *
     * @throws Exception
     * imagePath 图片路径
     * savePath 保存路径
     * header 保存文件名
     * rows 纵向拆分数
     * cols 横向拆分数
     */
    public static void splitImage(String imagepath , String savePath,String header, int rows, int cols) throws Exception {
        String originalImg = imagepath;
        File file = new File(originalImg);
        if(!file.exists()){
            System.out.println("file error");
            return;
        }
        FileInputStream fis = new FileInputStream(file);
        BufferedImage image = ImageIO.read(fis);

//        int rows = 6; //纵向拆分数
//        int cols = 1; //横向拆分数
        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++) {
                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();
            }
        }
        for (int i = 0; i < imgs.length; i++) {
            ImageIO.write(imgs[i], "jpg", new File(savePath+"/"+header+ "_00"+i + ".jpg"));
        }
    }

发表评论

邮箱地址不会被公开。 必填项已用*标注