public class OSSClientUtil {
Logger logger = LoggerFactory.getLogger(OSSClientUtil.class);
// endpoint以杭州为例,其它region请按实际情况填写
private String endpoint = ConstUtil.ENDPOINT;
// accessKey
private String accessKeyId = ConstUtil.ACCESSKEYID;
private String accessKeySecret = ConstUtil.ACCESSKEYSECRET;
//空间
private String bucketName = ConstUtil.BUCKETNAME;
//文件存储目录
private String filedir = ConstUtil.FILEDIR;
private OSSClient ossClient;
public OSSClientUtil() {
ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
/**
* 初始化
*/
public void init() {
ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
/**
* 销毁
*/
public void destory() {
ossClient.shutdown();
}
/**
* 上传图片
*/
public String uploadImg2Oss(MultipartFile file, Integer widthValue, Integer heightValue, int isCompress, String dirName, String dirkName, String ossImageDomain) {
//获取文件名字
String originalFilename = file.getOriginalFilename();
//文件后缀格式
String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
//根据时间给文件一个新的名字
SimpleDateFormat dt = new SimpleDateFormat("yyyyMMddHH");
//图片上级文件夹
String path = dt.format(new Date());
//图片名称
SimpleDateFormat dh = new SimpleDateFormat("yyyyMMddHHmmss");
String newname = dh.format(new Date());
String newImgName = newname + "_"
+ new Random().nextInt(1000) + substring;
filedir = filedir + dirName + "/" + dirkName + "/" + path + "/";//图片存储路径
try {
//将文件流化再压缩
InputStream inputStream = file.getInputStream();
if (widthValue != null && heightValue != null && isCompress == 1) {
Image bi = ImageIO.read(inputStream);//读取文件流写成图片
//根据宽高压缩
BufferedImage tag = new BufferedImage(widthValue, heightValue, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(bi, 0, 0, widthValue, heightValue, null);
//新建一个ByteArrayOutputStream把数据暂时保存在java内存中
ByteArrayOutputStream os = new ByteArrayOutputStream();
//写入ByteArrayOutputStream,substring.substring(1, substring.length())获取的是原文件后缀
ImageIO.write(tag, substring.substring(1, substring.length()), os);
//用文件流再次读取图片
inputStream = new ByteArrayInputStream(os.toByteArray());
}
String urlname = this.ossUpload(inputStream, filedir + newImgName, ossImageDomain);
return urlname;
} catch (Exception e) {
logger.error(e.getMessage(), e);
return "error图片上传失败";
}
}
/**
* 获得图片路径
*
* @param fileUrl
* @return
*/
public String getImgUrl(String fileUrl) {
if (!StringUtils.isEmpty(fileUrl)) {
String[] split = fileUrl.split("/");
return this.getUrl(this.filedir + split[split.length - 1]);
}
return null;
}
/**
* 获得url链接
*
* @param key
* @return
*/
public String getUrl(String key) {
// 设置URL过期时间为10年 3600l* 1000*24*365*10
Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
// 生成URL
URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
if (url != null) {
return url.toString();
}
return null;
}
/**
* @return
* @throws IOException
*/
public String ossUpload(InputStream inputStream, String key, String ossImageDomain) throws IOException {
ossClient.putObject(ConstUtil.BUCKETNAME, key, inputStream);
return ossImageDomain + "/" + key;
}
/**
* 返回上传到阿里云的地址
*
* @param imgUrl
* @return
*/
public String getOssSrc(String imgUrl, String imageBridge, String ossImageDomain) {
try {
String url = getDataSrc(imgUrl, imageBridge);//通过跳板下载,防止服务器被封杀
InputStream inputStream = new URL(url).openStream();
return getOssSrc(url, inputStream, ossImageDomain);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
public String getOssSrc(String url, InputStream inputStream, String ossImageDomain) {
String fileExt = url.substring(url.lastIndexOf("."), url.length());
//处理图片格式
fileExt = fileExtString(fileExt);
String key = EncryptUtils.md5(url);//无需扩展名,浏览器能正常加载<img/>
String dPath = "";
Calendar a = Calendar.getInstance();
dPath += String.valueOf(a.get(Calendar.YEAR));
dPath += "/";
dPath += String.valueOf(a.get(Calendar.MONTH) + 1);
dPath += "/";
dPath += String.valueOf(a.get(Calendar.DAY_OF_MONTH));
dPath += "/";
String oospath = dPath.substring(0, dPath.length() - 1);
String remoteFilePath = oospath.substring(0, oospath.length()).replaceAll("\\\\", "/") + "/";
String path = filedir + remoteFilePath + key + fileExt;
ossClient.putObject(ConstUtil.BUCKETNAME, path, inputStream);
return ossImageDomain + "/" + path;
}
String fileExtString(String fileExt){
if (fileExt.equalsIgnoreCase(".bmp")) {
return ".bmp";
}
if (fileExt.equalsIgnoreCase(".gif")) {
return ".gif";
}
if (fileExt.equalsIgnoreCase(".jpeg") ||
fileExt.equalsIgnoreCase(".jpg") ||
fileExt.equalsIgnoreCase(".png")) {
return ".jpeg";
}
if (fileExt.equalsIgnoreCase(".html")) {
return ".html";
}
if (fileExt.equalsIgnoreCase(".txt")) {
return ".plain";
}
if (fileExt.equalsIgnoreCase(".vsd")) {
return ".vnd.visio";
}
if (fileExt.equalsIgnoreCase(".pptx") ||
fileExt.equalsIgnoreCase(".ppt")) {
return ".vnd.ms-powerpoint";
}
if (fileExt.equalsIgnoreCase(".docx") ||
fileExt.equalsIgnoreCase(".doc")) {
return ".msword";
}
if (fileExt.equalsIgnoreCase(".xml")) {
return ".xml";
}
if (fileExt.equalsIgnoreCase(".pdf")) {
return ".pdf";
}
return ".jpeg";
}
/**
* 返回被跳板服务器处理过的地址
*
* @param imgUrl
* @return
*/
public String getDataSrc(String imgUrl, String imageBridge) {
if (imageBridge != null && !"".equals(imageBridge)) {
if (imgUrl != null) {
try {
return imageBridge + URLEncoder.encode(imgUrl, "utf-8");
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage(), e);
}
}
}
return imgUrl;
}
/**
* 上传图片
*/
public String uploadImg2OssImageShear(MultipartFile file, Integer imageHeightValue, Integer imageWidthValue, String dirName, String dirkName, String ossImageDomain) {
//获取文件名字
String originalFilename = file.getOriginalFilename();
//文件后缀格式
String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
//根据时间给文件一个新的名字
SimpleDateFormat dt = new SimpleDateFormat("yyyyMMddHH");
//图片上级文件夹
String path = dt.format(new Date());
//图片名称
SimpleDateFormat dh = new SimpleDateFormat("yyyyMMddHHmmss");
String newname = dh.format(new Date());
String newImgName = newname + "_"
+ new Random().nextInt(1000) + substring;
filedir = filedir + dirName + "/" + dirkName + "/" + path + "/";//图片存储路径
try {
//将文件流化再压缩
InputStream inputStream = file.getInputStream();
Image bi = ImageIO.read(inputStream);//读取文件流写成图片
int srcHeight = bi.getHeight(null); //原图片宽度
int srcWidth = bi.getWidth(null);
if(srcHeight<imageHeightValue){
return "error图片高度:"+srcHeight+",小于标准:"+imageHeightValue;
}
if(srcWidth<imageWidthValue){
return "error图片宽度:"+srcWidth+",小于标准:"+imageWidthValue;
}
inputStream = ImageUtil.PictureCompressionAndClipping(bi,imageHeightValue,imageWidthValue,substring.substring(1, substring.length()));
String urlname = this.ossUpload(inputStream, filedir + newImgName, ossImageDomain);
return urlname;
} catch (Exception e) {
logger.error(e.getMessage(), e);
return "error图片上传失败";
}
}
}
/**
* Created by xuzhen on 4/8/19.
*/
public class ImageUtil {
/**
* 压缩和剪切
*
* @param bi 图片
* @param imageHeightValue 压缩高度
* @param imageWidthValue 压缩宽度
* @param format 文件格式
* @return
*/
public static InputStream PictureCompressionAndClipping(Image bi, Integer imageHeightValue, Integer imageWidthValue, String format) throws IOException {
int srcHeight = bi.getHeight(null); //原图片宽度
int srcWidth = bi.getWidth(null);
ByteArrayOutputStream os = new ByteArrayOutputStream();
BufferedImage tag = null;
if (srcWidth > srcHeight) {
tag = PictureCompressionAndClippingHeight(bi, imageHeightValue, imageWidthValue);
} else {
tag = PictureCompressionAndClippingWidth(bi, imageHeightValue, imageWidthValue);
}
ImageIO.write(tag, format, os);
//用文件流再次读取图片
InputStream inputStream = new ByteArrayInputStream(os.toByteArray());
return inputStream;
}
/**
* 裁剪图片方法
*
* @param bufferedImage 图像源
* @param startX 裁剪开始x坐标
* @param startY 裁剪开始y坐标
* @param endX 裁剪结束x坐标
* @param endY 裁剪结束y坐标
* @return
*/
public static BufferedImage cropImage(BufferedImage bufferedImage, int startX, int startY, int endX, int endY) {
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
if (startX == -1) {
startX = 0;
}
if (startY == -1) {
startY = 0;
}
if (endX == -1) {
endX = width - 1;
}
if (endY == -1) {
endY = height - 1;
}
BufferedImage result = new BufferedImage(endX - startX, endY - startY, 4);
for (int x = startX; x < endX; ++x) {
for (int y = startY; y < endY; ++y) {
int rgb = bufferedImage.getRGB(x, y);
result.setRGB(x - startX, y - startY, rgb);
}
}
return result;
}
/**
* 根据宽度缩放
*
* @param bi
* @param imageHeightValue
* @param imageWidthValue
* @return
*/
public static BufferedImage PictureCompressionAndClippingWidth(Image bi, Integer imageHeightValue, Integer imageWidthValue) {
int srcHeight = bi.getHeight(null);
int srcWidth = bi.getWidth(null);
BufferedImage tag = null;
if (srcWidth > imageWidthValue) {
double jishu = (double) srcWidth / (double) imageWidthValue;
double heightValue = bi.getHeight(null);
heightValue = heightValue / jishu;
if (heightValue < imageHeightValue) {
return PictureCompressionAndClippingHeight(bi, imageHeightValue, imageWidthValue);
}
Double heightValuedouble = new Double(heightValue);
int heightValueInt = heightValuedouble.intValue();
tag = new BufferedImage(Integer.valueOf(imageWidthValue), heightValueInt, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(bi.getScaledInstance(Integer.valueOf(imageWidthValue), heightValueInt, Image.SCALE_SMOOTH), 0, 0, null);
if (heightValue > imageHeightValue) {
tag = cropImage(tag, 0, (heightValueInt - imageHeightValue) / 2, imageWidthValue, heightValueInt - ((heightValueInt - imageHeightValue) / 2));
}
} else {
tag = new BufferedImage(srcWidth, srcHeight, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_SMOOTH), 0, 0, null);
if (srcHeight > imageHeightValue) {
tag = cropImage(tag, 0, (srcHeight - imageHeightValue) / 2, srcWidth, srcHeight - ((srcHeight - imageHeightValue) / 2));
}
}
return tag;
}
/**
* 根据高度缩放
*
* @param bi
* @param imageHeightValue
* @param imageWidthValue
* @return
*/
public static BufferedImage PictureCompressionAndClippingHeight(Image bi, Integer imageHeightValue, Integer imageWidthValue) {
int srcHeight = bi.getHeight(null);
int srcWidth = bi.getWidth(null);
BufferedImage tag = null;
if (srcHeight > imageHeightValue) {
double jishu = (double) srcHeight / (double) imageHeightValue;
double widthValue = bi.getWidth(null);
widthValue = widthValue / jishu;
if (widthValue < imageWidthValue) {
return PictureCompressionAndClippingWidth(bi, imageHeightValue, imageWidthValue);
}
Double widthValuedouble = new Double(widthValue);
int widthValueInt = widthValuedouble.intValue();
tag = new BufferedImage(Integer.valueOf(widthValueInt), imageHeightValue, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(bi.getScaledInstance(Integer.valueOf(widthValueInt), imageHeightValue, Image.SCALE_SMOOTH), 0, 0, null);
if (widthValue > imageWidthValue) {
tag = cropImage(tag, (widthValueInt - imageWidthValue) / 2, 0, widthValueInt - ((widthValueInt - imageWidthValue) / 2), imageHeightValue);
}
} else {
tag = new BufferedImage(srcWidth, srcHeight, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_SMOOTH), 0, 0, null);
if (srcWidth > imageWidthValue) {
tag = cropImage(tag, (srcWidth - imageWidthValue) / 2, 0, srcWidth - ((srcWidth - imageWidthValue) / 2), srcHeight);
}
}
return tag;
}
public static InputStream MassCompression(InputStream inputStream, Image bi, Integer RegulationsWidth, Integer RegulationsHeight) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//原图片宽高
Integer width = bi.getWidth(null);
Integer height = bi.getHeight(null);
//宽度比例
//Double widthBi = width.doubleValue() / RegulationsWidth.doubleValue();
//高度比例
//Double heightBi = height.doubleValue() / RegulationsHeight.doubleValue();
//原图宽高比例
Double oldImageBi = width.doubleValue() / height.doubleValue();
//需求图片宽高比例
Double newImageBi = RegulationsWidth.doubleValue() / RegulationsHeight.doubleValue();
if (oldImageBi > newImageBi) {
//宽度比高度比例要大,证明是宽图 裁减宽度 再压缩
Thumbnails.of(inputStream)
.sourceRegion(Positions.CENTER, (int) (height * newImageBi), height) //裁减
.scale(RegulationsHeight.doubleValue() / height.doubleValue())
.outputQuality(0.8f) //质量压缩80%
.toOutputStream(outputStream);
} else {
Thumbnails.of(inputStream)
.sourceRegion(Positions.CENTER, width, (int) (width / newImageBi)) //裁减
.scale(RegulationsWidth.doubleValue() / width.doubleValue())
.outputQuality(0.8f) //质量压缩80%
.toOutputStream(outputStream);
}
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
return byteArrayInputStream;
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return null;
}
public static InputStream outputQuality(InputStream inputStream, Image bi) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Thumbnails.of(inputStream)
.size(bi.getWidth(null), bi.getHeight(null))
.outputQuality(0.5f) //质量压缩80%
.toOutputStream(outputStream);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
return byteArrayInputStream;
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return null;
}
}
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
```