Java将byte[]转换为图像

4

我知道这似乎是一个常见的问题,但我已经在互联网上搜索了很多,尝试了许多不同的教程和方法来解决它。我认为我已经接近成功了,但不确定。此外,我正在使用Play框架,但Java应该也是一样的。 以下是我的错误信息:

javax.image.IIOException: I/O error reading PNG header!
   at com.sun.plugins.png.PNGImageReader.readHeader(Unknown Source)
   ...
   ...
Caused by: java.io.EOFException
at javax.imageio.stream.ImageInputStreamImpl.readFully(Unknown Source)
  ...

以下是我的代码,其中我从表单中获取图片等内容,并将图像转换为字节数组并存储在 MS SQL 数据库中。

@Transactional
public static Result submitTrailer(){
     filledForm = newTrailerForm.bindFromRequest();
     MultipartFormData body = request().body().asMultipartFormData();
     FilePart picture = body.getFile("file");
     String fileName = picture.getFilename();
     System.out.println(fileName);
     String contentType = picture.getContentType(); 
     System.out.println(contentType);
     final File file = picture.getFile();
     filledForm.get().setContentType(contentType);

     try{
     BufferedImage originalImage = ImageIO.read(file);
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     ImageIO.write(originalImage, contentType, baos);

     filledForm.get().setImage(baos.toByteArray());
     baos.flush();
     baos.close();
     filledForm.get().save();
     }catch(IOException e){
         e.printStackTrace();
     }

    return ok(views.html.index.index.render());
}

这里我正在尝试将byte[]转换回图像,以便在HTML中显示它。

public File getConvertedPicture(){
    File imageFile;
    System.out.println("byteToImage() called");
    if(getImage()==null){
        System.out.println("getByteImage()==null");
        return null;

    }else{
        try{
        ByteArrayInputStream bis = new ByteArrayInputStream(getImage());
        imageFile=File.createTempFile("pattern", ".suffix");

        Iterator<?> readers = ImageIO.getImageReadersByFormatName("PNG");


        ImageReader reader = (ImageReader) readers.next();
         Object source = bis;
         ImageInputStream iis = ImageIO.createImageInputStream(source);
         reader.setInput(iis, true);
            ImageReadParam param = reader.getDefaultReadParam();

            Image image = reader.read(0, param);
            BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = bufferedImage.createGraphics();
            g2.drawImage(image, null, null);

            ImageIO.write(bufferedImage,"PNG", imageFile);
            return imageFile;

        }
        catch(IOException e){
            e.printStackTrace();
            return null;
        }
    }

我是初学者,这是我第一次使用play和数据库。如果有什么建议能帮助我使其正常运行将不胜感激。

另外,在我的getConvertedPicture()方法中我需要指定格式类型,是否有任何方式可以避免这种情况,让用户上传他们想要的任何类型的图片。


你的异常似乎表明 getImage() 的字节不够。你检查过了吗? - Denys Séguret
不,我不确定怎么做。我检查了确保数据在那里,但不确定如何检查它是否被正确存储。 - mingle
3个回答

7

如果想将字节转换为图像,而不知道文件类型,我通常会执行以下操作:

ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
BufferedImage image = ImageIO.read(bais);

这将返回一个BufferedImage,您可以将其保存为任何图片格式,如jpg。

要将图像写回字节数组:

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

我的BufferedImage图像尺寸比预期的要大得多。例如,如果我有一个9MB大小的字节数组图片,在转换为BufferedImage后它会变得更大。 - Ante Ereš

4
尝试使用

byte[] byteArray=null; //need to initialize it
ImageIcon imageIcon = new ImageIcon(byteArray);
imageIcon.getImage();

3

将字节数组,即byte[]转换为图像,请使用getImage()方法。可能最简单的方法是使用ImageIcon(byte[])构造函数实例化一个ImageIcon对象,然后调用getImage()方法。以下方法中,特别是最后一行演示了这一点:

public Image createImage(){
   byte[] b = {-119, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82,
      0, 0, 0, 15, 0, 0, 0, 15, 8, 6, 0, 0, 0, 59, -42, -107,
      74, 0, 0, 0, 64, 73, 68, 65, 84, 120, -38, 99, 96, -64, 14, -2,
      99, -63, 68, 1, 100, -59, -1, -79, -120, 17, -44, -8, 31, -121, 28, 81,
      26, -1, -29, 113, 13, 78, -51, 100, -125, -1, -108, 24, 64, 86, -24, -30,
      11, 101, -6, -37, 76, -106, -97, 25, 104, 17, 96, -76, 77, 97, 20, -89,
      109, -110, 114, 21, 0, -82, -127, 56, -56, 56, 76, -17, -42, 0, 0, 0,
      0, 73, 69, 78, 68, -82, 66, 96, -126};
   return new ImageIcon(b).getImage();
}

我认为这可以用于pnggifbmpjpg 图片。字节数组不需要像这个例子一样硬编码。
此外,new ImageIcon("image.png").getImage() 可以用于从文件加载可显示的图像,其中 image.png 是文件名。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接