目录
文件相关工具类
文件处理工具类
-
文件大小处理工具类
package com.example.exceldemo.utils;
import java.text.DecimalFormat;
/**
* <p>
* 文件大小工具类.
* </p>
*
* @author poplar.yfyang
* @version 1.0 2013-01-02 12:50 PM
* @since JDK 1.5
*/
public class FileSizeHelper {
public static long ONE_KB = 1024;
public static long ONE_MB = ONE_KB * 1024;
public static long ONE_GB = ONE_MB * 1024;
public static long ONE_TB = ONE_GB * (long) 1024;
public static long ONE_PB = ONE_TB * (long) 1024;
public static void main(String args[]) {
System.out.println(getHumanReadableFileSize(1024L*1024));
}
public static String getHumanReadableFileSize(Long fileSize) {
if (fileSize == null) {
return null;
}
return getHumanReadableFileSize(fileSize.longValue());
}
public static String getHumanReadableFileSize(long fileSize) {
if (fileSize < 0) {
return String.valueOf(fileSize);
}
String result = getHumanReadableFileSize(fileSize, ONE_PB, "PB");
if (result != null) {
return result;
}
result = getHumanReadableFileSize(fileSize, ONE_TB, "TB");
if (result != null) {
return result;
}
result = getHumanReadableFileSize(fileSize, ONE_GB, "GB");
if (result != null) {
return result;
}
result = getHumanReadableFileSize(fileSize, ONE_MB, "MB");
if (result != null) {
return result;
}
result = getHumanReadableFileSize(fileSize, ONE_KB, "KB");
if (result != null) {
return result;
}
return String.valueOf(fileSize) + "B";
}
private static String getHumanReadableFileSize(long fileSize, long unit, String unitName) {
if (fileSize == 0) {
return "0";
}
if (fileSize / unit >= 1) {
double value = fileSize / (double) unit;
DecimalFormat df = new DecimalFormat("######.##" + unitName);
return df.format(value);
}
return null;
}
}
图片工具类
-
图片操作工具类(缩放,切图,旋转,水印,压缩,编码处理等)
package com.demo;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.DecimalFormat;
public class ImgUtils {
//###################################################################### 图像处理工具类 ###################################################
/**
* 缩放图片
* @param src 源文件
* @param dest 目标文件
* @param ratio 缩放比例,如 0.1,0.8,1.2,2.4
* @throws IOException
*/
public static void zoom(String src,String dest,double ratio) throws IOException{
//获取文件扩展名
String suffix=src.substring(src.lastIndexOf(".")+1);
//读入文件
BufferedImage bi=ImageIO.read(new File(src));
//计算目标文件宽度
int targetWidth=Integer.parseInt(new DecimalFormat("0").format(bi.getWidth()*ratio));
//计算目标文件高度
int targetHeight=Integer.parseInt(new DecimalFormat("0").format(bi.getHeight()*ratio));
//获取BufferedImage读入的图片的一个缩放的版本
Image image=bi.getScaledInstance(targetWidth,targetHeight,Image.SCALE_DEFAULT);
//创建一张空白的缓存图片
BufferedImage target=new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
//返回一张2D图像
Graphics g=target.createGraphics();
//将BufferedImage读入的图片画到上一步创建的对象上
g.drawImage(image, 0, 0, null);
//释放
g.dispose();
//图像写入文件
ImageIO.write(target, suffix, new File(dest));
}
/**
* 切图
* @param src 源文件
* @param dest 目标文件
* @param startX 起点x坐标
* @param startY 起点y坐标
* @param endX 结束点x坐标
* @param endY 结束点y坐标
* @throws IOException
*/
public static void cut(String src,String dest,int startX,int startY,int endX,int endY) throws IOException{
//获取文件扩展名
String suffix=src.substring(src.lastIndexOf(".")+1);
//读入文件
BufferedImage bi=ImageIO.read(new File(src));
//计算宽度
int width=Math.abs(startX-endX);
//计算高度
int height=Math.abs(startY-endY);
BufferedImage target= bi.getSubimage(startX, startY, width, height);
ImageIO.write(target, suffix, new File(dest));
}
/**
* 旋转图片
*
* @param src 源文件
* @param dest 目标文件
* @param degree 旋转角度
* @param bgcolor 背景色,无背景色为null
* @throws IOException
*/
public static void rotate(String src, String dest, int degree, Color bgcolor) throws IOException {
BufferedImage image = ImageIO.read(new File(src));
int iw = image.getWidth();// 原始图象的宽度
int ih = image.getHeight();// 原始图象的高度
int w = 0;
int h = 0;
int x = 0;
int y = 0;
degree = degree % 360;
if (degree < 0) {
degree = 360 + degree;// 将角度转换到0-360度之间
}
double ang = Math.toRadians(degree);// 将角度转为弧度
/**
* 确定旋转后的图象的高度和宽度
*/
if (degree == 180 || degree == 0 || degree == 360) {
w = iw;
h = ih;
} else if (degree == 90 || degree == 270) {
w = ih;
h = iw;
} else {
double cosVal = Math.abs(Math.cos(ang));
double sinVal = Math.abs(Math.sin(ang));
w = (int) (sinVal * ih) + (int) (cosVal * iw);
h = (int) (sinVal * iw) + (int) (cosVal * ih);
}
x = (w / 2) - (iw / 2);// 确定原点坐标
y = (h / 2) - (ih / 2);
BufferedImage rotatedImage = new BufferedImage(w, h, image.getType());
Graphics2D gs = (Graphics2D) rotatedImage.getGraphics();
if (bgcolor == null) {
rotatedImage = gs.getDeviceConfiguration().createCompatibleImage(w,h, Transparency.TRANSLUCENT);
} else {
gs.setColor(bgcolor);
gs.fillRect(0, 0, w, h);// 以给定颜色绘制旋转后图片的背景
}
AffineTransform at = new AffineTransform();
at.rotate(ang, w / 2, h / 2);// 旋转图象
at.translate(x, y);
AffineTransformOp op = new AffineTransformOp(at,
AffineTransformOp.TYPE_BICUBIC);
op.filter(image, rotatedImage);
image = rotatedImage;
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ImageOutputStream iamgeOut = ImageIO.createImageOutputStream(byteOut);
ImageIO.write(image, "png", iamgeOut);
InputStream is = new ByteArrayInputStream(byteOut.toByteArray());
OutputStream os = new FileOutputStream(new File(dest));
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
os.close();
is.close();
byteOut.close();
}
//################################################################### 对图片进行压缩、水印、伸缩变换、透明处理、格式转换操作 ##############################################
public static final float DEFAULT_QUALITY = 0.2125f ;
/**
*
* 添加图片水印操作(物理存盘,使用默认格式)
*
* @param imgPath
* 待处理图片
* @param markPath
* 水印图片
* @param x
* 水印位于图片左上角的 x 坐标值
* @param y
* 水印位于图片左上角的 y 坐标值
* @param alpha
* 水印透明度 0.1f ~ 1.0f
* @param destPath
* 文件存放路径
* @throws Exception
*
*/
public static void addWaterMark(String imgPath, String markPath, int x, int y, float alpha,String destPath) throws Exception{
try {
BufferedImage bufferedImage = addWaterMark(imgPath, markPath, x, y, alpha);
ImageIO.write(bufferedImage, imageFormat(imgPath), new File(destPath));
} catch (Exception e) {
throw new RuntimeException("添加图片水印异常");
}
}
/**
*
* 添加图片水印操作(物理存盘,自定义格式)
*
* @param imgPath
* 待处理图片
* @param markPath
* 水印图片
* @param x
* 水印位于图片左上角的 x 坐标值
* @param y
* 水印位于图片左上角的 y 坐标值
* @param alpha
* 水印透明度 0.1f ~ 1.0f
* @param format
* 添加水印后存储的格式
* @param destPath
* 文件存放路径
* @throws Exception
*
*/
public static void addWaterMark(String imgPath, String markPath, int x, int y, float alpha,String format,String destPath) throws Exception{
try {
BufferedImage bufferedImage = addWaterMark(imgPath, markPath, x, y, alpha);
ImageIO.write(bufferedImage,format , new File(destPath));
} catch (Exception e) {
throw new RuntimeException("添加图片水印异常");
}
}
/**
*
* 添加图片水印操作,返回BufferedImage对象
*
* @param imgPath
* 待处理图片
* @param markPath
* 水印图片
* @param x
* 水印位于图片左上角的 x 坐标值
* @param y
* 水印位于图片左上角的 y 坐标值
* @param alpha
* 水印透明度 0.1f ~ 1.0f
* @return
* 处理后的图片对象
* @throws Exception
*
*/
public static BufferedImage addWaterMark(String imgPath, String markPath, int x, int y, float alpha) throws Exception{
BufferedImage targetImage = null;
try {
// 加载待处理图片文件
Image img = ImageIO.read(new File(imgPath));
//创建目标图象文件
targetImage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g = targetImage.createGraphics();
g.drawImage(img, 0, 0, null);
// 加载水印图片文件
Image markImg = ImageIO.read(new File(markPath));
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
g.drawImage(markImg, x, y, null);
g.dispose();
} catch (Exception e) {
throw new RuntimeException("添加图片水印操作异常");
}
return targetImage;
}
/**
*
* 添加文字水印操作(物理存盘,使用默认格式)
*
* @param imgPath
* 待处理图片
* @param text
* 水印文字
* @param font
* 水印字体信息 不写默认值为宋体
* @param color
* 水印字体颜色
* @param x
* 水印位于图片左上角的 x 坐标值
* @param y
* 水印位于图片左上角的 y 坐标值
* @param alpha
* 水印透明度 0.1f ~ 1.0f
* @param destPath
* 文件存放路径
* @throws Exception
*/
public static void addTextMark(String imgPath, String text, Font font, Color color, float x, float y, float alpha,String destPath) throws Exception{
try {
BufferedImage bufferedImage = addTextMark(imgPath, text, font, color, x, y, alpha);
ImageIO.write(bufferedImage, imageFormat(imgPath), new File(destPath));
} catch (Exception e) {
throw new RuntimeException("图片添加文字水印异常");
}
}
/**
*
* 添加文字水印操作(物理存盘,自定义格式)
*
* @param imgPath
* 待处理图片
* @param text
* 水印文字
* @param font
* 水印字体信息 不写默认值为宋体
* @param color
* 水印字体颜色
* @param x
* 水印位于图片左上角的 x 坐标值
* @param y
* 水印位于图片左上角的 y 坐标值
* @param alpha
* 水印透明度 0.1f ~ 1.0f
* @param format
* 添加水印后存储的格式
* @param destPath
* 文件存放路径
* @throws Exception
*/
public static void addTextMark(String imgPath, String text, Font font, Color color, float x, float y, float alpha,String format,String destPath) throws Exception{
try {
BufferedImage bufferedImage = addTextMark(imgPath, text, font, color, x, y, alpha);
ImageIO.write(bufferedImage, format, new File(destPath));
} catch (Exception e) {
throw new RuntimeException("图片添加文字水印异常");
}
}
/**
*
* 添加文字水印操作,返回BufferedImage对象
*
* @param imgPath
* 待处理图片
* @param text
* 水印文字
* @param font
* 水印字体信息 不写默认值为宋体
* @param color
* 水印字体颜色
* @param x
* 水印位于图片左上角的 x 坐标值
* @param y
* 水印位于图片左上角的 y 坐标值
* @param alpha
* 水印透明度 0.1f ~ 1.0f
* @return
* 处理后的图片对象
* @throws Exception
*/
public static BufferedImage addTextMark(String imgPath, String text, Font font, Color color, float x, float y, float alpha) throws Exception{
BufferedImage targetImage = null;
try {
Font Dfont = (font == null) ? new Font("宋体", 20, 13) : font;
Image img = ImageIO.read(new File(imgPath));
//创建目标图像文件
targetImage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g = targetImage.createGraphics();
g.drawImage(img, 0, 0, null);
g.setColor(color);
g.setFont(Dfont);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
g.drawString(text, x, y);
g.dispose();
} catch (Exception e) {
throw new RuntimeException("添加文字水印操作异常");
}
return targetImage;
}
/**
*
*
*
* 压缩图片操作(文件物理存盘,使用默认格式)
*
* @param imgPath
* 待处理图片
* @param quality
* 图片质量(0-1之間的float值)
* @param width
* 输出图片的宽度 输入负数参数表示用原来图片宽
* @param height
* 输出图片的高度 输入负数参数表示用原来图片高
* @param autoSize
* 是否等比缩放 true表示进行等比缩放 false表示不进行等比缩放
* @param destPath
* 文件存放路径
*
* @throws Exception
*/
public static void compressImage(String imgPath,float quality,int width, int height, boolean autoSize,String destPath)throws Exception{
try {
BufferedImage bufferedImage = compressImage(imgPath, quality, width, height, autoSize);
ImageIO.write(bufferedImage, imageFormat(imgPath), new File(destPath));
} catch (Exception e) {
throw new RuntimeException("图片压缩异常");
}
}
/**
*
* 压缩图片操作(文件物理存盘,可自定义格式)
*
* @param imgPath
* 待处理图片
* @param quality
* 图片质量(0-1之間的float值)
* @param width
* 输出图片的宽度 输入负数参数表示用原来图片宽
* @param height
* 输出图片的高度 输入负数参数表示用原来图片高
* @param autoSize
* 是否等比缩放 true表示进行等比缩放 false表示不进行等比缩放
* @param format
* 压缩后存储的格式
* @param destPath
* 文件存放路径
*
* @throws Exception
*/
public static void compressImage(String imgPath,float quality,int width, int height, boolean autoSize,String format,String destPath)throws Exception{
try {
BufferedImage bufferedImage = compressImage(imgPath, quality, width, height, autoSize);
ImageIO.write(bufferedImage, format, new File(destPath));
} catch (Exception e) {
throw new RuntimeException("图片压缩异常");
}
}
/**
*
* 压缩图片操作,返回BufferedImage对象
*
* @param imgPath
* 待处理图片
* @param quality
* 图片质量(0-1之間的float值)
* @param width
* 输出图片的宽度 输入负数参数表示用原来图片宽
* @param height
* 输出图片的高度 输入负数参数表示用原来图片高
* @param autoSize
* 是否等比缩放 true表示进行等比缩放 false表示不进行等比缩放
* @return
* 处理后的图片对象
* @throws Exception
*/
public static BufferedImage compressImage(String imgPath,float quality,int width, int height, boolean autoSize)throws Exception{
BufferedImage targetImage = null;
if(quality<0F||quality>1F){
quality = DEFAULT_QUALITY;
}
try {
Image img = ImageIO.read(new File(imgPath));
//如果用户输入的图片参数合法则按用户定义的复制,负值参数表示执行默认值
int newwidth =( width > 0 ) ? width : img.getWidth(null);
//如果用户输入的图片参数合法则按用户定义的复制,负值参数表示执行默认值
int newheight = ( height > 0 )? height: img.getHeight(null);
//如果是自适应大小则进行比例缩放
if(autoSize){
// 为等比缩放计算输出的图片宽度及高度
double Widthrate = ((double) img.getWidth(null)) / (double) width + 0.1;
double heightrate = ((double) img.getHeight(null))/ (double) height + 0.1;
double rate = Widthrate > heightrate ? Widthrate : heightrate;
newwidth = (int) (((double) img.getWidth(null)) / rate);
newheight = (int) (((double) img.getHeight(null)) / rate);
}
//创建目标图像文件
targetImage = new BufferedImage(newwidth,newheight,BufferedImage.TYPE_INT_RGB);
Graphics2D g = targetImage.createGraphics();
g.drawImage(img, 0, 0, newwidth, newheight, null);
//如果添加水印或者文字则继续下面操作,不添加的话直接返回目标文件----------------------
g.dispose();
} catch (Exception e) {
throw new RuntimeException("图片压缩操作异常");
}
return targetImage;
}
/**
* 图片黑白化操作(文件物理存盘,使用默认格式)
*
* @param destPath
* 目标文件地址
* @throws Exception
*
*/
public static void imageGray(String imgPath, String destPath)throws Exception{
imageGray(imgPath, imageFormat(imgPath), destPath);
}
/**
* 图片黑白化操作(文件物理存盘,可自定义格式)
*
* @param format
* 图片格式
* @param destPath
* 目标文件地址
* @throws Exception
*
*/
public static void imageGray(String imgPath,String format, String destPath)throws Exception{
try {
BufferedImage bufferedImage = ImageIO.read(new File(imgPath));
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorConvertOp op = new ColorConvertOp(cs, null);
bufferedImage = op.filter(bufferedImage, null);
ImageIO.write(bufferedImage, format , new File(destPath));
} catch (Exception e) {
throw new RuntimeException("图片灰白化异常");
}
}
/**
* 图片透明化操作(文件物理存盘,使用默认格式)
*
* @param imgPath
* 图片路径
* @param destPath
* 图片存放路径
* @throws Exception
*/
public static void imageLucency(String imgPath,String destPath)throws Exception{
try {
BufferedImage bufferedImage = imageLucency(imgPath);
ImageIO.write(bufferedImage, imageFormat(imgPath), new File(destPath));
} catch (Exception e) {
throw new RuntimeException("图片透明化异常");
}
}
/**
* 图片透明化操作(文件物理存盘,可自定义格式)
*
* @param imgPath
* 图片路径
* @param format
* 图片格式
* @param destPath
* 图片存放路径
* @throws Exception
*/
public static void imageLucency(String imgPath,String format,String destPath)throws Exception{
try {
BufferedImage bufferedImage = imageLucency(imgPath);
ImageIO.write(bufferedImage, format, new File(destPath));
} catch (Exception e) {
throw new RuntimeException("图片透明化异常");
}
}
/**
* 图片透明化操作返回BufferedImage对象
*
* @param imgPath
* 图片路径
* @return
* 透明化后的图片对象
* @throws Exception
*/
public static BufferedImage imageLucency(String imgPath)throws Exception{
BufferedImage targetImage = null;
try {
//读取图片
BufferedImage img = ImageIO.read(new FileInputStream(imgPath));
//透明度
int alpha = 0;
//执行透明化
executeRGB(img, alpha);
targetImage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g = targetImage.createGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
} catch (Exception e) {
throw new RuntimeException("图片透明化执行异常");
}
return targetImage;
}
/**
* 执行透明化的核心算法
*
* @param img
* 图片对象
* @param alpha
* 透明度
* @throws Exception
*/
public static void executeRGB(BufferedImage img, int alpha) throws Exception{
int rgb = 0;//RGB值
//x表示BufferedImage的x坐标,y表示BufferedImage的y坐标
for(int x=img.getMinX();x<img.getWidth();x++){
for(int y=img.getMinY();y<img.getHeight();y++){
//获取点位的RGB值进行比较重新设定
rgb = img.getRGB(x, y);
int R =(rgb & 0xff0000 ) >> 16 ;
int G= (rgb & 0xff00 ) >> 8 ;
int B= (rgb & 0xff );
if(((255-R)<30) && ((255-G)<30) && ((255-B)<30)){
rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);
img.setRGB(x, y, rgb);
}
}
}
}
/**
* 图片格式转化操作(文件物理存盘)
*
* @param imgPath
* 原始图片存放地址
* @param format
* 待转换的格式 jpeg,gif,png,bmp等
* @param destPath
* 目标文件地址
* @throws Exception
*/
public static void formatConvert(String imgPath, String format, String destPath)throws Exception{
try {
BufferedImage bufferedImage = ImageIO.read(new File(imgPath));
ImageIO.write(bufferedImage, format, new File(destPath));
} catch (IOException e) {
throw new RuntimeException("文件格式转换出错");
}
}
/**
* 图片格式转化操作返回BufferedImage对象
*
* @param bufferedImag
* BufferedImage图片转换对象
* @param format
* 待转换的格式 jpeg,gif,png,bmp等
* @param destPath
* 目标文件地址
* @throws Exception
*/
public static void formatConvert(BufferedImage bufferedImag, String format, String destPath)throws Exception{
try {
ImageIO.write(bufferedImag, format, new File(destPath));
} catch (IOException e) {
throw new RuntimeException("文件格式转换出错");
}
}
/**
* 获取图片文件的真实格式信息
*
* @param imgPath
* 图片原文件存放地址
* @return
* 图片格式
* @throws Exception
*/
public static String imageFormat(String imgPath)throws Exception{
String[] filess = imgPath.split("\\\\");
String[] formats = filess[filess.length - 1].split("\\.");
return formats[formats.length - 1];
}
//############################################################### 图片与字符串转换 ###############################################
/**
* 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
* @param imgSrcPath 生成64编码的图片的路径
* @return
*/
public static String getImageStr(String imgSrcPath){
InputStream in=null;
byte[] data=null;
//读取图片字节数组
try {
in=new FileInputStream(imgSrcPath);
data=new byte[in.available()];
in.read(data);
in.close();
} catch ( FileNotFoundException e ) {
e.printStackTrace();
} catch ( IOException e ) {
e.printStackTrace();
}
//对字节数组Base64编码
BASE64Encoder encoder=new BASE64Encoder();
//返回Base64编码过的字节数组字符串
return encoder.encode(data);
}
/**
* 对字节数组字符串进行Base64解码并生成图片
* @param imgStr 转换为图片的字符串
* @param imgCreatePath 将64编码生成图片的路径
* @return
*/
public static boolean generateImage(String imgStr,String imgCreatePath){
if(null==imgStr){ //图像数据为空
return false;
}
BASE64Decoder decoder=new BASE64Decoder();
try {
//Base64解码
byte[] b=decoder.decodeBuffer(imgStr);
for ( int i = 0; i < b.length; i++ ) {
if(b[i]<0){ //调整异常数据
b[i]+=256;
}
}
OutputStream out=new FileOutputStream(imgCreatePath);
out.write(b);
out.flush();
out.close();
return true;
} catch ( IOException e ) {
e.printStackTrace();
return false;
}
}
}
-
图片合并工具类-列
package com.github.wxiaoqi.demo;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
/**
*
*@类功能说明:java拼接多张图片,生成的格式是jpg、bmp、gif等,
* 如果其他格式则报错或者photoshop或者画图工具打不开
*/
public class JoinMoreImage {
/**
* Java拼接多张图片
*
* @param imgs 图片地址集合
* @param type 图片类型
* @param dst_pic //输出的文件:F:/test2.jpg
* @return
*/
public static boolean merge(String[] imgs, String type, String dst_pic) {
//获取需要拼接的图片长度
int len = imgs.length;
//判断长度是否大于0
if (len < 1) {
return false;
}
File[] src = new File[len];
BufferedImage[] images = new BufferedImage[len];
int[][] ImageArrays = new int[len][];
for (int i = 0; i < len; i++) {
try {
src[i] = new File(imgs[i]);
images[i] = ImageIO.read(src[i]);
} catch (Exception e) {
e.printStackTrace();
return false;
}
int width = images[i].getWidth();
int height = images[i].getHeight();
// 从图片中读取RGB 像素
ImageArrays[i] = new int[width * height];
ImageArrays[i] = images[i].getRGB(0, 0, width, height, ImageArrays[i], 0, width);
}
int dst_height = 0;
int dst_width = images[0].getWidth();
//合成图片像素
for (int i = 0; i < images.length; i++) {
dst_width = dst_width > images[i].getWidth() ? dst_width : images[i].getWidth();
dst_height += images[i].getHeight();
}
//合成后的图片
System.out.println("宽度:"+dst_width);
System.out.println("高度:"+dst_height);
if (dst_height < 1) {
System.out.println("dst_height < 1");
return false;
}
// 生成新图片
try {
dst_width = images[0].getWidth();
BufferedImage ImageNew = new BufferedImage(dst_width, dst_height,
BufferedImage.TYPE_INT_RGB);
int height_i = 0;
for (int i = 0; i < images.length; i++) {
ImageNew.setRGB(0, height_i, dst_width, images[i].getHeight(),
ImageArrays[i], 0, dst_width);
height_i += images[i].getHeight();
}
File outFile = new File(dst_pic);
ImageIO.write(ImageNew, type, outFile);// 写图片 ,输出到硬盘
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
//测试类:注意图片的长宽高不一致可能会报错
public static void main(String[] args) {
//输入图片地址
String[] imgs={"D:\\test\\1.jpg","D:\\test\\2.jpg","D:\\test\\3.jpg"};
//调用方法生成图片
JoinMoreImage.merge(imgs,"jpg","D:/test.jpg");
}
}
-
图片合并工具类-九宫格
package com.github.wxiaoqi.demoTest;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
/**
* 该类是图片处理类
*
*/
public final class ImageUtil {
public static String[] getXy(int size){
String[] s = new String[size];
int _x = 0;
int _y = 0;
if(size ==1){
_x = _y = 6;
s[0] = "6,6";
}
if(size == 2){
_x =_y = 4;
s[0] = "4,"+(132/2-60/2);
s[1] = 60+2*_x+","+ (132/2-60/2);
}
if(size == 3){
_x=_y =4;
s[0] = (132/2-60/2)+","+_y;
s[1] = _x+","+(60+2*_y);
s[2] = (60+2*_y)+","+(60+2*_y);
}
if(size ==4){
_x=_y =4;
s[0] = _x+","+_y;
s[1] = (_x*2 + 60)+","+_y;
s[2] = _x+","+(60+2*_y);
s[3] = (60+2*_y)+","+(60+2*_y);
}
if(size == 5){
_x = _y = 3;
s[0] = (132-40*2-_x)/2+","+(132-40*2-_y)/2;
s[1] = ((132-40*2-_x)/2+40+_x)+","+(132-40*2-_y)/2;
s[2] = _x+","+((132-40*2-_x)/2+40+_y);
s[3] = (_x*2+40)+","+((132-40*2-_x)/2+40+_y);
s[4] = (_x*3+40*2)+","+((132-40*2-_x)/2+40+_y);
}
if(size == 6){
_x = _y = 3;
s[0] = _x+","+((132-40*2-_x)/2);
s[1] = (_x*2+40)+","+((132-40*2-_x)/2);
s[2] = (_x*3+40*2)+","+((132-40*2-_x)/2);
s[3] = _x+","+((132-40*2-_x)/2+40+_y);
s[4] = (_x*2+40)+","+((132-40*2-_x)/2+40+_y);
s[5] = (_x*3+40*2)+","+((132-40*2-_x)/2+40+_y);
}
if(size == 7){
_x=_y =3;
s[0] = (132-40)/2+","+_y;
s[1] = _x+","+(_y*2+40);
s[2] = (_x*2+40)+","+(_y*2+40);
s[3] = (_x*3+40*2)+","+(_y*2+40);
s[4] = _x+","+(_y*3+40*2);
s[5] = (_x*2+40)+","+(_y*3+40*2);
s[6] = (_x*3+40*2)+","+(_y*3+40*2);
}
if(size == 8){
_x=_y =3;
s[0] = (132-80-_x)/2+","+_y;
s[1] = ((132-80-_x)/2+_x+40)+","+_y;
s[2] = _x+","+(_y*2+40);
s[3] = (_x*2+40)+","+(_y*2+40);
s[4] = (_x*3+40*2)+","+(_y*2+40);
s[5] = _x+","+(_y*3+40*2);
s[6] = (_x*2+40)+","+(_y*3+40*2);
s[7] = (_x*3+40*2)+","+(_y*3+40*2);
}
if(size == 9){
_x=_y = 3;
s[0]=_x+","+_y;
s[1] = _x*2+40+","+_y;
s[2] = _x*3+40*2 +","+_y;
s[3] = _x+","+(_y*2+40);
s[4] = (_x*2+40)+","+(_y*2+40);
s[5] = (_x*3+40*2)+","+(_y*2+40);
s[6] = _x+","+(_y*3+40*2);
s[7] = (_x*2+40)+","+(_y*3+40*2);
s[8] = (_x*3+40*2)+","+(_y*3+40*2);
}
return s;
}
public static int getWidth(int size){
int width = 0;
if(size == 1){
width = 120;
}
if(size>1 && size<=4){
width = 60;
}
if(size>=5){
width = 40;
}
return width;
}
public static void download(String urlString, String filename,String savePath) throws Exception {
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection con = url.openConnection();
//设置请求超时为5s
con.setConnectTimeout(5*1000);
// 输入流
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
File sf=new File(savePath);
if(!sf.exists()){
sf.mkdirs();
}
OutputStream os = new FileOutputStream(sf.getPath()+File.separator+filename);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
}
public static String zoom(String sourcePath,String targetPath,int width,int height) throws IOException{
File imageFile = new File(sourcePath);
if(!imageFile.exists()){
throw new IOException("Not found the images:"+sourcePath);
}
if(targetPath==null || targetPath.isEmpty()) {
targetPath = sourcePath;
}
String format = sourcePath.substring(sourcePath.lastIndexOf(".")+1,sourcePath.length());
BufferedImage image = ImageIO.read(imageFile);
image = zoom(image,width,height);
ImageIO.write(image, format, new File(targetPath));
return targetPath;
}
private static BufferedImage zoom(BufferedImage sourceImage , int width , int height){
BufferedImage zoomImage = new BufferedImage(width, height, sourceImage.getType());
Image image = sourceImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
Graphics gc = zoomImage.getGraphics();
gc.setColor(Color.WHITE);
gc.drawImage( image , 0, 0, null);
return zoomImage;
}
public static void createImage(List<String> files,String outPath) throws Exception{
String[] imageSize = getXy(files.size());
int width = getWidth(files.size());
BufferedImage ImageNew = new BufferedImage(132,132,BufferedImage.TYPE_INT_RGB);
//设置背景为白色
for(int m=0;m<132;m++){
for(int n=0;n<132;n++){
ImageNew.setRGB(m, n, 0xFFFFFF);
}
}
for(int i=0;i<imageSize.length;i++){
String size = imageSize[i];
String[] sizeArr = size.split(",");
int x = Integer.valueOf(sizeArr[0]);
int y = Integer.valueOf(sizeArr[1]);
String f = zoom(files.get(i),"D:test",width,width);
File fileOne = new File(f);
BufferedImage ImageOne = ImageIO.read(fileOne);
//从图片中读取RGB
int[] ImageArrayOne = new int[width*width];
ImageArrayOne = ImageOne.getRGB(0,0,width,width,ImageArrayOne,0,width);
ImageNew.setRGB(x,y,width,width,ImageArrayOne,0,width);//设置左半部分的RGB
}
File outFile = new File(outPath);
ImageIO.write(ImageNew, "png", outFile);//写图片
}
public static void main(String[] args) throws Exception{
List<String> imgList=new ArrayList<String>();
imgList.add("D:/test/1.jpg");
imgList.add("D:/test/2.jpg");
imgList.add("D:/test/2.jpg");
imgList.add("D:/test/1.jpg");
imgList.add("D:/test/2.jpg");
imgList.add("D:/test/2.jpg");
createImage(imgList,"D:/g.png");
System.out.println("生成完成");
}
}
-
图片比较
package com.zp.demo.utils;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
/**
* 图片比较
*/
public final class ImageCompare {
/**
* 改变成二进制码
*
* @param file
* @return
*/
public static String[][] getPX(File file) {
int[] rgb = new int[3];
BufferedImage bi = null;
try {
bi = ImageIO.read(file);
} catch (Exception e) {
e.printStackTrace();
}
int width = bi.getWidth();
int height = bi.getHeight();
int minx = bi.getMinX();
int miny = bi.getMinY();
String[][] list = new String[width][height];
for (int i = minx; i < width; i++) {
for (int j = miny; j < height; j++) {
int pixel = bi.getRGB(i, j);
rgb[0] = (pixel & 0xff0000) >> 16;
rgb[1] = (pixel & 0xff00) >> 8;
rgb[2] = (pixel & 0xff);
list[i][j] = rgb[0] + "," + rgb[1] + "," + rgb[2];
}
}
return list;
}
/**
* 比较俩个图片的相似度
*
* @param image1
* @param image2
* @return
*/
public static float compareImage(File image1, File image2) {
String[][] list1 = getPX(image1);
String[][] list2 = getPX(image2);
int xiangsi = 0;
int busi = 0;
int i = 0, j = 0;
for (String[] strings : list1) {
if ((i + 1) == list1.length) {
continue;
}
for (int m = 0; m < strings.length; m++) {
try {
String[] value1 = list1[i][j].toString().split(",");
String[] value2 = list2[i][j].toString().split(",");
int k = 0;
for (int n = 0; n < value2.length; n++) {
if (Math.abs(Integer.parseInt(value1[k]) - Integer.parseInt(value2[k])) < 5) {
xiangsi++;
} else {
busi++;
}
}
} catch (RuntimeException e) {
continue;
}
j++;
}
i++;
}
list1 = getPX(image1);
list2 = getPX(image2);
i = 0;
j = 0;
for (String[] strings : list1) {
if ((i + 1) == list1.length) {
continue;
}
for (int m = 0; m < strings.length; m++) {
try {
String[] value1 = list1[i][j].toString().split(",");
String[] value2 = list2[i][j].toString().split(",");
int k = 0;
for (int n = 0; n < value2.length; n++) {
if (Math.abs(Integer.parseInt(value1[k]) - Integer.parseInt(value2[k])) < 5) {
xiangsi++;
} else {
busi++;
}
}
} catch (RuntimeException e) {
continue;
}
j++;
}
i++;
}
String baifen = "";
try {
baifen = ((Double.parseDouble(xiangsi + "") / Double.parseDouble((busi + xiangsi) + "")) + "");
baifen = baifen.substring(baifen.indexOf(".") + 1, baifen.indexOf(".") + 3);
} catch (Exception e) {
baifen = "0";
}
if (baifen.length() <= 0) {
baifen = "0";
}
if (busi == 0) {
baifen = "100";
}
return Integer.parseInt(baifen);
}
}
-
条形码,二维码生成与解码
package com.example.exceldemo.utils;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;
/**
* 条形码和二维码编码解码
*
* 相关pom依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.2</version>
</dependency>
*/
public class ZxingHandler {
/**
* 条形码编码
*
* @param contents
* @param width
* @param height
* @param imgPath
*/
public static void encode(String contents, int width, int height, String imgPath) {
int codeWidth = 3 + // start guard
(7 * 6) + // left bars
5 + // middle guard
(7 * 6) + // right bars
3; // end guard
codeWidth = Math.max(codeWidth, width);
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
BarcodeFormat.EAN_13, codeWidth, height, null);
MatrixToImageWriter
.writeToFile(bitMatrix, "png", new File(imgPath));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 条形码解码
*
* @param imgPath
* @return String
*/
public static String decode(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("the decode image may be not exit.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
result = new MultiFormatReader().decode(bitmap, null);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 二维码编码
*
* @param contents
* @param width
* @param height
* @param imgPath
*/
public static void encode2(String contents, int width, int height, String imgPath) {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
// 指定纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
// 指定编码格式
hints.put(EncodeHintType.CHARACTER_SET, "GBK");
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter
.writeToFile(bitMatrix, "png", new File(imgPath));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 二维码解码
*
* @param imgPath
* @return String
*/
public static String decode2(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("the decode image may be not exit.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, "GBK");
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param args
*/
public static void main(String[] args) {
// 条形码
String imgPath = "D:\\zxing_EAN13.png";
String contents = "6923450657713";
int width = 105, height = 50;
ZxingHandler.encode(contents, width, height, imgPath);
System.out.println("条形码生成成功");
String decodeContent = ZxingHandler.decode(imgPath);
System.out.println("解码内容如下:" + decodeContent);
System.out.println("条形码解码成功");
// 二维码
String imgPath2 = "D:\\zxing.png";
String contents2 = "Hello Gem, welcome to Zxing!"
+ "\nBlog [ http://thinkgem.iteye.com ]"
+ "\nEMail [ thinkgem@163.com ]";
int width2 = 300, height2 = 300;
ZxingHandler.encode2(contents2, width2, height2, imgPath2);
System.out.println("二维码生成成功");
String decodeContent2 = ZxingHandler.decode2(imgPath2);
System.out.println("解码内容如下:" + decodeContent2);
System.out.println("二维码解码成功");
}
}