功能:app应用图片上传
功能说明:app应用上传图片,服务端接口处理上传的图片并保存至阿里云OSS。据同事提出,由于用户手机系统不同,有部分情况下上传的照片会存在旋转角度,此时要判断并保存正常角度的图片。
提示:相关方法可在本文末尾查找,如:encodeImgageToBase64() , uploadToAliYunOSS()。。。
方法一:若存储在本地服务器,利用 Thumbnails.jar 代码如下:
public static void main(String[] args) throws Exception {
String path = "图片路径";
File file = new File(path);
String imgBase64 = encodeImgageToBase64(file);
byte[] bytes = Base64.decodeBase64(imgBase64);
InputStream input = new ByteArrayInputStream(bytes);
BufferedImage old_img = ImageIO.read(input);
int w = old_img.getWidth();
int h = old_img.getHeight();
double angle = 90;//旋转角度,正数为顺时针旋转,负数逆时针旋转
Thumbnails.of(old_img).size(w , h).rotate(angle).toFile(new File("保存目录" + System.currentTimeMillis() + ".jpg"));
}
方法二:存储到阿里云OSS(注:uploadToAliYunOSS方法,末尾提供一个参考。详情见阿里云对象存储OSS_SDK手册_JAVA-SDK上传文件:https://help.aliyun.com/document_detail/32013.html?spm=5176.doc31986.6.288.BUSv4Z)
坑一:用方法一中的步骤,图片上传成功,新图高宽正常,但图片底色有变化,
原因:Thumbnails类的apply()方法中,BufferedImage的定义为:
BufferedImage newImage = new BufferedImageBuilder(newWidth, newHeight).build();
个人理解为:由于,图片是有base64编码而来,定义新图片时底色有所丢失,转而重新定义为(具体详见于末尾rotateImg()方法):
BufferedImage new_img = new BufferedImageBuilder(newWidth, newHeight , BufferedImage.TYPE_INT_BGR).build();
测试代码如下:
public static void main(String[] args) throws Exception {
String path = "图片路径"