Java 切割图片代码
(2012-09-04 10:39:48)
标签:
宽度
切割
源文件
工具类
java
package com.lyis.commons.util;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import com.lyis.commons.dto.ImageDto;
public class CutImage {
public ImageDto cut(File sourceFile, String targetDir, int width,
int height)
throws Exception {
List list = new
ArrayList();
BufferedImage source = ImageIO.read(sourceFile);
int sWidth = source.getWidth(); // 图片宽度
int sHeight = source.getHeight(); // 图片高度
if (sWidth > width
&& sHeight > height)
{
int cols = 0; // 横向切片总数
int rows = 0; // 纵向切片总数
int eWidth = 0; // 末端切片宽度
int eHeight = 0; // 末端切片高度
if (sWidth % width == 0) {
cols = sWidth / width;
} else {
eWidth = sWidth % width;
cols = sWidth / width + 1;
}
if (sHeight % height == 0) {
rows = sHeight / height;
} else {
eHeight = sHeight % height;
rows = sHeight / height + 1;
}
String fileName = null;
File file = new File(targetDir);
if (!file.exists()) { // 存储目录不存在,则创建目录
file.mkdirs();
}
BufferedImage image = null;
int cWidth = 0; // 当前切片宽度
int cHeight = 0; // 当前切片高度
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cWidth = getWidth(j, cols, eWidth, width);
cHeight = getHeight(i, rows, eHeight, height);
// x坐标,y坐标,宽度,高度
image = source.getSubimage(j * width, i * height, cWidth,
cHeight);
fileName = targetDir + "/map_" +
i + "_" + j +
".jpg";
file = new File(fileName);
ImageIO.write(image, "JPEG",
file);
list.add(file);
}
}
}
return new ImageDto(sWidth, sHeight, list);
}
public ImageDto cut(String source, String targetDir, int width, int
height)
throws Exception {
return cut(new File(source), targetDir, width, height);
}
private int getWidth(int index, int cols, int endWidth, int width)
{
if (index == cols - 1) {
if (endWidth != 0) {
return endWidth;
}
}
return width;
}
private int getHeight(int index, int rows, int endHeight, int
height) {
if (index == rows - 1) {
if (endHeight != 0) {
return endHeight;
}
}
return height;
}
}
分享:
喜欢
0
赠金笔
加载中,请稍候......
评论加载中,请稍候...
发评论
登录名: 密码: 找回密码 注册记住登录状态
昵 称:
评论并转载此博文
发评论
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。