我可以通过BufferedImage读取InputStream吗?

时间:2012-11-04 10:25:05

标签: java image inputstream bufferedimage javax.imageio

InputStream bais = new ByteArrayInputStream(b);
BufferedImage bImageFromConvert = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = bImageFromConvert.createGraphics();
g = cvrimg.getGraphics();
g.drawImage(bImageFromConvert, width, height, null);
ImageIO.write(bImageFromConvert, "png", new File("D:\\new.png"));

我收到以下异常: java.lang.IllegalArgumentException: im == null!

我该怎么办?

这是示例代码:

BufferedImage cvrimg = ImageIO.read(file);
int height = cvrimg.getHeight();
int width = cvrimg.getWidth();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(new_img, "jpg", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
byte[] b = new byte[imageInByte.length];
b[i] = fromUnsignedInt(b2);
InputStream bais = new ByteArrayInputStream(b);
BufferedImage bImageFromConvert = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

// int inBytes = bais.available();

Graphics g = bImageFromConvert.createGraphics();
g = cvrimg.getGraphics();
g.drawImage(bImageFromConvert, width, height, null);
bImageFromConvert=ImageIO.read(bais);
ImageIO.write(bImageFromConvert, "png", new File("D:\\new.png"));

1 个答案:

答案 0 :(得分:1)

您正在获取异常,因为您没有读取输入流。使用

BufferedImage im = ImageIO.read(bais);

代码中的一个简单转换器,它读取jpg文件并写入png文件。

BufferedImage cvrimg = ImageIO.read(new File("/path/to/images/old.jpg"));
int height = cvrimg.getHeight();
int width = cvrimg.getWidth();
BufferedImage bImageFromConvert = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bImageFromConvert.createGraphics();
g.drawRenderedImage(cvrimg, null);
ImageIO.write(bImageFromConvert, "png", new File("/path/to/images/new.png"));