java中如何切割图片_Java 切割图片代码

本文提供了一个Java工具类CutImage,用于将图片按照指定的宽度和高度进行切割。该类包含两个cut方法,分别接受File对象和字符串路径作为源图片参数,切割后的图片保存在目标目录,并返回每个切片的尺寸和列表。
摘要由CSDN通过智能技术生成

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;

}

}

分享:

a4c26d1e5885305701be709a3d33442f.png喜欢

0

a4c26d1e5885305701be709a3d33442f.png赠金笔

加载中,请稍候......

评论加载中,请稍候...

发评论

登录名: 密码: 找回密码 注册记住登录状态

昵   称:

评论并转载此博文

a4c26d1e5885305701be709a3d33442f.png

发评论

以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值