import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class ImgUtils {
/**
* 根据两张图片和文件类型型来判断两张图片的base64来判断是否为同一张图片
*
* @return
*/
public Boolean decideImg(File source, File target, String sourceType, String targetType) {
String sourceBase64 = FileUtil.imgToBase64ByFile(source, sourceType);
String targetBase64 = FileUtil.imgToBase64ByFile(target, targetType);
if (sourceBase64.equals(targetBase64)) {
return false;
} else {
return true;
}
}
/**
* MultipartFile 转base64
*
* @param mFile
* @return
* @throws Exception
*/
public static String multipartFileToBASE64(MultipartFile mFile) throws Exception {
String[] suffixArra = mFile.getOriginalFilename().split("\\.");
String preffix = "data:image/jpg;base64,".replace("jpg", suffixArra[suffixArra.length - 1]);
File file = new File(mFile.getOriginalFilename());
FileUtils.copyInputStreamToFile(mFile.getInputStream(), file);
FileInputStream inputFile = null;
byte[] buffer = null;
try {
inputFile = new FileInputStream(file);
buffer = new byte[(int) file.length()];
inputFile.read(buffer);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputFile != null) {
try {
inputFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return preffix + Base64.encodeBase64String(buffer);
}
/**
* 图片转base64
* @param imagePath 图片路径
* @return
*/
public static String imageToBase64Str(String imagePath) {
String[] suffixArra = imagePath.split("\\.");
String preffix = "data:image/jpg;base64,".replace("jpg", suffixArra[suffixArra.length - 1]);
File file = new File(imagePath);
ByteArrayOutputStream baos = null;
try {
BufferedImage bufferedImage = ImageIO.read(file);
baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, suffixArra[suffixArra.length - 1], baos);
byte[] bytes = baos.toByteArray();
return preffix + java.util.Base64.getEncoder().encodeToString(bytes);
} catch (Exception var16) {
var16.printStackTrace();
} finally {
try {
if (baos != null) {
baos.close();
}
} catch (IOException var15) {
var15.printStackTrace();
}
}
return "";
}
/**
* base64转InputStream
* @param base64String base64 字符串
* @return
*/
public static InputStream base64ToInputStream(String base64String){
// data:image/jpeg;base64,/9j/4A
String[] datas = base64String.split(",");
String suffix = datas[0].split(";")[0].replaceAll("data:image/", "");
byte[] bytes = java.util.Base64.getDecoder().decode(datas[1]);
return new ByteArrayInputStream(bytes);
}
/**
* base64转图片
* @param base64String base64 字符串
* @param path 图片保存地址
* @return
*/
public static void base64ToFile(String base64String, String path){
ByteArrayInputStream bais = null;
try {
// data:image/jpeg;base64,/9j/4A
String[] datas = base64String.split(",");
String suffix = datas[0].split(";")[0].replaceAll("data:image/", "");
byte[] bytes = java.util.Base64.getDecoder().decode(datas[1]);
bais = new ByteArrayInputStream(bytes);
BufferedImage bufferedImage = ImageIO.read(bais);
File imageFile = new File(path);
ImageIO.write(bufferedImage, suffix, imageFile);
} catch (Exception var15) {
var15.printStackTrace();
} finally {
try {
if (bais != null) {
bais.close();
}
} catch (IOException var14) {
var14.printStackTrace();
}
}
}
/**
* 压缩图片
* @param file
* @param qality 参数qality是取值0~1范围内 代表压缩的程度
* @return
* @throws IOException
*/
public static File compressPictureByQality(File file,float qality) throws IOException {
BufferedImage src = null;
FileOutputStream out = null;
ImageWriter imgWrier;
ImageWriteParam imgWriteParams;
// 指定写图片的方式为 jpg
imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(
null);
// 要使用压缩,必须指定压缩方式为MODE_EXPLICIT
imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
// 这里指定压缩的程度,参数qality是取值0~1范围内,
imgWriteParams.setCompressionQuality(qality);
imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
ColorModel colorModel =ImageIO.read(file).getColorModel();// ColorModel.getRGBdefault();
imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(
colorModel, colorModel.createCompatibleSampleModel(32, 32)));
if (!file.exists()) {
throw new FileNotFoundException("Not Found Img File,文件不存在");
} else {
src = ImageIO.read(file);
out = new FileOutputStream(file);
imgWrier.reset();
// 必须先指定 out值,才能调用write方法, ImageOutputStream可以通过任何
// OutputStream构造
imgWrier.setOutput(ImageIO.createImageOutputStream(out));
// 调用write方法,就可以向输入流写图片
imgWrier.write(null, new IIOImage(src, null, null),
imgWriteParams);
out.flush();
out.close();
return file;
}
}
/**
* @param srcImgPath 源图片路径
* @param tarImgPath 保存的图片路径
* @param waterMarkContent 水印内容
* @param markContentColor 水印颜色
* @param font 水印字体
*/
public static void addWaterMark(String srcImgPath, String tarImgPath, String waterMarkContent,Color markContentColor,Font font) {
try {
// 读取原图片信息
File srcImgFile = new File(srcImgPath);//得到文件
Image srcImg = ImageIO.read(srcImgFile);//文件转化为图片
int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
int srcImgHeight = srcImg.getHeight(null);//获取图片的高
// 加水印
BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufImg.createGraphics();
g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
g.setColor(markContentColor); //根据图片的背景设置水印颜色
g.setFont(font); //设置字体
//设置水印的坐标
int x = srcImgWidth - 1*getWatermarkLength(waterMarkContent, g);
int y = srcImgHeight - 1*getWatermarkLength(waterMarkContent, g);
g.drawString(waterMarkContent, x, y); //画出水印
g.dispose();
// 输出图片
FileOutputStream outImgStream = new FileOutputStream(tarImgPath);
ImageIO.write(bufImg, "png", outImgStream);
System.out.println("添加水印完成");
outImgStream.flush();
outImgStream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
}
//将图片转化为字节数组
public static byte[] image2byte(String path){
byte[] data = null;
FileImageInputStream input = null;
try {
input = new FileImageInputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int numBytesRead = 0;
while ((numBytesRead = input.read(buf)) != -1) {
output.write(buf, 0, numBytesRead);
}
data = output.toByteArray();
output.close();
input.close();
}
catch (FileNotFoundException ex1) {
ex1.printStackTrace();
}
catch (IOException ex1) {
ex1.printStackTrace();
}
return data;
}
// 根据图片字节数组,转换为图片文件
public static void byte2image(byte[] data,String path){
if(data.length<3||path.equals("")) return;
try{
FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
InputStream in = new ByteArrayInputStream(data);
BufferedImage bImageFromConvert = ImageIO.read(in);
Graphics2D g2d = (Graphics2D) bImageFromConvert.getGraphics();
AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f);
g2d.setComposite(alphaChannel);
g2d.setColor(Color.red);
g2d.setFont(new Font("微软雅黑", Font.BOLD+Font.ITALIC, 80));
FontMetrics fontMetrics = g2d.getFontMetrics();
Rectangle2D rect = fontMetrics.getStringBounds("仅供预览", g2d);
// calculates the coordinate where the String is painted
int centerX = bImageFromConvert.getWidth() /3 ;
int centerY = bImageFromConvert.getHeight()/2;
// paints the textual watermark
g2d.drawString("仅供预览", centerX, centerY);
ImageIO.write(bImageFromConvert, "png", imageOutput);
g2d.dispose();
in.close();
imageOutput.close();
} catch(Exception ex) {
System.out.println("Exception: " + ex);
ex.printStackTrace();
}
}
//byte数组到16进制字符串
public String byte2string(byte[] data){
if(data==null||data.length<=1) return "0x";
if(data.length>200000) return "0x";
StringBuffer sb = new StringBuffer();
int buf[] = new int[data.length];
//byte数组转化成十进制
for(int k=0;k<data.length;k++){
buf[k] = data[k]<0?(data[k]+256):(data[k]);
}
//十进制转化成十六进制
for(int k=0;k<buf.length;k++){
if(buf[k]<16) sb.append("0"+Integer.toHexString(buf[k]));
else sb.append(Integer.toHexString(buf[k]));
}
return "0x"+sb.toString().toUpperCase();
}
private static byte[] generateText(String pressText, String path, int x, int y, String fontName,
int fontSize, Color fontColor, int style){
try {
BufferedImage bgImage= ImageIO.read(new File(path));
int wideth = bgImage.getWidth(null);
int height = bgImage.getHeight(null);
BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.drawImage(bgImage, 0, 0, wideth, height, null);
//设置字体大小、颜色等
g.setColor(fontColor);
g.setFont(new Font(fontName, style, fontSize));
g.drawString(pressText, x, y);
g.dispose();
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", out);
return out.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* pdf转图片
* @param pdfPath
* @param outPath
*/
public static void pdf2Image(String pdfPath, String outPath) {
try {
InputStream is = new FileInputStream(pdfPath);
PDDocument pdf = PDDocument.load(is);
int actSize = pdf.getNumberOfPages();
java.util.List<BufferedImage> picList = new ArrayList<BufferedImage>();
for (int i = 0; i < actSize; i++) {
BufferedImage image = new PDFRenderer(pdf).renderImageWithDPI(i,130, ImageType.RGB);
picList.add(image);
}
splicingImage(picList, outPath);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 将宽度相同的图片,竖向追加在一起 ##注意:宽度必须相同
* @param picList 文件流数组
* @param outPath 输出路径
*/
public static void splicingImage(java.util.List<BufferedImage> picList, String outPath) {
if (picList == null || picList.size() <= 0) {
System.out.println("图片数组为空!");
return;
}
try {
int height = 0, // 总高度
width = 0, // 总宽度
_height = 0, // 临时的高度 , 或保存偏移高度
__height = 0, // 临时的高度,主要保存每个高度
picNum = picList.size();// 图片的数量
int[] heightArray = new int[picNum]; // 保存每个文件的高度
BufferedImage buffer = null; // 保存图片流
List<int[]> imgRGB = new ArrayList<int[]>(); // 保存所有的图片的RGB
int[] _imgRGB; // 保存一张图片中的RGB数据
for (int i = 0; i < picNum; i++) {
buffer = picList.get(i);
heightArray[i] = _height = buffer.getHeight();// 图片高度
if (i == 0) {
width = buffer.getWidth();// 图片宽度
}
height += _height; // 获取总高度
_imgRGB = new int[width * _height];// 从图片中读取RGB
_imgRGB = buffer.getRGB(0, 0, width, _height, _imgRGB, 0, width);
imgRGB.add(_imgRGB);
}
_height = 0; // 设置偏移高度为0
// 生成新图片
BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < picNum; i++) {
__height = heightArray[i];
if (i != 0) _height += __height; // 计算偏移高度
imageResult.setRGB(0, _height, width, __height, imgRGB.get(i), 0, width); // 写入流中
}
File outFile = new File(outPath);
ImageIO.write(imageResult, "jpg", outFile);// 写图片
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 请求图片地址, 返回的结果进行base64编码
* @param imgPath 图片地址
* @return
*/
public static String requestUrlToBase64(String imgPath) {
String result = null;
try {
// 获取请求输入流
InputStream inputStream = new FileInputStream(imgPath);
// inputStream流数据转ByteArrayOutputStream
int len = -1;
byte[] buffer = new byte[1024];
ByteArrayOutputStream out = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
// ByteArrayOutputStream编码成base64字符串
result = new String(java.util.Base64.getEncoder().encode(out.toByteArray()));
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 保存图片
* @param source 源文件
* @param target 图片地址
* @return
*/
public void updateFile(MultipartFile source, File target) throws Exception {
//判断下文件不可为空
if (source == null) {
throw new Exception("上传文件为空");
}
String uploadPath = "E:\\";
File dir = new File(uploadPath);
if (!dir.exists()) {
dir.mkdirs();
}
try {
// String fileName = getFileName(uploadPath + "/" + wjlj, source.getOriginalFilename());
// File target = new File(uploadPath + "/" + wjlj + "/" + fileName);
FileUtils.copyInputStreamToFile(source.getInputStream(), target);
} catch (IOException e) {
throw new RuntimeException("存储文件出错");
}
}
/**
* 获取新文件名称
* @param wjlj 文件路径
* @param fileName 文件名
* @return
*/
public String getFileName(String wjlj, String fileName) {
String newFileName = fileName;
File file = new File(wjlj + "/" + fileName);
if (file.exists()) {
String suffix = fileName.substring(fileName.lastIndexOf("."));
String fileName1 = "";
if (fileName.indexOf("_") > 0) {
fileName1 = fileName.substring(0, fileName.lastIndexOf("_"));
} else {
fileName1 = fileName.substring(0, fileName.lastIndexOf("."));
}
fileName1 += "_" + getStringRandom(4) + suffix;
newFileName = getFileName(wjlj, fileName1);
}
return newFileName;
}
public String getStringRandom(int length) {
String val = "";
Random random = new Random();
// 参数length,表示生成几位随机数
for (int i = 0; i < length; i++) {
String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
// 输出字母还是数字
if ("char".equalsIgnoreCase(charOrNum)) {
// 输出是大写字母还是小写字母
int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
val += (char) (random.nextInt(26) + temp);
} else if ("num".equalsIgnoreCase(charOrNum)) {
val += String.valueOf(random.nextInt(10));
}
}
return val;
}
}
import java.io.*;
import static org.apache.commons.codec.binary.Base64.encodeBase64String;
/**
* 文件操作类
*/
public class FileUtil {
public static String imgToBase64(String path,String fileType){
File file = new File(path);
String base64 = FileUtil.file2base64(file);
return "data:image/" + fileType + ";base64," + base64;
}
public static String imgToBase64ByFile(File file,String fileType){
String base64 = FileUtil.file2base64(file);
return "data:image/" + fileType + ";base64," + base64;
}
public static String pdfToBase64(File file){
String base64 = FileUtil.file2base64(file);
return "data:application/pdf;base64," + base64;
}
public static String file2base64(File file) {
try {
byte[] buffer;
FileInputStream inputFile = new FileInputStream(file);
buffer = new byte[(int) file.length()];
inputFile.read(buffer);
return encodeBase64String(buffer);
} catch (Exception e ) {
log.error(e.getMessage(), e);
e.printStackTrace();
}
return "";
}
}