Java Image from Byte Array bytesToImage(byte[] imageBytes)

Here you can find the source of bytesToImage(byte[] imageBytes)

Description

bytes To Image

License

Open Source License

Declaration

public static Image bytesToImage(byte[] imageBytes) throws IOException 

Method Source Code

//package com.java2s;
/*/*from   www .j a  va2  s . c o  m*/
 * Copyright (c) 2014 tabletoptool.com team.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html
 * 
 * Contributors:
 *     rptools.com team - initial implementation
 *     tabletoptool.com team - further development
 */

import java.awt.Image;
import java.awt.MediaTracker;

import java.awt.Toolkit;

import java.io.ByteArrayInputStream;

import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class Main {
    private static final JPanel observer = new JPanel();

    public static Image bytesToImage(byte[] imageBytes) throws IOException {

        if (imageBytes == null) {
            System.out.println("WEhaah??");
        }
        Throwable exception = null;
        Image image = null;
        try {
            image = Toolkit.getDefaultToolkit().createImage(imageBytes);
            MediaTracker tracker = new MediaTracker(observer);
            tracker.addImage(image, 0);
            tracker.waitForID(0);
        } catch (Throwable t) {
            exception = t;
        }
        if (image == null || exception != null || image.getWidth(null) <= 0 || image.getHeight(null) <= 0) {
            // Try the newer way (although it pretty much sucks rocks)
            image = ImageIO.read(new ByteArrayInputStream(imageBytes));
        }

        if (image == null) {
            throw new IOException("Could not load image: " + exception);
        }

        return image;
    }
}

Related

  1. bytesToBImage(byte[] bytes)
  2. bytesToImage(byte[] imageBytes)
  3. bytesToImage(byte[] imageBytes)