分享一个上传图片,图片压缩Unsupported Image Type解决方案
http://blog.csdn.net/frankcheng5143/article/details/53185201
************************************************************************
文件上传是一个最基本的功能,往往我们需要对图片进行压缩,来加快移动端的加载速度。
SprimgMVC图片上传可以参考SpringMVC传值
从这里开始
System.out.println("文件大小: " + file.getSize());
System.out.println("文件类型: " + file.getContentType());
System.out.println("表单名称: " + file.getName());
System.out.println("文件原名: " + file.getOriginalFilename());
if (!file.getContentType().contains("image")) {
return BaseReturn.response(ErrorCode.FAILURE, "不支持的图片类型:" + file.getContentType());
}
String image = ImageService.saveImage(request, file, uploadPath);
相关依赖
<!-- 图片压缩 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
<!-- cmyk格式图片转换 -->
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-jpeg</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-tiff</artifactId>
<version>3.3</version>
</dependency>
ImageService
package com.jrbac.service; import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException; import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile; import com.jrbac.util.UUIDGenerator; import net.coobird.thumbnailator.Thumbnails; public class ImageService {
private static final Logger logger = LoggerFactory.getLogger(ImageService.class); /**
* @param request
* @param file
* @param uploadPath
* 形如这样的/assets/upload/image/
* @return /assets/upload/image/abc.jpg
* @throws IOException
*/
public static String saveImage(HttpServletRequest request, MultipartFile file, String uploadPath) {
// 如果用的是Tomcat服务器,则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\uploadPath\\文件夹中
// String fileName = file.getOriginalFilename();
// String fileExt[] = fileName.split("\\.");
String ext = file.getContentType().split("\\/")[1];
String newFileName = UUIDGenerator.getUUID() + "." + ext;
String realPath = request.getSession().getServletContext().getRealPath(uploadPath);
String filePathAndName = null;
if (realPath.endsWith(File.separator)) {
filePathAndName = realPath + newFileName;
} else {
filePathAndName = realPath + File.separator + newFileName;
}
logger.info("-----上传的文件:{}-----", filePathAndName);
try {
// 先把文件保存到本地
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, newFileName));
} catch (IOException e1) {
logger.error("-----文件保存到本地发生异常:{}-----", e1.getMessage());
}
int big = 2 * 1024 * 1024; // 2M以上就进行0.6压缩
if (file.getSize() > big) {
thumbnail(filePathAndName, 0.6f);
} else {
thumbnail(filePathAndName, 0.8f);
}
return uploadPath + newFileName;
} private static void thumbnail(String filePathAndName, double size) {
try {
Thumbnails.of(filePathAndName).scale(size).toFile(filePathAndName);
} catch (IOException e) {
logger.error("-----读取图片发生异常:{}-----", e.getMessage());
logger.info("-----尝试cmyk转化-----");
File cmykJPEGFile = new File(filePathAndName);
try {
BufferedImage image = ImageIO.read(cmykJPEGFile);
ImageOutputStream output = ImageIO.createImageOutputStream(cmykJPEGFile);
if (!ImageIO.write(image, "jpg", output)) {
logger.info("-----cmyk转化异常:{}-----");
}
Thumbnails.of(image).scale(0.4f).toFile(filePathAndName);
logger.info("-----cmyk转化成功-----");
} catch (IOException e1) {
logger.info("-----cmyk转化异常:{}-----", e1.getMessage());
}
}
}
}
这里有一点需要解释一下
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, newFileName));
会将图片保存到本地,
这一步没问题
问题会发生在
Thumbnails.of(filePathAndName).scale(size).toFile(filePathAndName);
大部分情况下是不会出问题的,如果
P过的图片保存为jpg格式时,默认的模式是CMYK模式
就会报如下错误
javax.imageio.IIOException: Unsupported Image Type
这里采用https://github.com/haraldk/TwelveMonkeys工具解决
参考文献
分享一个上传图片,图片压缩Unsupported Image Type解决方案的更多相关文章
- Http POST 提交 415错误 Unsupported Media Type 解决方案
1 问题 在调用webapi post 提交时出现 415 Unsupported Media Type 错误 前端代码如下: $.post("/api/student/poststuden ...
- 分享一个延迟加载图片的JS
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...
- 分享一个react 图片上传组件 支持OSS 七牛云
react-uplod-img 是一个基于 React antd组件的图片上传组件 支持oss qiniu等服务端自定义获取签名,批量上传, 预览, 删除, 排序等功能 需要 react 版本大于 v ...
- vuejs开发组件分享之H5图片上传、压缩及拍照旋转的问题处理
一.前言 三年.net开发转前端已经四个月了,前端主要用webpack+vue,由于后端转过来的,前端不够系统,希望分享下开发心得与园友一起学习. 图片的上传之前都是用的插件(ajaxupload), ...
- 分享图片压缩上传demo,可以选择一张或多张图片也可以拍摄照片
2016-08-05更新: 下方的代码是比较OLD的了,是通过js进行图片的剪切 旋转 再生成,效率较低. 后来又整合了一个利用native.js本地接口的压缩代码 ,链接在这 .页面中有详细的说明, ...
- Android webview实现上传图片的效果(图片压缩)
mainactivity代码 package com.bwie.webviewupload; import java.io.ByteArrayInputStream; import java.io.B ...
- 使用ajax上传图片,支持图片即时浏览,支持js图片压缩后上传给服务器
使用ajax上传图片,支持图片即时浏览,支持js图片压缩后上传给服务器 ajax上传主要使用了 var reader = new FileReader() 此方法 js图片压缩主要是利用canvas进 ...
- 上传图片时压缩图片 - 前端(canvas)做法
HTML前端代码: <?php $this->layout('head'); ?> <?php $this->layout('sidebar'); ?> <m ...
- $.ajax通路RESTful Web Service一个错误:Unsupported Media Type
最近项目,使用头版jquery ajax访问背景CXF发布时间rest维修,结果遇到了错误"Unsupported Media Type". 公布的服务java代码例如以下: im ...
随机推荐
- Windows注意目录
win7: c:\windows\tracing%windir%\system32\logfiles\C:\Users\Administrator\AppData\Roaming\softC:\Use ...
- 用Java实现AES加密(坑!)
大坑!使用SecureRandom默认的加密方式即SHA1PRNG生成的密码有误,即使使用相同的password来生成,不同runtime或时刻生成的随机密码也有可能不同,造成的错误为javax.cr ...
- python之函数用法execfile()
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法execfile() #execfile() #说明:用来执行一个文件,相对于双击的效 ...
- java Socket 获取本地主机ip
package cn.itcast.net.p1.ip; import java.net.InetAddress;import java.net.UnknownHostException; publi ...
- Spark GraphX 的数据可视化
概述 Spark GraphX 本身并不提供可视化的支持, 我们通过第三方库 GraphStream 和 Breeze 来实现这一目标 详细 代码下载:http://www.demodashi.com ...
- 微信小程序:input输入框和form表单几种传值和取值方式
1.传值:index下标传值.页面navigator传值 1.index下标 实现方式是:data-index="{{index}}"挖坑及e.currentTarget.data ...
- Falsk-信号
Flask框架中的信号基于blinker,其主要就是让开发者可是在flask请求过程中定制一些用户行为. 安装:pip3 install blinker request_started = _sign ...
- Java compiler level does not match解决方法(转)
本文转自:https://www.cnblogs.com/lauer0246/p/5740572.html#undefined 从别的地方导入一个项目的时候,经常会遇到eclipse/Myeclips ...
- 狄斯奎诺(dijkstra 模板)
/*狄斯奎诺算法(dijkstra)<邻接表> */ #include<stdio.h> #include<string.h> #include<stdlib ...
- enumerate的简单使用
l = [11,22,33,55,"ss","zz"] for i,v in enumerate(l): print(i,v) #打印结果: # 0 11 # ...