1.前言
前面两节我们跟新了图片上传的前端知识。没看的小伙伴可以返回去看看。
图片上传及图片处理—–前端技术栈
图片上传及图片处理—–5+runtime技术栈
现在,我们要做的就是后端服务器处理图片。
一般来说,对于一张图片。他可能在手机端,平板电脑端以及pc端进行展示。有可能以列表形式展示,也有可能以详情图展示,对于不同的展示方式。我们应该给与不同大小的图片进行展示。这样做,有以下几个好处。
- 提高传输效率
- 节省用户流量
- 减轻客户端渲染的压力(对于手机端,如果全是几百kb以上的图片。在低端安卓机上。真的卡的不行)
基于以上几点,我们可以按照用途把图片划分为以下几个尺寸(本节主要将等宽比例压缩,当然你也可以试试其他的)
- 宽度250(20kb左右)——适用于手机横向展示2张以上的图片(比如列表展示)
- 宽度550(60kb左右)——适用于手机横向单图、平板电脑端横向2图、pc端横向4图
- 宽度1000(150kb左右)——适用于手机图片单张详情预览、平板横向单张展示、平板图片详情、pc端图片详情
- 宽度2000(350kb左右)——适用于平板电脑单张详情(不常用)、pc端巨幕<该类为了增加上传速度可单独用作判断>
- 原图——适用于对图片质量要求很高的摄影绘画等等的下载<不常用,平台无原图下载功能建议不用>
基于这样的构思我们来构思实现代码逻辑
- 拿到前端传过来的文件
- 如果图片大小满足压缩按照比例压缩图片
- 获取压缩图片的输出流
- 输出到本地路径或者远程服务器
废话不多说了,就这个逻辑。上代码。
- 从file中按照250,550,1000,2000,原图五个方式获得输出流
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class CompressUtils {
private static Logger log = LoggerFactory.getLogger(CompressUtils.class);
/**
* 获取宽250返回流(手机列表图)
* @param file
* @return
*/
public static InputStream getMinInputStream(MultipartFile file){
if (file == null) {
log.error("文件不能为空:CompressUtils.getMinInputStream");
return null;
}
return handPicture(file,250);
}
/**
* 获取宽550返回流(手机详情图)
* @param file
* @return
*/
public static InputStream getMiddleInputStream(MultipartFile file){
if (file == null) {
log.error("文件不能为空:CompressUtils.getMiddleInputStream");
return null;
}
return handPicture(file,550);
}
/**
* 获取宽1000返回流(pad详情图)
* @param file
* @return
*/
public static InputStream getMaxInputStream(MultipartFile file){
if (file == null) {
log.error("文件不能为空:CompressUtils.getMaxInputStream");
return null;
}
return handPicture(file,1000);
}
/**
* 获取宽2000返回流(pc详情图)
* @param file
* @return
*/
public static InputStream getSupperInputStream(MultipartFile file){
if (file == null) {
log.error("文件不能为空:CompressUtils.getSupperInputStream");
return null;
}
return handPicture(file,2000);
}
/**
* 获取原图返回流
* @param file
* @return
*/
public static InputStream getOrginInputStream(MultipartFile file){
if (file == null) {
log.error("文件不能为空:CompressUtils.getOrginInputStream");
return null;
}
try {
return getPictureInputStream(ImageIO.read(file.getInputStream()),0,0);
} catch (IOException e) {
log.error("文件io异常:CompressUtils.getOrginInputStream");
return null;
}
}
private static InputStream handPicture(MultipartFile file,Integer width){
try {
InputStream inputStream = file.getInputStream();
BufferedImage bufImg=ImageIO.read(inputStream);
Integer w = bufImg.getWidth(null);
if(width>w) return getPictureInputStream(bufImg,0,0);
return getPictureInputStream(bufImg,width,0);
} catch (IOException e) {
log.error("文件io异常:CompressUtils.handPicture");
return null;
}
}
private static InputStream getPictureInputStream(BufferedImage bufImg, int width, int height) {
try {
Integer w = bufImg.getWidth(null);
Integer h = bufImg.getHeight(null);
double bili;
if(width>0){
bili=width/(double)w;
height = (int) (h*bili);
}else{
if(height>0){
bili=height/(double)h;
width = (int) (w*bili);
}else{
height=h;
width =w;
}
}
// 获得缓存流
BufferedImage newBufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
newBufferedImage .getGraphics().drawImage(bufImg.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
// 指定写图片的方式为 jpg
ImageWriter imgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
ImageWriteParam imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
// 获取流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
imgWriter.reset();
imgWriter.setOutput(ImageIO.createImageOutputStream(bos));
imgWriter.write(null, new IIOImage(newBufferedImage, null, null), imgWriteParams);
// 转换为输出流
InputStream inputStream = new ByteArrayInputStream(bos.toByteArray());
inputStream.close();
return new ByteArrayInputStream(bos.toByteArray());
} catch (IOException e) {
log.error("图片压缩io异常:CompressUtils.getPictureInputStream<==>"+e.getMessage());
return null;
}
}
}
- 使用传统方法将图片写在本地
/**
* 将InputStream写入本地文件
* @param input 输入流
* @throws IOException
*/
private static String writeToLocal(String destination,InputStream input) throws IOException {
int index;
byte[] bytes = new byte[1024];
FileOutputStream downloadFile = new FileOutputStream(destination);
while ((index = input.read(bytes)) != -1) {
downloadFile.write(bytes, 0, index);
downloadFile.flush();
}
downloadFile.close();
input.close();
}
/**
* web服务器保存图片路径
*/
public static String createPath(){
String minUrl= UUID.randomUUID().toString().replace("-","");
Calendar cale = Calendar.getInstance();
int year =cale.get(Calendar.YEAR);
int month = cale.get(Calendar.MONTH) + 1;
int day = cale.get(Calendar.DATE);
String pname=year+"y"+month+"/"+day+"/"+minUrl+".jpg";
String path ="/pictures/"+ pname
return path;
}
public static void main(String[] args) {
// 乱写的后期来源于前端文件
MultipartFile file =new MultipartFile ();
// 1.路径写死
String minUrl= UUID.randomUUID().toString().replace("-","");
writeToLocal("E/ehu/src/main/java/resource/pictures/"+minUrl+".jpg",getOrginInputStream(file));
// 2.使用相对路径
String path =createPath();
writeToLocal(request.getContextPath()+path,getOrginInputStream(file));
}
其中 input 用第一个方法获得。destination一般采用配置文件路径+UUID自动生成+”.jpg”后缀。
如上所示main文件写好后,destination为写死的。这样做,读取文件可能麻烦一些。我们可以使用获取项目资源文件路径,从而把图片写在资源文件夹+按照年+月份分第一层包+按照日期分第二层包+文件名称。具体方式见上面代码createPath()方法。这样在前端获取图片文件资源的时候。只需要加上服务器ip+项目端口号(默认80,可不写)+项目名称(一般配置为省略)+createPath()即可
- 使用三方对象存储服务
当前三方比较流行的有阿里云对象存储,七牛云对象存储,腾讯云对象存储等。他们可用于存任何的文件(我其实一直在考虑要不要用来开辟一块自己的网盘)。该代码借用人人开源代码集成做了一些修改。大致步骤有以下几个。
- 写配置类加载配置
- 工厂方法调用上传调用
- 在pom中引入三方jar包
<properties>
<qiniu-version>[7.2.0, 7.2.99]</qiniu-version>
<aliyun-oss-version>2.5.0</aliyun-oss-version>
<qcloud-cos-version>4.4</qcloud-cos-version>
</properties>
<dependencies>
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>${qiniu-version}</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>${aliyun-oss-version}</version>
</dependency>
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>${qcloud-cos-version}</version>
</dependency>
</dependencies>
分别集成阿里云,七牛云,以及腾讯云
阿里云存储服务
import com.aliyun.oss.OSSClient;
import com.hannan.ehu.common.exception.RRException;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
/**
* 阿里云存储
*/
public class AliyunCloudStorageService extends CloudStorageService {
private OSSClient client;
public AliyunCloudStorageService(CloudStorageConfig config){
this.config = config;
//初始化
init();
}
private void init(){
client = new OSSClient(config.getAliyunEndPoint(), config.getAliyunAccessKeyId(),
config.getAliyunAccessKeySecret());
}
@Override
public String upload(byte[] data, String path) {
return upload(new ByteArrayInputStream(data), path);
}
@Override
public String upload(InputStream inputStream, String path) {
try {
client.putObject(config.getAliyunBucketName(), path, inputStream);
} catch (Exception e){
throw new RRException("上传文件失败,请检查配置信息", e);
}
return config.getAliyunDomain() + "/" + path;
}
@Override
public String uploadSuffix(byte[] data, String suffix) {
return upload(data, getPath(config.getAliyunPrefix(), suffix));
}
@Override
public String uploadSuffix(InputStream inputStream, String suffix) {
return upload(inputStream, getPath(config.getAliyunPrefix(), suffix));
}
}
腾讯云存储服务
import com.hannan.ehu.common.exception.RRException;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.request.UploadFileRequest;
import com.qcloud.cos.sign.Credentials;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
/**
* 腾讯云存储
*/
public class QcloudCloudStorageService extends CloudStorageService {
private COSClient client;
public QcloudCloudStorageService(CloudStorageConfig config){
this.config = config;
//初始化
init();
}
private void init(){
Credentials credentials = new Credentials(config.getQcloudAppId(), config.getQcloudSecretId(),
config.getQcloudSecretKey());
//初始化客户端配置
ClientConfig clientConfig = new ClientConfig();
//设置bucket所在的区域,华南:gz 华北:tj 华东:sh
clientConfig.setRegion(config.getQcloudRegion());
client = new COSClient(clientConfig, credentials);
}
@Override
public String upload(byte[] data, String path) {
//腾讯云必需要以"/"开头
if(!path.startsWith("/")) {
path = "/" + path;
}
//上传到腾讯云
UploadFileRequest request = new UploadFileRequest(config.getQcloudBucketName(), path, data);
String response = client.uploadFile(request);
JSONObject jsonObject = JSONObject.fromObject(response);
if(jsonObject.getInt("code") != 0) {
throw new RRException("文件上传失败," + jsonObject.getString("message"));
}
return config.getQcloudDomain() + path;
}
@Override
public String upload(InputStream inputStream, String path) {
try {
byte[] data = IOUtils.toByteArray(inputStream);
return this.upload(data, path);
} catch (IOException e) {
throw new RRException("上传文件失败", e);
}
}
@Override
public String uploadSuffix(byte[] data, String suffix) {
return upload(data, getPath(config.getQcloudPrefix(), suffix));
}
@Override
public String uploadSuffix(InputStream inputStream, String suffix) {
return upload(inputStream, getPath(config.getQcloudPrefix(), suffix));
}
}
七牛云存储
import com.hannan.ehu.common.exception.RRException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
/**
* 七牛云存储
*/
public class QiniuCloudStorageService extends CloudStorageService {
private UploadManager uploadManager;
private String token;
public QiniuCloudStorageService(CloudStorageConfig config){
this.config = config;
//初始化
init();
}
private void init(){
uploadManager = new UploadManager(new Configuration(Zone.autoZone()));
token = Auth.create(config.getQiniuAccessKey(), config.getQiniuSecretKey()).
uploadToken(config.getQiniuBucketName());
}
@Override
public String upload(byte[] data, String path) {
try {
Response res = uploadManager.put(data, path, token);
if (!res.isOK()) {
throw new RuntimeException("上传七牛出错:" + res.toString());
}
} catch (Exception e) {
throw new RRException("上传文件失败,请核对七牛配置信息", e);
}
return config.getQiniuDomain() + "/" + path;
}
@Override
public String upload(InputStream inputStream, String path) {
try {
byte[] data = IOUtils.toByteArray(inputStream);
return this.upload(data, path);
} catch (IOException e) {
throw new RRException("上传文件失败", e);
}
}
@Override
public String uploadSuffix(byte[] data, String suffix) {
return upload(data, getPath(config.getQiniuPrefix(), suffix));
}
@Override
public String uploadSuffix(InputStream inputStream, String suffix) {
return upload(inputStream, getPath(config.getQiniuPrefix(), suffix));
}
}
公共接口服务
import org.apache.commons.lang.StringUtils;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;
/**
* 云存储(支持七牛、阿里云、腾讯云)
*/
public abstract class CloudStorageService {
/** 云存储配置信息 */
CloudStorageConfig config;
/**
* 文件路径
* @param prefix 前缀
* @param suffix 后缀
* @return 返回上传路径
*/
public String getPath(String prefix, String suffix) {
//生成uuid
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//文件路径
String path = DateUtils.format(new Date(), "yyyyMMdd") + "/" + uuid;
if(StringUtils.isNotBlank(prefix)){
path = prefix + "/" + path;
}
return path + suffix;
}
/**
* 文件上传
* @param data 文件字节数组
* @param path 文件路径,包含文件名
* @return 返回http地址
*/
public abstract String upload(byte[] data, String path);
/**
* 文件上传
* @param data 文件字节数组
* @param suffix 后缀
* @return 返回http地址
*/
public abstract String uploadSuffix(byte[] data, String suffix);
/**
* 文件上传
* @param inputStream 字节流
* @param path 文件路径,包含文件名
* @return 返回http地址
*/
public abstract String upload(InputStream inputStream, String path);
/**
* 文件上传
* @param inputStream 字节流
* @param suffix 后缀
* @return 返回http地址
*/
public abstract String uploadSuffix(InputStream inputStream, String suffix);
}
配置类
package com.hannan.ehu.common.cloud;
import lombok.Data;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.Serializable;
/**
* 云存储配置信息
*/
@Component
@Data
public class CloudStorageConfig implements Serializable {
private static final long serialVersionUID = 1L;
//类型 1:七牛 2:阿里云 3:腾讯云
@Range(min=1, max=3, message = "类型错误")
@Value("${cloudStorageConfig.type}")
private Integer type;
//七牛绑定的域名
@Value("${cloudStorageConfig.qiniuDomain}")
private String qiniuDomain;
//七牛路径前缀
@Value("${cloudStorageConfig.qiniuPrefix}")
private String qiniuPrefix;
//七牛ACCESS_KEY
@Value("${cloudStorageConfig.qiniuAccessKey}")
private String qiniuAccessKey;
//七牛SECRET_KEY
@Value("${cloudStorageConfig.qiniuSecretKey}")
private String qiniuSecretKey;
//七牛存储空间名
@Value("${cloudStorageConfig.qiniuBucketName}")
private String qiniuBucketName;
//阿里云绑定的域名
private String aliyunDomain;
//阿里云路径前缀
private String aliyunPrefix;
//阿里云EndPoint
private String aliyunEndPoint;
//阿里云AccessKeyId
private String aliyunAccessKeyId;
//阿里云AccessKeySecret
private String aliyunAccessKeySecret;
//阿里云BucketName
private String aliyunBucketName;
//腾讯云绑定的域名
private String qcloudDomain;
//腾讯云路径前缀
private String qcloudPrefix;
//腾讯云AppId
private Integer qcloudAppId;
//腾讯云SecretId
private String qcloudSecretId;
//腾讯云SecretKey
private String qcloudSecretKey;
//腾讯云BucketName
private String qcloudBucketName;
//腾讯云COS所属地区
private String qcloudRegion;
}
日期工具类
package com.hannan.ehu.common.cloud;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 日期处理
*
* @author chenshun
* @email sunlightcs@gmail.com
* @date 2016年12月21日 下午12:53:33
*/
public class DateUtils {
/** 时间格式(yyyy-MM-dd) */
public final static String DATE_PATTERN = "yyyy-MM-dd";
/** 时间格式(yyyy-MM-dd HH:mm:ss) */
public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
public static String format(Date date) {
return format(date, DATE_PATTERN);
}
public static String format(Date date, String pattern) {
if(date != null){
SimpleDateFormat df = new SimpleDateFormat(pattern);
return df.format(date);
}
return null;
}
}
工厂类
package com.hannan.ehu.common.cloud;
/**
* 文件上传Factory
* @author chenshun
* @email sunlightcs@gmail.com
* @date 2017-03-26 10:18
*/
public final class OSSFactory {
private static Interger QINIU_Cloud = 1;
private static Interger ALIYUN_Cloud = 2;
private static Interger QCLOUD_Cloud = 3;
public static CloudStorageService build(CloudStorageConfig config){
if(config.getType() == QINIU_Cloud ){
return new QiniuCloudStorageService(config);
}else if(config.getType() == ALIYUN_Cloud){
return new AliyunCloudStorageService(config);
}else if(config.getType() == QCLOUD_Cloud){
return new QcloudCloudStorageService(config);
}
return null;
}
}
调用文件上传
@Autowired
private CloudStorageConfig config;
@ApiOperation(value = "上传图片", notes = "code 200 成功,返回所有大小图片的地址")
@PostMapping("/uploadPicture")
public R uploadPicture(@RequestBody MultipartFile file) {
String minUrl=OSSFactory.build(config).uploadSuffix(CompressUtils.getMinInputStream(file),".jpg");
String midUrl =OSSFactory.build(config).uploadSuffix(CompressUtils.getMiddleInputStream(file),".jpg");
String maxUrl =OSSFactory.build(config).uploadSuffix(CompressUtils.getMaxInputStream(file),".jpg");
String supperUrl =OSSFactory.build(config).uploadSuffix(CompressUtils.getSupperInputStream(file),".jpg");
String oriUrl =OSSFactory.build(config).uploadSuffix(CompressUtils.getOrginInputStream(file),".jpg");
return R.ok(oriUrl).put("maxUrl",maxUrl).put("midUrl",midUrl).put("minUrl",minUrl).put("supperUrl",supperUrl);
}
到此三方上传完结。
附上配置文件获取链接
七牛云注册并获取配置
阿里云对象存储服务开通
腾讯云对象云存储开通