public class OSSClientUtil {Logger logger = LoggerFactory.getLogger(OSSClientUtil.class);// endpoint以杭州为例,其它region请按实际情况填写private String endpoint = ConstUtil.ENDPOINT;// accessKeyprivate 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*10Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);// 生成URLURL 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>```

阿里云图片上传 跳板服务器方式 图片压缩裁减质量压缩相关推荐

  1. ios 拍照上传到服务器_ios端浏览器拍照上传到服务器,图片被旋转90度 php 解决方案...

    1.可以通过前端进行解决,本案例通过后端解决的 判断请求的浏览器的ua,如果是ios浏览器则进行90度旋转 重点来了: 必须确保检测的图片是ios设备上传的完整图片,不要在前端压缩过的,因为压缩后的图 ...

  2. PicGo + 阿里云图床上传失败解析

    在图片上传失败的时候,直接去看PicGo的配置文件,上传失败就是你配置哪里有问题,因为服务器不可能出问题,你typora的软件也不可能出问题,出问题的就只有PickGo这个中间配置软件了. 其实就是一 ...

  3. iOS-图片上传(第三方服务器)实现图片的上传和获取

    最简单的实现方式上传图片 //在调用相机中获取图片   [manager POST:naurl parameters:requestParms constructingBodyWithBlock:^( ...

  4. ios java 图片上传到服务器,iOS 图片上传服务器

    最近搞图片上传,折腾了一个星期终于做出来了,网上搜出来的方法几乎都是好几年前的,试了好多都不能用,此次把代码公布出来供大家参考. 注:部分代码是后台写的,此方法没用到第三方库. 1.图片保存到本地同时 ...

  5. 解决网站上传到服务器,图片上传不成功的问题

    解决办法就是: 给上传到的文件夹添加权限:主要就是添加 NetworkService用户的写入权限! 转载于:https://www.cnblogs.com/yougmi/p/4432760.html

  6. 网页上传到服务器时图片无法显示问题

    加粗样式注意相对路径和绝对路径问题,具体内容如下: http://www.xitongzhijia.net/xtjc/20170804/104068.html

  7. 上传文件到服务器打不开,关于软件上传到服务器后出现图片打不开的解决方法...

    在本地做好的课程网站后上传到服务器出现图片.视频等文件无法打开,出现这种问题是由于在本地直接运行mini iis,上传的图片.视频和其他文件都是以根地址存入在数据库,如果把软件上传至服务器后并且以虚拟 ...

  8. C# ASP.NET MVC 图片上传的多种方式(存储至服务器文件夹,阿里云oss)

    图片上传时我们进场用到的一个功能今天将他整理了一下写了个demo希望对大家有用 该demo分为如下 1.上传至至服务器文件夹 2.上传至阿里云oss 3.百度webupload上传图片 效果图如下: ...

  9. Java实现文件上传到服务器(FTP方式)

    Java实现文件上传到服务器(FTP方式) 1,jar包:commons-net-3.3.jar 2,实现代码: //FTP传输到数据库服务器private boolean uploadServerB ...

最新文章

  1. dp,sp,px相互转化
  2. 斯坦福证明神经网络能直接在光学芯片上训练
  3. javaWEB开发中get方式请求的乱码问题解决
  4. php 函数报错,PHP报错函数error_reporting()怎么用?
  5. composer 检查镜像_检查N元树中的镜像
  6. Django中QueryDict的坑
  7. 解决 asp.net 伪静态 IIS设置后 真正的HTML无法显示的问题
  8. 春眠不觉晓,Kubernetes知多少
  9. WPF中如何选择合适的元数据标记?(英文)
  10. 超酷的jQuery百叶窗图片滑块实现教程
  11. 华为交换机初始化_华为交换机初始设置
  12. 成功解决error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>’ and ‘Eigen::Quate
  13. Word中插入手写体签名
  14. PHP内置的MySQL函数总结
  15. 剑三重置版找不到服务器,重制版客户端安装常见问题
  16. Windows phone 8 学习笔记(8) 定位地图导航(转)
  17. 多媒体中控软件开发流程_网络多媒体:视频工作流程提示
  18. 项目经理的权力永动机
  19. 怎么利用米筐量化测试实盘数据?
  20. Ubuntu如何修改键盘和语言

热门文章

  1. python爬取考研成绩什么时候出来_用Python爬取了考研吧1000条帖子,原来他们都在讨论这些...
  2. android 6.1 换字体,换炫字体管家app
  3. 测试经理谈软件测试行业(想学习转行的看收益颇多)
  4. 成功把Ubuntu安装到U盘完整教程!
  5. 数字1转换成0001
  6. 【Minecraft开服教学】使用 MCSM 面板一键搭建我的世界服务器 并使用内网穿透公网远程联机
  7. matlab 生物信息学工具箱,Matlab生物信息学工具箱新增功能
  8. jQuery:模拟购物车
  9. javaWeb(购物车项目)
  10. 为什么我在使用word时。输入空格是点点点