1. 程式人生 > >分享一個上傳圖片,圖片壓縮Unsupported Image Type解決方案

分享一個上傳圖片,圖片壓縮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.slf
4j.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

參考文獻