packagecom.jx.utils;importcom.sun.image.codec.jpeg.JPEGCodec;importcom.sun.image.codec.jpeg.JPEGImageEncoder;importsun.misc.BASE64Decoder;importsun.misc.BASE64Encoder;importjavax.imageio.ImageIO;importjavax.imageio.ImageReadParam;importjavax.imageio.ImageReader;importjavax.imageio.stream.ImageInputStream;importjavax.imageio.stream.ImageOutputStream;import java.awt.*;importjava.awt.image.BufferedImage;import java.io.*;importjava.net.URL;importjava.util.Iterator;/*** @Author jingXuan
* @Date 2020/10/14
* @Description 图片处理工具类*/
public classImageUtils {public static String PREFIX_HTTP = "http:";public static String PREFIX_HTTPS = "https:";public static int BUFFER_SIZE = 1024;/*** 根据图片路径读取该图片的IO流
*
*@paramimageUrl 图片地址
*@return图片IO流*/
public staticInputStream readImage(String imageUrl) {if(isEmpty(imageUrl)) {return null;
}try{if (imageUrl.startsWith(PREFIX_HTTP) ||imageUrl.startsWith(PREFIX_HTTPS)) {//读取网络图片
URL urls = newURL(imageUrl);returnurls.openConnection().getInputStream();
}else{//读取本地图片
return new FileInputStream(newFile(imageUrl));
}
}catch(IOException var) {throw new IllegalArgumentException("read image inputStream error :", var);
}
}/*** 保存图片到本地地址
*
*@paramfileUrl 图片地址
*@paramwriteUrl 保存图片地址
*@returntrue:成功 false:失败*/
public static booleanwriteImage(String fileUrl, String writeUrl) {//读取IO流
InputStream input =readImage(fileUrl);if (input == null ||isEmpty(writeUrl)) {return false;
}returntransformWrite(input, getOutputStream(writeUrl));
}/*** 保存图片到本地地址
*
*@parambytes 数组
*@paramwriteUrl 保存图片地址
*@return
*/
public static boolean writeImage(byte[] bytes, String writeUrl) {
InputStream inputStream=imageByteArray(bytes);if (inputStream == null ||isEmpty(writeUrl)) {return false;
}returntransformWrite(inputStream, getOutputStream(writeUrl));
}/*** 根据图片路径转换成字节数组
*
*@paramfileUrl 图片路径
*@return
*/
public static byte[] bytesImage(String fileUrl) {
InputStream input=readImage(fileUrl);if (input == null) {return null;
}
ByteArrayOutputStream out= null;try{
out= newByteArrayOutputStream();byte[] buf = new byte[BUFFER_SIZE];int len = 0;while ((len = input.read(buf)) != -1) {
out.write(buf,0, len);
}returnout.toByteArray();
}catch(IOException e) {throw new IllegalArgumentException("convert image to byte array error:", e);
}finally{
close(input, out);
}
}/*** 将IO流转换成byte数组
*
*@paraminput
*@return
*/
public static byte[] bytesImage(InputStream input) {if (input == null) {return null;
}try{byte[] data = new byte[input.available()];
input.read(data);returndata;
}catch(IOException e) {throw new IllegalArgumentException("convert image to byte array error:", e);
}finally{
close(input,null);
}
}/*** 将byte array 转成IO流
*
*@parambytes
*@return
*/
public static InputStream imageByteArray(byte[] bytes) {if (bytes == null || bytes.length == 0) {return null;
}return newByteArrayInputStream(bytes);
}/*** 将input保存到out中
*
*@paraminput
*@paramout
*@return
*/
public static booleantransformWrite(InputStream input, OutputStream out) {try{//缓冲区
byte[] buf = new byte[BUFFER_SIZE];int len = 0;while ((len = input.read(buf)) != -1) {
out.write(buf,0, len);
}//刷到硬盘中
out.flush();return true;
}catch(IOException e) {throw new IllegalArgumentException("write image error:", e);
}finally{
close(input, out);
}
}/*** 根据路径生成输出流
*
*@parampath
*@return
*/
public staticOutputStream getOutputStream(String path) {if(isEmpty(path)) {throw new IllegalArgumentException("file path cannot null error");
}try{return newFileOutputStream(path);
}catch(FileNotFoundException e) {throw new IllegalArgumentException("file not found error:", e);
}
}/*** 关闭IO流
*
*@paraminput
*@paramout*/
private static voidclose(InputStream input, OutputStream out) {if (out != null) {try{
out.close();
}catch(IOException e) {throw new IllegalArgumentException("close OutputStream ERROR:", e);
}
}if (input != null) {try{
input.close();
}catch(IOException e) {throw new IllegalArgumentException("close InputStream ERROR:", e);
}
}
}/*** 关闭io流
*
*@paramvar1
*@paramvar2*/
private static voidclose(OutputStream var1, ImageOutputStream var2) {if (var1 != null) {try{
var1.close();
}catch(IOException e) {throw new IllegalArgumentException("close OutputStream ERROR:", e);
}
}if (var2 != null) {try{
var2.close();
}catch(IOException e) {throw new IllegalArgumentException("close OutputStream ERROR:", e);
}
}
}/*** 将IO转换成base64的字符串
*
*@paraminputStream
*@return
*/
public staticString imageBase64(InputStream inputStream) {if (inputStream == null) {return null;
}//将数据转换成byte数组
byte[] bytes =bytesImage(inputStream);//加密
BASE64Encoder encoder = newBASE64Encoder();returnencoder.encode(bytes);
}/*** 将图片地址转换成base64的字符串
*
*@paramfileUrl
*@return
*/
public staticString imageBase64(String fileUrl) {
InputStream inputStream=readImage(fileUrl);if (inputStream == null) {return null;
}returnimageBase64(inputStream);
}/*** 将base64图片字符串转换成数组
*
*@parambase64Image
*@return
*/
public static byte[] base64ByteArray(String base64Image) {if(isEmpty(base64Image)) {return null;
}
BASE64Decoder decoder= newBASE64Decoder();try{returndecoder.decodeBuffer(base64Image);
}catch(IOException e) {throw new IllegalArgumentException("convert base64 Image to byte array error:", e);
}
}/*** 将base64图片字符串转换成IO流
*
*@parambase64Image
*@return
*/
public staticInputStream base64Stream(String base64Image) {byte[] bytes =base64ByteArray(base64Image);return newByteArrayInputStream(bytes);
}/*** 判断字符串是否为空
*
*@paramvar
*@return
*/
public static booleanisEmpty(String var) {return var == null || var.trim().length() == 0;
}/*** 压缩图片处理
*
*@paramimageUrl 图片地址
*@paramwidth 图片宽
*@paramheight 图片高
*@paramrate 压缩比例
*@return
*/
public staticInputStream compressImage(String imageUrl, Integer width, Integer height, Float rate) {
InputStream inputStream=readImage(imageUrl);if (inputStream == null) {return null;
}
ByteArrayOutputStream bs= null;
ImageOutputStream imOut= null;try{//处理图片生成新的BufferedImage
BufferedImage tag =handleImage(inputStream, width, height, rate);
bs= newByteArrayOutputStream();
imOut=ImageIO.createImageOutputStream(bs);
ImageIO.write(tag,"png", imOut);return newByteArrayInputStream(bs.toByteArray());
}catch(IOException e) {throw new IllegalArgumentException("compress image error:", e);
}finally{
close(bs, imOut);
}
}/*** 压缩图片处理
*
*@paramimageUrl 图片地址
*@paramsaveUrl 保存图片地址
*@paramwidth 压缩的图片宽
*@paramheight 压缩的图片高
*@paramrate 压缩比例
*@return
*/
public static booleancompressImage(String imageUrl, String saveUrl, Integer width, Integer height, Float rate) {if (isEmpty(imageUrl) ||isEmpty(saveUrl)) {return false;
}//读取io流
InputStream inputStream =readImage(imageUrl);
OutputStream out= null;try{//处理图片生成新的BufferedImage
BufferedImage tag =handleImage(inputStream, width, height, rate);if (tag == null) {return false;
}//创建文件输出流
out = newFileOutputStream(saveUrl);//将图片按JPEG压缩,保存到out中
JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
}catch(IOException e) {throw new IllegalArgumentException("compress image error:", e);
}finally{
close(inputStream, out);
}return true;
}/*** 处理图片生成新的BufferedImage
*
*@paraminputStream
*@paramwidth
*@paramheight
*@paramrate
*@return*@throwsIOException*/
public static BufferedImage handleImage(InputStream inputStream, Integer width, Integer height, Float rate) throwsIOException {//转换流成图片流
BufferedImage bufferedImage =ImageIO.read(inputStream);//原图片高
int srcHeight =bufferedImage.getHeight();//原图片宽
int srcWidth =bufferedImage.getWidth();
System.out.println("原图片的高:" + srcHeight + ";宽:" +srcWidth);if (rate != null && rate > 0) {
width= (int) (srcWidth *rate);
height= (int) (srcHeight *rate);
}if (width == null || height == null) {return null;
}
System.out.println("压缩文件的高:" + height + ";宽:" +width);//绘制图像:返回一个新的按照with,height缩放呈现的Image
Image scaledInstance =bufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);//构造一个新的BufferedImage
bufferedImage = newBufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bufferedImage.getGraphics().drawImage(scaledInstance,0, 0, null);returnbufferedImage;
}/*** 处理图片生成新的BufferedImage
*
*@paraminputStream
*@paramwidth
*@paramheight
*@paramx
*@paramy
*@paramsuffix
*@return*@throwsIOException*/
public static BufferedImage handleImage(InputStream inputStream, int width, int height, int x, int y, String suffix) throwsIOException {
Iterator it =ImageIO.getImageReadersByFormatName(suffix);
ImageReader reader=it.next();
ImageInputStream imageInputStream=ImageIO.createImageInputStream(inputStream);
reader.setInput(imageInputStream,true);
ImageReadParam param=reader.getDefaultReadParam();
Rectangle rect= newRectangle(x, y, width, height);
param.setSourceRegion(rect);return reader.read(0, param);
}/*** 截取指定位置的图片并保存到指定位置
*
*@paramimageUrl
*@paramsaveUrl
*@paramwidth
*@paramheight
*@paramx
*@paramy
*@return
*/
public static boolean cutImage(String imageUrl, String saveUrl, int width, int height, int x, inty) {if (isEmpty(imageUrl) ||isEmpty(saveUrl)) {return false;
}try{//图片后缀名
String suffix = imageUrl.substring(imageUrl.lastIndexOf(".") + 1);//读取io流
InputStream inputStream =readImage(imageUrl);//处理图片
BufferedImage bi =handleImage(inputStream, width, height, x, y, suffix);//写入IO
ImageIO.write(bi, suffix, newFile(saveUrl));return true;
}catch(IOException e) {throw new IllegalArgumentException("cut image error:", e);
}
}
}