来源于网络,本文仅做记录,以备不时之需。
1. png转jpg、旋转图片、压缩图片等
原文地址:ImageUtil图片工具: 压缩/格式转换等 - 开发技术 - 亿速云
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* Created by niewj on 2018/9/10.
*/
public class ImgUtil {// @TODO
private static Logger logger = LoggerFactory.getLogger(ImgUtil.class);
public static final String JPG = "jpg";
public static final String GIF = "gif";
public static final String PNG = "png";
public static final String BMP = "bmp";
public static final int K = 1024;
public static final String TYPE_UNKNOWN = "unknown";
/**
* png格式图片转为jpg格式
*
* @param pngFile
* @return
*/
public static File convert2Jpg(File pngFile) {
// #0. 判空
if (pngFile == null || !pngFile.exists() || !pngFile.isFile() || !pngFile.canRead()) {
return null;
}
File jpgFile = null;
BufferedImage image;
try {
//#1. read image file
image = ImageIO.read(pngFile);
String parentPath = pngFile.getParent();
logger.info(ImgUtil.getPicType(new FileInputStream(pngFile)));
// #2. create a blank, RGB, same width and height, and a white background
BufferedImage newBufferedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
newBufferedImage.createGraphics().drawImage(image, 0, 0, Color.WHITE, null);
// #3. create image filename
long currentMillis = System.currentTimeMillis();
jpgFile = new File(parentPath, currentMillis + ".jpg");
// write to jpeg file
ImageIO.write(newBufferedImage, "jpg", jpgFile);
logger.info("Done");
} catch (IOException e) {
e.printStackTrace();
}
return jpgFile;
}
/**
* 旋转图片
*
* @param sourceFile 原图片
* @param degrees 旋转度数
* @throws IOException
*/
public static void rotate(File sourceFile, double degrees) throws IOException {
Thumbnails.of(sourceFile)
.rotate(degrees)//旋转度数
.scale(1)//缩放比例
.toFile(sourceFile);
}
/**
* 根据文件流判断图片类型
*
* @param fis
* @return jpg/png/gif/bmp
*/
public static String getPicType(FileInputStream fis) {
//读取文件的前几个字节来判断图片格式
byte[] b = new byte[4];
try {
fis.read(b, 0, b.length);
String type = bytesToHexString(b).toUpperCase();
if (type.contains("FFD8FF")) {
return JPG;
} else if (type.contains("89504E47")) {
return PNG;
} else if (type.contains("47494638")) {
return GIF;
} else if (type.contains("424D")) {
return BMP;
} else {
return TYPE_UNKNOWN;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* byte数组转换成16进制字符串
*
* @param src
* @return
*/
private static String bytesToHexString(byte[] src) {
StringBuilder sBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
sBuilder.append(0);
}
sBuilder.append(hv);
}
return sBuilder.toString();
}
/**
* @param srcFile 待压缩的源文件
* @param desFileSize 限制的文件大小,单位Kb
* @param scale 压缩比例(0, 1.0]
*/
public static void commpressPicForScale(File srcFile, long desFileSize, double scale) {
try {
// #0. 获取文件类型,根据内容而不是后缀名
String type = getPicType(new FileInputStream(srcFile));
// #1. 判空
if (srcFile == null || !srcFile.exists() || !srcFile.isFile()) {
return;
}
// #2.输出大小
long len = srcFile.length();
logger.info("源图片:" + srcFile.getAbsolutePath() + ",大小:" + len / K + "kb");
// #3. 递归方法压缩
compressImage(type, srcFile, desFileSize, scale);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 根据照片类型、精确度,上限大小,压缩指定照片
*
* @param type 照片类型:jpg/png (1. type是根据文件的内容定的,而不是名字后缀值; 2. 除了jpg,其他都按照png处理)
* @param srcFile 源文件和目标文件:用的同一个
* @param desFileSize 目标值限制大小,单位Kb
* @param scale 压缩比:(0,1.0]
*/
private static void compressImage(String type, File srcFile, long desFileSize, double scale) {
if (srcFile == null || !srcFile.exists() || !srcFile.isFile()) {
logger.error("_n_待压缩源文件不合要求:srcFile={}", srcFile);
return;
}
try {
long fileSize = srcFile.length();
// 1、判断大小,如果小于500kb,不压缩;如果大于等于500kb,压缩:递归结束条件
if (fileSize <= desFileSize * K) {
return;
}
// 2. jpg格式有不失真的压缩方式;png的没有;
if (JPG.equalsIgnoreCase(type)) {
logger.info("jpg_file_compress:{}", srcFile.getAbsoluteFile());
Thumbnails.of(srcFile).scale(1.0f).outputQuality(scale).toFile(srcFile);
} else { // 其他图片类型,一律按照PNG格式缩放
logger.info("png_file_compress:{}", srcFile.getAbsoluteFile());
Thumbnails.of(srcFile).scale(scale).toFile(srcFile);
}
// 3. 记录下压缩后的大小
logger.info("compressing...{}kb", srcFile.length() / K);
// 4. 递归调用,直到大小符合要求
compressImage(type, srcFile, desFileSize, scale);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取base64字符串
*
* @param file
* @return
*/
public static String getImageBase64(File file) {
FileInputStream inputFile = null;
byte[] buffer = new byte[0];
try {
// #1. Base64输入流
inputFile = new FileInputStream(file);
buffer = new byte[(int) file.length()];
inputFile.read(buffer);
inputFile.close();
} catch (IOException e) {
e.printStackTrace();
} finally { // 用完后删除文件
deleteUploadedFile(file);
}
return new BASE64Encoder().encode(buffer);
}
/**
* 返回之前,把生成的文件删除掉
*
* @param file
*/
public static void deleteUploadedFile(File file) {
// 上传完文件之后,照片或视频文件删除掉
if (file != null && file.exists()) {
logger.info("file deleting: ", file.getAbsolutePath());
file.delete();
}
}
// private static String getImageBase64(String imageId) {
// File orgFile = FtpHelper.getFile(imageId);
// File file = renameFile(orgFile);
// ImageUtil.commpressPicForScale(file, 500, 0.9d); // 压缩照片
// Assert.assertion(file != null, ResponseCodeEnum.INTERNAL_HANDLE_ERROR, "file is not exit");
// FileInputStream inputFile = null;
// byte[] buffer = new byte[0];
// try {
// inputFile = new FileInputStream(file);
// buffer = new byte[(int) file.length()];
// inputFile.read(buffer);
// inputFile.close();
// } catch (Exception e) {
// LOGGER.error("Exception->\n {}", e);
// throw new ThirdPartException(ResponseCodeEnum.INTERNAL_HANDLE_ERROR, StringMsg.fmtMsg("*"));
// } finally { // 用完后删除文件
// FtpHelper.deleteUploadedFile(file);
// FtpHelper.deleteUploadedFile(orgFile);
// }
// return new BASE64Encoder().encode(buffer);
// }
public static void main(String[] args) throws FileNotFoundException {
// File f2 = new File("E:\\chrome_download\\1.png");
// String type2 = ImageUtil.getPicType(new FileInputStream(f2));
// System.out.println("type2=" + type2);
ImageUtil.compressImage(type2, f2, 500, 0.9d);
// File pngFile = new File("C:\\Users\\weijun.nie\\Desktop\\thinkstats\\test2.png");
// File jpgFile = convert2Jpg(pngFile);
// System.out.println(jpgFile.getAbsolutePath());
System.out.printf("%02X", 125);
}
}
2.图片工具类,json工具类 原文地址:https://www.cnblogs.com/hyhy904/p/10942139.html
package com.jarvis.base.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import net.coobird.thumbnailator.Thumbnails;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
*
*
* @Title: ImageHelper.java
* @Package com.jarvis.base.util
* @Description:图片处理工具类。
* @version V1.0
*/
@SuppressWarnings("restriction")
public class ImageHelper {
/**
* @描述:Base64解码并生成图片
* @入参:@param imgStr
* @入参:@param imgFile
* @入参:@throws IOException
* @出参:void
*/
public static void generateImage(String imgStr, String imgFile) throws IOException {
BASE64Decoder decoder = new BASE64Decoder();
// Base64解码
byte[] bytes;
OutputStream out = null;
try {
bytes = decoder.decodeBuffer(imgStr);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
// 生成图片
out = new FileOutputStream(imgFile);
out.write(bytes);
out.flush();
} catch (IOException e) {
throw new IOException();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* @throws IOException
* @描述:根据路径得到base编码后图片
* @入参:@param imgFilePath
* @入参:@return
* @出参:String
*/
public static String getImageStr(String imgFilePath) throws IOException {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imgFilePath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
throw new IOException();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64编码过的字节数组字符串
}
/**
* @throws IOException
* @描述:图片旋转
* @入参:@param base64In 传入的图片base64
* @入参:@param angle 图片旋转度数
* @入参:@throws Exception
* @出参:String 传出的图片base64
*/
public static String imgAngleRevolve(String base64In, int angle) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
Thumbnails.of(base64ToIo(base64In)).scale(1.0).rotate(angle).toOutputStream(os);
} catch (IOException e) {
throw new IOException();
}
byte[] bs = os.toByteArray();
String s = new BASE64Encoder().encode(bs);
return s;
}
/**
* @描述:base64转为io流
* @入参:@param strBase64
* @入参:@return
* @入参:@throws IOException
* @出参:InputStream
*/
public static InputStream base64ToIo(String strBase64) throws IOException {
// 解码,然后将字节转换为文件
byte[] bytes = new BASE64Decoder().decodeBuffer(strBase64); // 将字符串转换为byte数组
return new ByteArrayInputStream(bytes);
}
}
package com.jarvis.base.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
/**
*
*
* @Title: FastJsonUtil.java
* @Package com.jarvis.base.util
* @Description:fastjson工具类
* @version V1.0
*/
public class FastJsonUtil {
private static final SerializeConfig config;
static {
config = new SerializeConfig();
config.put(java.util.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
config.put(java.sql.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
}
private static final SerializerFeature[] features = { SerializerFeature.WriteMapNullValue, // 输出空置字段
SerializerFeature.WriteNullListAsEmpty, // list字段如果为null,输出为[],而不是null
SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,而不是null
SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,而不是null
SerializerFeature.WriteNullStringAsEmpty, // 字符类型字段如果为null,输出为"",而不是null
SerializerFeature.PrettyFormat //是否需要格式化输出Json数据
};
/**
* @param object
* @return Return:String Description:将对象转成成Json对象
*/
public static String toJSONString(Object object) {
return JSON.toJSONString(object, config, features);
}
/**
* @param object
* @return Return:String Description:使用和json-lib兼容的日期输出格式
*/
public static String toJSONNoFeatures(Object object) {
return JSON.toJSONString(object, config);
}
/**
* @param jsonStr
* @return Return:Object Description:将Json数据转换成JSONObject
*/
public static JSONObject toJsonObj(String jsonStr) {
return (JSONObject) JSON.parse(jsonStr);
}
/**
* @param jsonStr
* @param clazz
* @return Return:T Description:将Json数据转换成Object
*/
public static T toBean(String jsonStr, Class clazz) {
return JSON.parseObject(jsonStr, clazz);
}
/**
* @param jsonStr
* @return Return:Object[] Description:将Json数据转换为数组
*/
public static Object[] toArray(String jsonStr) {
return toArray(jsonStr, null);
}
/**
* @param jsonStr
* @param clazz
* @return Return:Object[] Description:将Json数据转换为数组
*/
public static Object[] toArray(String jsonStr, Class clazz) {
return JSON.parseArray(jsonStr, clazz).toArray();
}
/**
* @param jsonStr
* @param clazz
* @return Return:List Description:将Json数据转换为List
*/
public static List toList(String jsonStr, Class clazz) {
return JSON.parseArray(jsonStr, clazz);
}
/**
* 将javabean转化为序列化的JSONObject对象
*
* @param keyvalue
* @return
*/
public static JSONObject beanToJsonObj(Object bean) {
String jsonStr = JSON.toJSONString(bean);
JSONObject objectJson = (JSONObject) JSON.parse(jsonStr);
return objectJson;
}
/**
* json字符串转化为map
*
* @param s
* @return
*/
public static Map, ?> stringToCollect(String jsonStr) {
Map, ?> map = JSONObject.parseObject(jsonStr);
return map;
}
/**
* 将map转化为string
*
* @param m
* @return
*/
public static String collectToString(Map, ?> map) {
String jsonStr = JSONObject.toJSONString(map);
return jsonStr;
}
/**
* @param t
* @param file
* @throws IOException
* Return:void Description:将对象的Json数据写入文件。
*/
public static void writeJsonToFile(T t, File file) throws IOException {
String jsonStr = JSONObject.toJSONString(t, SerializerFeature.PrettyFormat);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(jsonStr);
bw.close();
}
/**
* @param t
* @param filename
* @throws IOException
* Return:void Description:将对象的Json数据写入文件。
*/
public static void writeJsonToFile(T t, String filename) throws IOException {
writeJsonToFile(t, new File(filename));
}
/**
* @param cls
* @param file
* @return
* @throws IOException
* Return:T Description:将文件中的Json数据转换成Object对象
*/
public static T readJsonFromFile(Class cls, File file) throws IOException {
StringBuilder strBuilder = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
while ((line = br.readLine()) != null) {
strBuilder.append(line);
}
br.close();
return JSONObject.parseObject(strBuilder.toString(), cls);
}
/**
* Author:Jack Time:2017年9月2日下午4:22:30
*
* @param cls
* @param filename
* @return
* @throws IOException
* Return:T Description:将文件中的Json数据转换成Object对象
*/
public static T readJsonFromFile(Class cls, String filename) throws IOException {
return readJsonFromFile(cls, new File(filename));
}
/**
* Author:Jack Time:2017年9月2日下午4:23:06
*
* @param typeReference
* @param file
* @return
* @throws IOException
* Return:T Description:从文件中读取出Json对象
*/
public static T readJsonFromFile(TypeReference typeReference, File file) throws IOException {
StringBuilder strBuilder = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
while ((line = br.readLine()) != null) {
strBuilder.append(line);
}
br.close();
return JSONObject.parseObject(strBuilder.toString(), typeReference);
}
/**
* Author:Jack Time:2017年9月2日下午4:23:11
*
* @param typeReference
* @param filename
* @return
* @throws IOException
* Return:T Description:从文件中读取出Json对象
*/
public static T readJsonFromFile(TypeReference typeReference, String filename) throws IOException {
return readJsonFromFile(typeReference, new File(filename));
}
}