ImageIo.read 返回null


一、問題描述

今天收到一個bug就是imageio讀取圖片會返回null,具體如下

但是其他的圖片就沒有問題

二、問題分析

結合百度發現這張圖片原本的后綴並非是jpg,使用notpard++打開就可以發現

好家伙是webp格式的!!!!

WebP是google開發的一種旨在加快圖片加載速度的圖片格式。圖片壓縮體積大約只有JPEG的2/3,並能節省大量的服務器帶寬資源和數據空間。是現代圖像格式,提供了優越的無損和有損壓縮的圖片在網絡上。使用WebP,網站管理員和web開發人員可以創建更小、更豐富的圖像,使網頁更快。

WebP無損的png圖像小26%。WebP有損圖像是25 - 34%小於等效SSIM質量指數可比JPEG圖像

無損WebP支持透明(也稱為alpha通道)的成本只有22%額外的字節。對有損壓縮RGB壓縮情況下是可以接受的,有損WebP還支持透明度,通常提供3×PNG相比較小的文件大小。

但是!!!由於Webp格式推出比較晚, Jdk 內置的圖片編解碼庫對此並不支持。我只需要知道如何把webp格式轉換成jpg或者其他格式就可以了!!!

三、解決問題

1、在百度找到一個api(地址如下)

我是地址
友情建議,最好用0.1.0哪個版本的其他版本試了都有問題~~~~~~

2、由於這個項目並未發布到maven中央倉庫,所以需要手動導入本地jar包.

(1)、maven導包

<dependency> 
  <groupId>com.github.nintha</groupId> 
  <artifactId>webp-imageio-core</artifactId> 
  <version>{versoin}</version> 
  <scope>system</scope> 
  <systemPath>${project.basedir}/libs/webp-imageio-core-{version}.jar</systemPath> 
</dependency>

(2)、gradle導包

dependencies {
  compile fileTree(dir:'src/main/resources/libs',include:['*.jar'])
}

當然了,你想放在自己倉庫中也是無可厚非的

3、上代碼

(1)、Webp編碼

public static void main(String args[]) throws IOException {
  String inputPngPath = "test_pic/test.png";
  String inputJpgPath = "test_pic/test.jpg";
  String outputWebpPath = "test_pic/test_.webp";

  // Obtain an image to encode from somewhere
  BufferedImage image = ImageIO.read(new File(inputJpgPath));

  // Obtain a WebP ImageWriter instance
  ImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();

  // Configure encoding parameters
  WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());
  writeParam.setCompressionMode(WebPWriteParam.MODE_DEFAULT);

  // Configure the output on the ImageWriter
  writer.setOutput(new FileImageOutputStream(new File(outputWebpPath)));

  // Encode
  writer.write(null, new IIOImage(image, null, null), writeParam);
}

(2)、Webp解碼

public static void main(String args[]) throws IOException {
  ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();

  WebPReadParam readParam = new WebPReadParam();
  readParam.setBypassFiltering(true);

  // Configure the input on the ImageReader
  reader.setInput(new FileImageInputStream(new File(webp圖片地址)));

  // Decode the image
  BufferedImage image = reader.read(0, readParam);

  ImageIO.write(image, "jpg", new File(輸出jpg的地址,png什么的也可以));
}

搞完收工!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM