Java 图片操作工具类
/**
* 按照指定宽高剪切图片
*
* @param fromFilePath 原始图片完整路径
* @param saveToFilePath 缩略图片保存路径
* @param width 剪切后图片的宽
* @param height 剪切后图片的高
* @throws Exception
*/
private static void cutImage1(String fromFilePath, String saveToFilePath, int width, int height) throws Exception {
// 校验原始图片
File file = new File(fromFilePath);
if (!file.isFile()) {
throw new Exception(file + " is not image file error in cutImage!");
}
BufferedImage buffer = ImageIO.read(file);
/*
* 核心算法,计算图片的压缩比
* w 和 h 为原始图片的宽和高
* width 和 height 为压缩/放大后图片的宽和高
*/
int w = buffer.getWidth();
int h = buffer.getHeight();
double ratiox = 1.0;
double ratioy = 1.0;
ratiox = w * ratiox / width;
ratioy = h * ratioy / height;
// 缩小图片
if (ratiox >= 1) {
if (ratioy < 1) {
ratiox = height * 1.0 / h;
} else {
if (ratiox > ratioy) {
ratiox = height * 1.0 / h;
} else {
ratiox = width * 1.0 / w;
}
}
} else {
// 放大图片
if (ratioy < 1) {
if (ratiox > ratioy) {
ratiox = height * 1.0 / h;
} else {
ratiox = width * 1.0 / w;
}
} else {
ratiox = width * 1.0 / w;
}
}
// 对于图片的放大或缩小倍数计算完成,ratiox大于1,则表示放大,否则表示缩小
AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratiox, ratiox), null);
buffer = op.filter(buffer, null);
// 从放大的图像中心截图
buffer = buffer.getSubimage((buffer.getWidth() - width) / 2, (buffer.getHeight() - height) / 2, width, height);
try {
ImageIO.write(buffer, "jpg", new File(saveToFilePath));
} catch (Exception ex) {
throw new Exception(" ImageIo.write error in CreatThum.: " + ex.getMessage());
}
}
/**
* 等比例放大/缩小图片
*
* @param fromFilePath 原始图片完整路径
* @param saveToFilePath 缩略图片保存路径
* @param scale 缩放比例
* @throws Exception
*/
private static void cutImage2(String fromFilePath, String saveToFilePath, double scale) throws Exception {
// 校验原始图片
File file = new File(fromFilePath);
if (!file.isFile()) {
throw new Exception(file + " is not image file error in cutImage!");
}
BufferedImage buffer = ImageIO.read(file);
/*
* width和height为压缩后图片的宽和高
*/
int width = (int) (buffer.getWidth() * scale);
int height = (int) (buffer.getHeight() * scale);
AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(scale, scale), null);
buffer = op.filter(buffer, null);
buffer = buffer.getSubimage(0, 0, width, height);
try {
ImageIO.write(buffer, "jpg", new File(saveToFilePath));
} catch (Exception ex) {
throw new Exception(" ImageIo.write error in CreatThum.: " + ex.getMessage());
}
}
/**
* 切图
* @param originalImg 选择照片路径
* @param toOriginalImg 输出照片路径
* @param rows 切图的行个数
* @param cols 切图的列个数
* @throws IOException
*/
private static void splitImage(String originalImg, String toOriginalImg , int rows , int cols) throws IOException {
// 读入大图
File file = new File(originalImg);
FileInputStream fis = new FileInputStream(file);
BufferedImage image = ImageIO.read(fis);
// 分割成4*4(16)个小图
// int rows = 4;
// int cols = 4;
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++) {
//设置小图的大小和类型
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++) {
ImageIO.write(imgs[i], "jpg", new File(toOriginalImg + i + ".jpg"));
}
}
/**
* 加字水印
* @param srcImgPath 原图片的路径
* @param tarImgPath 新图片的路径
* @param watermarkContent 水印的内容
* @param color 水印的颜色
* @param font 水印的字体
*/
public static void addWatermark(String srcImgPath, String tarImgPath, String watermarkContent, Color color, Font font) {
try {
//获取图片文件
File srcImgfile = new File(srcImgPath);
//把文件转换成图片
Image srcImg = ImageIO.read(srcImgfile);
//获取图片的宽和高
int srcImgwidth = srcImg.getWidth(null);
int srcImgheight = srcImg.getHeight(null);
//画水印需要一个画板 创建一个画板
BufferedImage buffImg = new BufferedImage(srcImgwidth,srcImgheight,BufferedImage.TYPE_INT_RGB);
//创建一个2D的图像
Graphics2D g = buffImg.createGraphics();
//画出来
g.drawImage(srcImg, 0, 0, srcImgwidth, srcImgheight,null);
//设置水印的颜色
g.setColor(color);
//设置水印的字体
g.setFont(font);
//设置水印坐标
int x = srcImgwidth*19/20 -getwaterMarkLength(watermarkContent, g);
int y = srcImgheight*9/10;
//根据获取的坐标 在相应的位置画出水印
g.drawString(watermarkContent, x, y);
//释放画板的资源
g.dispose();
//输出新的图片
FileOutputStream outputStream = new FileOutputStream(srcImgfile);
//创建新的图片
ImageIO.write(buffImg, "jpg", outputStream);
//刷新流
outputStream.flush();
//关闭流
outputStream.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
/**
* 获取水印的坐标
* @param watermarkContent 水印内容
* @param g 2d图像
* @return 水印的长度
*/
public static int getwaterMarkLength(String watermarkContent,Graphics2D g) {
return g.getFontMetrics(g.getFont()).charsWidth(watermarkContent.toCharArray(), 0, watermarkContent.length());
}
/**
* 贴图,贴文字
* @param bigImage 底图
* @param smartImage 小图(标签)
* @param x 基于底图X轴
* @param y 基于底图Y轴
* @param fromToImage 保存地址
*/
public static void chartletImage(String bigImage,String smartImage,int x , int y,String fromToImage){
try {
//A.jpg是背景图
InputStream is = new FileInputStream(bigImage);
//通过JPEG图象流创建JPEG数据流解码器
JPEGImageDecoder jpegDecoder = JPEGCodec.createJPEGDecoder(is);
//解码当前JPEG数据流,返回BufferedImage对象
BufferedImage buffImg = jpegDecoder.decodeAsBufferedImage();
//得到画笔对象
Graphics g = buffImg.getGraphics();
//创建你要附加的图象。
//新的头像的路径
ImageIcon imgIcon = new ImageIcon(smartImage);
//得到Image对象。
Image img = imgIcon.getImage();
//将小图片绘到大图片上。
//5,300 .表示你的小图片在大图片上的位置。
g.drawImage(img, x, y, null);
//设置颜色。
// g.setColor(Color.BLACK);
//最后一个参数用来设置字体的大小
// Font f = new Font("宋体", Font.PLAIN, 50);
// Color mycolor = Color.BLACK;//new Color(0, 0, 255);
// g.setColor(mycolor);
// g.setFont(f);
//10,20 表示这段文字在图片上的位置(x,y) .第一个是你设置的内容。
// g.drawString("你好", 100, 135);
g.dispose();
OutputStream os;
//os = new FileOutputStream("d:/union.jpg");
String shareFileName = fromToImage + System.currentTimeMillis() + ".jpg";
os = new FileOutputStream(shareFileName);
//创键编码器,用于编码内存中的图象数据。
JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
en.encode(buffImg);
is.close();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ImageFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}