Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

Java: BufferedImage to byte array and back

I see that a number of people have had a similar problem, however I'm yet to try find exactly what I'm looking for.

So, I have a method which reads an input image and converts it to a byte array:

    File imgPath = new File(ImageName);
    BufferedImage bufferedImage = ImageIO.read(imgPath);
    WritableRaster raster = bufferedImage .getRaster();
    DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();

What I now want to do is convert it back into a BufferedImage (I have an application for which I need this functionality). Note that "test" is the byte array.

    BufferedImage img = ImageIO.read(new ByteArrayInputStream(test));
    File outputfile = new File("src/image.jpg");
    ImageIO.write(img,"jpg",outputfile);

However, this returns the following exception:

    Exception in thread "main" java.lang.IllegalArgumentException: im == null!

This is because the BufferedImage img is null. I think this has something to do with the fact that in my original conversion from BufferedImage to byte array, information is changed/lost so that the data can no longer be recognised as a jpg.

Does anyone have any suggestions on how to solve this? Would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is recommended to convert to a byte array

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
byte[] bytes = baos.toByteArray();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...