最近做一个猜图小游戏,需要将一张大图动态切割成小图块,写个博客记录一下。
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageUtil {
/**
* @param filePath 源图片路径
* @param destDir 切割后的小图输出目录
* @param cols 列数
* @param rows 行数
* @throws IOException
*/
public static void cutImage(String filePath,String destDir,int cols,int rows) throws IOException{
File file = new File(filePath);
//读取图片
BufferedImage image= ImageIO.read(file);
//获取源图片的宽、高
int srcWidth = image.getWidth();
int srcHeight = image.getHeight();
//计算小图块的平均宽、高
int avgWidth = srcWidth / cols;
int avgHeight = srcHeight / rows;
int startHeight = 0;
for (int i = 0; i < rows; i++) {
int startWidth = 0;
for (int j = 0; j < cols; j++) {
//获取小图块数据
BufferedImage subImage = image.getSubimage(startWidth, startHeight, avgWidth, avgHeight);
//输出
ImageIO.write(subImage, "jpg", new File(destDir+"/abc"+i+"_"+j+".jpg"));
startWidth = startWidth + avgWidth;
}
startHeight = startHeight+avgHeight;
}
}
public static void main(String[] args) {
try {
cutImage("d://test.jpg", "d://images", 5, 5);
} catch (IOException e) {
e.printStackTrace();
}
}
}