java 图片切分

 

 

import java.awt.Graphics2D;

 

import java.awt.image.BufferedImage;

 

import java.io.File;

 

import java.io.FileInputStream;

 

import java.io.IOException;

 

 

 

import javax.imageio.ImageIO;

 

 

 

public class Test {

 

 

 

public static void cutImg(String path,String sPath,String numStr) throws IOException{

 

 

 

    File file = new File(path); // 项目目录下有名为btg.jpg的图片 

 

    FileInputStream fis = new FileInputStream(file); 

 

    BufferedImage image = ImageIO.read(fis); //把文件读到图片缓冲流中

 

 

 

    int rows = 1; //定义图片要切分成多少块 

 

    int cols = 2; 

 

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

 

        } 

 

    } 

 

 

 

    //保存小图片到文件中

 

 

 

    for (int i = 0; i < imgs.length; i++) { 

 

    //保存名 img9-1-0

 

      String  fileName=numStr+"-"+i+".jpg";   

 

        ImageIO.write(imgs[i], "jpg", new File(sPath+fileName)); 

 

       

 

    } 

 

   

 

}

 

 

 

 

 

 

 

 

 

 

 

 

 

}

猜你喜欢

转载自1634801662.iteye.com/blog/2215124
今日推荐