原文鏈接:https://blog.csdn.net/qq_39069924/article/details/103088374
當
File imgFile = new File(path+imgs);
ImageIO.read(imgFile)
讀取的圖片文件的色彩模式為CMYK時就會拋出Unsupported Image Type的異常,一般圖片的色彩模式為CMYK是因為經過了ps修過的圖或者使用ps做的圖。
百度到很多方法就是用ps重新更改圖片,但是再實際項目中不可能讓客戶重新ps一遍圖片
解決方案 1.使用圖片編輯器,重新另存圖片為jpg格式。(不推薦) 2.maven導入 twelvemonkeys <!-- cmyk格式圖片轉換 --> <dependency> <groupId>com.twelvemonkeys.imageio</groupId> <artifactId>imageio-jpeg</artifactId> <version>3.3</version> </dependency> 導入maven之后,不需要加任何代碼,再次運行原有拋異常的代碼,會發現已經可以正常讀取了。
追更--------------------------------------------------------------------------------------
繼上次修改之后,又出現了下述的問題,這個錯誤正是從我上次導的包里面報出的,所以由此可知,和上次修改有關系 ,我就去掉了這個jar包,然后就可以正常讀取,那就又回到了最初的問題,不能讀取印刷模式的圖片
所以處理方法
File imgFile = new File(path+imgs);// 得到文件 Image img2=null; try{ img2= ImageIO.read(imgFile);// 處理RGB模式的圖片 }catch (Exception e){//處理CMYK模式的圖片 ImageInputStream input = ImageIO.createImageInputStream(imgFile); Iterator readers = ImageIO.getImageReaders(input); ImageReader reader = (ImageReader) readers.next(); reader.setInput(input); Raster raster = reader.readRaster(0, null);//CMYK img2 = createJPEG4(raster); } g.drawImage(img2, 2340, 800, 300, 420, null);
private static BufferedImage createJPEG4(Raster raster) { int w = raster.getWidth(); int h = raster.getHeight(); byte[] rgb = new byte[w * h * 3]; //彩色空間轉換 float[] Y = raster.getSamples(0, 0, w, h, 0, (float[]) null); float[] Cb = raster.getSamples(0, 0, w, h, 1, (float[]) null); float[] Cr = raster.getSamples(0, 0, w, h, 2, (float[]) null); float[] K = raster.getSamples(0, 0, w, h, 3, (float[]) null); for (int i = 0, imax = Y.length, base = 0; i < imax; i++, base += 3) { float k = 220 - K[i], y = 255 - Y[i], cb = 255 - Cb[i], cr = 255 - Cr[i]; double val = y + 1.402 * (cr - 128) - k; val = (val - 128) * .65f + 128; rgb[base] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5); val = y - 0.34414 * (cb - 128) - 0.71414 * (cr - 128) - k; val = (val - 128) * .65f + 128; rgb[base + 1] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5); val = y + 1.772 * (cb - 128) - k; val = (val - 128) * .65f + 128; rgb[base + 2] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5); } raster = Raster.createInterleavedRaster(new DataBufferByte(rgb, rgb.length), w, h, w * 3, 3, new int[]{0, 1, 2}, null); ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); ColorModel cm = new ComponentColorModel(cs, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); return new BufferedImage(cm, (WritableRaster) raster, true, null); }