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

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

Description

Converts a byte array into an Image instance.

License

Apache License

Parameter

Parameter Description
imageBytes bytes to convert

Exception

Parameter Description
IOException an exception

Declaration

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

Method Source Code

//package com.java2s;
/*/*from ww w  . j a  v  a2  s  . co  m*/
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

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

    /**
     * Converts a byte array into an {@link Image} instance.
     * 
     * @param imageBytes
     *            bytes to convert
     * @return
     * @throws IOException
     */
    public static Image bytesToImage(byte[] imageBytes) throws IOException {
        if (imageBytes == null) {
            throw new IOException("Could not load image - no data provided");
        }
        boolean interrupted = false;
        Throwable exception = null;
        Image image = null;
        image = Toolkit.getDefaultToolkit().createImage(imageBytes);
        MediaTracker tracker = new MediaTracker(observer);
        tracker.addImage(image, 0);
        do {
            try {
                interrupted = false;
                tracker.waitForID(0); // This is the only method that throws an exception
            } catch (InterruptedException t) {
                interrupted = true;
                continue;
            } catch (Throwable t) {
                exception = t;
            }
        } while (interrupted);
        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)