阿里云OSS服务转储缩略图

一、需求

APP后台服务单独搭建文件服务器,选择了阿里云的OSS对象存储,某些功能模块中,对图片的存储是私有读写的,即不能通过域名+路径直接访问,在图片列表中,考虑到APP流畅性以及带宽费率问题,需要显示缩略图提升流畅性以及快速加载。所以,上传原图后(私有读写),自动转储一份缩略图(公共读,私有写),可通过域名+路径直接访问。

二、实现

package com.guangjutx.modules.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.GenericResult;
import com.aliyun.oss.model.ProcessObjectRequest;
import com.guangjutx.common.util.DateUtil;
import org.apache.commons.lang3.time.DateUtils;

import java.io.IOException;
import java.util.Date;
import java.util.Formatter;
import java.util.UUID;

/**
 * Created by 丁文浩 on 2019/8/15.
 * 阿里云OSS图片转储缩略图工具类
 */
public class OssUtils {

    /**
     * 域名(阿里云OSS控制台找到地区对应的域名)
     */
    private final static String OSS_END_POINT = "oss-cn-shenzhen.aliyuncs.com";

    /**
     * 账号(阿里云主账号生成的子账号密码)
     */
    private final static String OSS_ACCESS_KEY_ID = "xxxxxx";

    /**
     * 密匙
     */
    private final static String OSS_ACCESS_KEY_SECRET = "xxxxxxxxxxxxxxx";

    /**
     * 存储空间(默认存储空间)
     */
    private final static String OSS_BUCKET_NAME = "bucketName";

    private volatile static OSS instance = null;

    private OssUtils() {}

    /**
     * Oss 实例化
     * @return
     */
    private static OSS getOssClient() {
        if(instance == null) {
            synchronized (OssUtil.class){
                if(instance == null){
                    instance = new OSSClientBuilder().build(OSS_END_POINT, OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET);
                }
            }
        }
        return instance;
    }

    /**
     * 过期时间(小时)
     * @param hours
     * @return
     */
    public static Date getExpiration(int hours){
        return DateUtils.addHours(new Date(), hours);
    }

    /**
     * 根据源文件生成缩略图路径(唯一路径,重复则会覆盖)
     * @param sourceImage
     * @return
     */
    public static String getThumbnailPath(String sourceImage){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("thumbnail/");//主文件夹
        stringBuilder.append(DateUtil.getDate("yyyyMM"));//子文件夹
        stringBuilder.append("/");
        stringBuilder.append(UUID.randomUUID().toString().replaceAll("-",""));//生成唯一文件名
        stringBuilder.append(sourceImage.substring(sourceImage.lastIndexOf(".")));
        return stringBuilder.toString();
    }

    /**
     *  阿里云转储缩略图(图片格式只能是:jpg、png、bmp、gif、webp、tiff)
     * @param targetBucketName  目标bucketName(公共读,私有写)
     * @param sourceBucketName  源文件bucketName(私有读写)
     * @param sourceImage       源文件路径(需要生成缩略图的源文件路径)
     * @return 缩略图路径
     * @throws IOException
     */
    public static String dumpThumbnail(String targetBucketName,String sourceBucketName,String sourceImage)throws IOException{
        OSS ossClient = getOssClient();
        // 图片处理持久化 : 缩放
        StringBuilder sbStyle = new StringBuilder();
        Formatter styleFormatter = new Formatter(sbStyle);
        String styleType = "image/resize,m_fixed,w_150,h_150";
        String targetImage = getThumbnailPath(sourceImage);
        styleFormatter.format("%s|sys/saveas,o_%s,b_%s", styleType,
                BinaryUtil.toBase64String(targetImage.getBytes()),
                BinaryUtil.toBase64String(targetBucketName.getBytes()));
        System.out.println(sbStyle.toString());//输设置后的出样式
        ProcessObjectRequest request = new ProcessObjectRequest(sourceBucketName, sourceImage, sbStyle.toString());
        GenericResult processResult = ossClient.processObject(request);
        String json = IOUtils.readStreamAsString(processResult.getResponse().getContent(), "UTF-8");
        processResult.getResponse().getContent().close();
        System.out.println(json);   //输出相应结果,可根据结果做出对应的操作
        return targetImage;
    }

    /**
     * 测试
     * @param args
     * @throws IOException
     */
    public static void main(String[] args)throws IOException{
        //targetBucketName:缩略图转储到的位置(即目标存储空间)
        //sourceBucketName:原图存储空间
        //sourceImage     :原图路径(sourceBucketName+sourceImage:构成原图访问路径)
        String thumbnailPath =  dumpThumbnail("targetBucketName","sourceBucketName","0f04af422502a40b6c8dc19d53d1f348.jpg");
        System.out.println(thumbnailPath);
    }


}

响应结果:

阿里云OSS服务转储缩略图_第1张图片

你可能感兴趣的:(Java)