分享一个上传图片,图片压缩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 ...
随机推荐
- webpack 处理CSS
1.安装插件 npm i style-loader css-loader --save-dev npm i postcss-loader --save-dev npm i autoprefixer - ...
- EXCEL 列与列怎么交换?
选中A列数据,按先SHIFT键的同时按住鼠标左键,向右拖动鼠标,在拖动的过程中,会出现一条虚线,当拖动到B列的右边缘时,屏幕上会出现 C:C 的提示,这时送开SHIFT键及鼠标左键,就完成了A B两列 ...
- 在命令行上 使用 mutt, fetchmail, maildrop, msmtp 收发邮件
基于shell 现在已经有了 Mail.app, Thunderbird, Outlook 这些图形化工具能很方便的处理邮件,为啥还需要 mutt 这种命令行文本方式的邮件工具呢?mutt 的一个优势 ...
- Unix 网络编程 读书笔记1
第一章: C/C++语言提供两种不同的编程模式:IPL32和PL64.► IPL32 ● 表示integer/pointer/long三种数据类型是32位(4个字节),在这种模式下,提供32位的地址空 ...
- Linux 系统sudo命令
Linux系统中有许多的系统命令和服务为了安全性考虑,因此只有root超级用户才可以去使用.如果普通用户需要做此类操作,则可以使用su - 命令(减号(-)指完全切换到新的用户,即把环境变量信息也变更 ...
- Spring mvc中@RequestMapping 6个基本用法小结
Spring mvc中@RequestMapping 6个基本用法小结 小结下spring mvc中的@RequestMapping的用法. 1)最基本的,方法级别上应用,例如: @RequestMa ...
- 添加space_key, enter_key, clear_key, delete_key的处理。
final EditText view = (EditText) mInflater.inflate(R.layout.sms_receipient_input, null); view.setOnK ...
- cxf之Exception in thread "main" java.lang.NoSuchMethodError: org.apache.cxf.jaxrs.provider.ProviderFactory.<init>(Lorg/apache/cxf/Bus;)V
pom.xml中关于cxf的配置jar包冲突??? 1.http://blog.csdn.net/yzl_8877/article/details/53216923 2.https://www.cnb ...
- RCF库ClientStub.setAutoReconnect
这个选项为false时,当连接断开时,第一次调用服务会抛出异常,而第二次调用时,也会自动连接.
- 采用异步来实现重新连接服务器或者重新启动服务 C#中类的属性的获取 SignalR2简易数据看板演示 C#动态调用泛型类、泛型方法 asp .net core Get raw request. 从壹开始前后端分离[.NetCore 不定期更新] 38 ║自动初始化数据库
采用异步来实现重新连接服务器或者重新启动服务 开启异步监听,不会导致主线程的堵塞,在服务异常断开后一直检测重新连接服务,成功连接服务后通知各个注册的客户端! #region 检测断线并重连OPC服务 ...