简体   繁体   中英

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

@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

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.

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.

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() . Probably the easiest way to do this is to instantiate an ImageIcon using the ImageIcon(byte[]) constructor, and then call 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. 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.

Try to use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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