import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.coobird.thumbnailator.Thumbnails;
public class ImageUtils {
private static final Logger logger = LoggerFactory.getLogger(ImageUtils.class);
/**
* 将图片转换为byte
* @date 2018年9月11日 下午4:17:47
*/
public static byte[] blobToByte(Blob blob){
if(blob == null){
logger.info("blob 为空");
}
byte[] data = null;
try {
InputStream inStream = blob.getBinaryStream();
long nLen = blob.length();
int nSize = (int) nLen;
data = new byte[nSize];
inStream.read(data);
inStream.close();
} catch (Exception e) {
logger.info("获取图片数据失败,原因:" + e.getMessage());
}
return data;
}
/**
* 对字节数组Base64编码
* @date 2018年9月11日 下午4:20:29
*/
public static String imageToBase64(byte[] data){
String base64 = new String(Base64.encodeBase64(data));
return base64;
}
/**
* 根据指定大小压缩图片
* @author cuishiliang
* @param imageBytes 源图片字节数组
* @param desFileSize 指定图片大小,单位kb
* @param imageId 影像编号
* @return 压缩质量后的图片字节数组
*/
public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize, String imageId) {
if (imageBytes == null || imageBytes.length <= 0 || imageBytes.length < desFileSize * 1024) {
return imageBytes;
}
long srcSize = imageBytes.length;
double accuracy = getAccuracy(srcSize / 1024);
try {
while (imageBytes.length > desFileSize * 1024) {
ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
Thumbnails.of(inputStream)
.scale(accuracy)
.outputQuality(accuracy)
.toOutputStream(outputStream);
imageBytes = outputStream.toByteArray();
}
logger.info("【图片压缩】imageId={} | 图片原大小={}kb | 压缩后大小={}kb",
imageId, srcSize / 1024, imageBytes.length / 1024);
} catch (Exception e) {
logger.error("【图片压缩】msg=图片压缩失败!", e);
}
return imageBytes;
}
/**
* 自动调节精度(经验数值)
* @author cuishiliang
* @param size 源图片大小
* @return 图片压缩质量比
*/
private static double getAccuracy(long size) {
double accuracy;
if (size < 900) {
accuracy = 0.85;
} else if (size < 2047) {
accuracy = 0.6;
} else if (size < 3275) {
accuracy = 0.44;
} else {
accuracy = 0.4;
}
return accuracy;
}
}
image工具类谷歌图片压缩
最新推荐文章于 2022-06-22 19:54:03 发布