阿里云

教程中心

     

阿里云  > 教程中心  > java

ImageIO.read 方法报javax.imageio.IIOException: Unsupported Image Type

发布时间:2018-04-09 来源:网络 上传者:用户

ImageIO IIOException Unsupported 方法 image javax type read

java在对图片处理时,使用ImageIO.read方法有时报javax.imageio.IIOException: Unsupported Image Type错,上网查发现是图片类型的问题,图片不是RGB 格式而是CMYK格式,网上说图片在进过ps软件处理后,默认是CMYK格式的。网上好多使用代码转换的程序有问题,最后看到一篇文章说http://dsmart-30buy.iteye.com/blog/1226969


找到解决方法:


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);
}

以上是ImageIO.read 方法报javax.imageio.IIOException: Unsupported Image Type的内容,更多 ImageIO IIOException Unsupported 方法 image javax type read 的内容,请您使用搜索功能获取相关信息。
< 1 / 6 >
本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果你发现本社区中有涉嫌抄袭的内容,欢迎发送邮件至:zixun-group@service.aliyun.com 进行举报,并提供相关证据,工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。