分享一个上传图片,图片压缩Unsupported Image Type解决方案

文件上传是一个最基本的功能,往往我们需要对图片进行压缩,来加快移动端的加载速度。

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工具解决

参考文献

SpringMVC传值

imageIO异常:Unsupported Image Type, 不支持图像类型

java下cmyk图片读取和转换rgb

https://github.com/haraldk/TwelveMonkeys

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值