Converts a ByteBuffer to a BufferedImage. - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Convert

Description

Converts a ByteBuffer to a BufferedImage.

Demo Code

/*//  ww  w. j a va  2s  .  c o  m
 * Image conversion utilities.
 * 
 * Copyright (c) 2006 Jean-Sebastien Senecal (js@drone.ws)
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 675 Mass
 * Ave, Cambridge, MA 02139, USA.
 */
//package com.java2s;

import java.awt.image.BufferedImage;

import java.awt.image.DataBufferByte;

import java.nio.ByteBuffer;

public class Main {
    /**
     * Converts a <code>ByteBuffer</code> to a <code>BufferedImage</code>.
     * @param bb a ByteBuffer with each byte representing R, G, B color bytes.
     * @param bi a BufferedImage of TYPE_3BYTE_BGR. The size of the ByteBuffer 
     *    must equal to the number of pixels of the BufferedImage * 3.
     */
    public static void byteBuffer2BufferedImage(ByteBuffer bb,
            BufferedImage bi) {
        final int bytesPerPixel = 3;
        byte[] imageArray = ((DataBufferByte) bi.getRaster()
                .getDataBuffer()).getData();
        bb.rewind();
        bb.get(imageArray);
        int numPixels = bb.capacity() / bytesPerPixel;
        for (int i = 0; i < numPixels; i++) {
            byte tmp = imageArray[i * bytesPerPixel];
            imageArray[i * bytesPerPixel] = imageArray[i * bytesPerPixel
                    + 2];
            imageArray[i * bytesPerPixel + 2] = tmp;
        }
    }
}

Related Tutorials