java 图片 切割_Java 图片切割

最近做一个猜图小游戏,需要将一张大图动态切割成小图块,写个博客记录一下。

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

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值