一、打开官网,注册账号,获取秘钥(每个月500张免费)
1.打开官网,注册账号
TinyPNG – Compress WebP, PNG and JPEG images intelligently
2.登录后,点击账号名字,找到如图所示
3.找到API,就看到一串秘钥,后续工具类的API_KEY换成它
二、API手册
三、导入依赖,和配置文件
<dependency><groupId>com.tinify</groupId><artifactId>tinify</artifactId><version>RELEASE</version></dependency>
#oss
oss.endpoint:oss-cn-自己的.com
oss.accessKeyId:自己的
oss.accessKeySecret:自己的
oss.bucketName:自己的
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
四、上传oss工具类
@Configuration
public class AliOssUtil {@Value("${oss.endpoint}")private String endpoint;// accessKey@Value("${oss.accessKeyId}")private String accessKeyId;@Value("${oss.accessKeySecret}")private String accessKeySecret;// 空间@Value("${oss.bucketName}")private String bucketName;private OSS ossClient;//Tinify的API密钥private static String API_KEY = "自己的APIKEY";/*** 初始化*/@PostConstructpublic void init() {ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);}/*** tiny压缩图片后上传到oss** @param file* @return*/public String compressImage1(MultipartFile file) {try {// 设置Tinify的API密钥Tinify.setKey(API_KEY);// 从MultipartFile创建Tinify的Source对象Source source = Tinify.fromBuffer(file.getBytes());// 压缩图片source.toFile(file.getOriginalFilename());// 返回压缩后的图片数据byte[] bytes = Files.readAllBytes(Paths.get(file.getOriginalFilename()));// 上传到ossMultipartFile file1 = convertToMultipartFile(bytes, file.getOriginalFilename());String url = uploadObject2OSS(file1);return url;} catch (Exception e) {e.printStackTrace();return null;}}/*** tiny自定义图片大小后上传到oss** @param file* @return*/public String compressImage2(MultipartFile file) {try {// 设置Tinify的API密钥Tinify.setKey(API_KEY);// 从MultipartFile创建Tinify的Source对象Source source = Tinify.fromBuffer(file.getBytes());// 自定义图片大小Options options = new Options().with("method", "fit").with("width", 100).with("height", 100);Source resized = source.resize(options);resized.toFile(file.getOriginalFilename());// 返回压缩后的图片数据byte[] bytes = Files.readAllBytes(Paths.get(file.getOriginalFilename()));// 上传到ossMultipartFile file1 = convertToMultipartFile(bytes, file.getOriginalFilename());String url = uploadObject2OSS(file1);return url;} catch (Exception e) {e.printStackTrace();return null;}}/*** 向阿里云的OSS存储中存储文件 --file也可以用InputStream替代** @param file 上传文件* @return String 唯一MD5数字签名*/public String uploadObject2OSS(MultipartFile file) {String resultStr = null;try {// 创建上传Object的MetadataObjectMetadata metadata = new ObjectMetadata();metadata.setContentLength(file.getInputStream().available());metadata.setCacheControl("no-cache");metadata.setHeader("Pragma", "no-cache");metadata.setContentEncoding("utf-8");metadata.setContentType(file.getContentType());String fileName = file.getOriginalFilename();String date = new DateTime().toString("yyyy/MM-dd");String filePath = "自定义名字/" + date + "/" + RandomStringUtils.randomNumeric(6) + fileName;PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePath, file.getInputStream(), metadata);ossClient.putObject(putObjectRequest);// 关闭resultStr = "https://" + bucketName + "." + endpoint + "/" + filePath;} catch (Exception e) {e.printStackTrace();System.out.println("上传阿里云OSS服务器异常." + e.getMessage() + e);}return resultStr;}/*** 二进制转为MultipartFile** @param data* @param filename* @return*/public static MultipartFile convertToMultipartFile(byte[] data, String filename) {ByteArrayResource resource = new ByteArrayResource(data) {@Overridepublic String getFilename() {return filename;}};return new MultipartFile() {@Overridepublic String getName() {return filename;}@Overridepublic String getOriginalFilename() {return filename;}@Overridepublic String getContentType() {return MediaType.APPLICATION_OCTET_STREAM_VALUE;}@Overridepublic boolean isEmpty() {return data.length == 0;}@Overridepublic long getSize() {return data.length;}@Overridepublic byte[] getBytes() {return data;}@Overridepublic InputStream getInputStream() {return new ByteArrayInputStream(data);}@Overridepublic void transferTo(File dest) throws IOException, IllegalStateException {new FileOutputStream(dest).write(data);}};}}
五、controller使用工具类
import com.xiaoqiu.gate2.utils.AliOssUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;import javax.annotation.Resource;/*** 上传*/
@RestController
@RequestMapping("/test/upload")
public class UploadController {@Resourceprivate AliOssUtil aliOssUtil;/*** 上传图片** @param file* @return*/@PostMapping("/fileUpload")@ResponseBodypublic String upload(@RequestParam("file") MultipartFile file) {String url = aliOssUtil.compressImage(file);return url;}
}