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

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>
        
        ```
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值