简体   繁体   English

Java将byte []转换为图像

[英]Java converting byte[] to image

I know this seems like a common question but i have looked all over the internets, and tried many different tutorials and methods for doing this. 我知道这似乎是一个常见的问题,但我在互联网上四处浏览,并尝试了许多不同的教程和方法来执行此操作。 I think i am close, but not sure. 我想我很近,但不确定。 Also i am using Play Framework but it should be the same for java. 我也正在使用Play Framework,但对于Java应该是相同的。 here is my error 这是我的错误

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)
  ...

Here is my code where i get the picture among other things from a form and convert the image to a byte[] and store in MS SQL db. 这是我的代码,在其中我从表单中获取图片并将图像转换为byte []并存储在MS SQL db中。

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

here is where i am trying to covert the byte[] back to an image so i can display it in html 这是我尝试将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;
        }
    }

I am a beginner, this is my first time using play, and first time using databases. 我是一个初学者,这是我第一次使用游戏,也是第一次使用数据库。 Any advice to get this to work would be greatly appreciated. 任何建议,以使这一工作,将不胜感激。

also, in my method getConvertedPicture() i have to specify the format type, is there anyway to get around this so the user can upload any type of picture they want. 另外,在我的方法getConvertedPicture()中,我必须指定格式类型,无论如何都可以解决这个问题,以便用户可以上传他们想要的任何类型的图片。

To convert bytes to an image without knowing the file type I usually do: 要将字节转换为图像而不知道文件类型,我通常会这样做:

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

That will return a BufferedImage that you can save into any picture format such as jpg. 这将返回一个BufferedImage,您可以将其保存为任何图片格式,例如jpg。

To write the image back out to a byte array: 要将图像写回到字节数组:

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

To convert an array of bytes, ie byte[] into an image, use getImage() . 要将字节数组(即byte[]转换为图像,请使用getImage() Probably the easiest way to do this is to instantiate an ImageIcon using the ImageIcon(byte[]) constructor, and then call getImage() . 可能最简单的方法是使用ImageIcon(byte[])构造函数实例化ImageIcon ,然后调用getImage() This is illustrated in the method below, particularly the last line: 下面的方法对此进行了说明,特别是最后一行:

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

I think this can by used for png , gif , bmp , and jpg images. 我认为这可以用于pnggifbmpjpg图像。 The byte array does not have to be hard-coded, as in this example. 如本例所示,字节数组不必进行硬编码。

Additionally, new ImageIcon("image.png").getImage() can be used to load a displayable image from a file, where image.png is the filename. 另外,可以使用new ImageIcon("image.png").getImage()从文件中加载可显示的图像,其中image.png是文件名。

Try to use 尝试使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM