javax.imageio.IIOException: Unsupported Image Type異常,解決方法

javax.imageio.IIOException: Unsupported Image Type異常
可以採用如下方案:

public class ImagesUtils {
	public static byte[] compressImage(File file, int ppi) {
		byte[] smallImage = null;
		try {
			BufferedImage bi = ImagesUtils.readImage(file);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			Thumbnails.of(bi).size(ppi, ppi).outputFormat("png").toOutputStream(out);
			smallImage = out.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return smallImage;
 
	}

	public static BufferedImage readImage(File file) throws IOException {
		return readImage(ImageIO.createImageInputStream(file));
	}

	public static BufferedImage readImage(InputStream stream) throws IOException {
		return readImage(ImageIO.createImageInputStream(stream));
	}

	public static BufferedImage readImage(ImageInputStream input) throws IOException {
		Iterator<?> readers = ImageIO.getImageReaders(input);
		if (readers == null || !readers.hasNext()) {
			return null;
		}

		ImageReader reader = (ImageReader) readers.next();
		reader.setInput(input);

		BufferedImage image;
		try {
			// 嘗試讀取圖片 (包括顏色的轉換).
			image = reader.read(0); // RGB

		} catch (IIOException e) {
			// 讀取Raster (沒有顏色的轉換).
			Raster raster = reader.readRaster(0, null);// CMYK
			image = createJPEG4(raster);
		}

		return image;
	}

	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);
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章