Java BufferedImage to Gray Scale byteBufferToGrayBufferedImage(ByteBuffer buffer, BufferedImage bi)

Here you can find the source of byteBufferToGrayBufferedImage(ByteBuffer buffer, BufferedImage bi)

Description

Converts depth values in ShortBuffer to a gray scale BufferedImage.

License

Open Source License

Parameter

Parameter Description
buffer a parameter
bi <BufferedImage> of with type <code>TYPE_USHORT_GRAY</code>

Declaration

public static void byteBufferToGrayBufferedImage(ByteBuffer buffer, BufferedImage bi) 

Method Source Code

//package com.java2s;
/*/*from   w w w  . j av a 2  s  .  co  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.
 */

import java.awt.image.BufferedImage;

import java.awt.image.DataBufferUShort;

import java.nio.ByteBuffer;

public class Main {
    /**
     * Converts depth values in <code>ShortBuffer</code> to a gray scale 
     * <code>BufferedImage</code>.
     * @param buffer
     * @param bi <BufferedImage> of with type <code>TYPE_USHORT_GRAY</code>
     */
    public static void byteBufferToGrayBufferedImage(ByteBuffer buffer, BufferedImage bi) {
        if (bi.getType() != BufferedImage.TYPE_USHORT_GRAY)
            throw new IllegalArgumentException(
                    "Invalid image type. Expect image " + "type BufferedImage.TYPE_USHORT_GRAY.");
        int maxDepth = 1 << 16 - 1;

        short[] imageArray = ((DataBufferUShort) bi.getRaster().getDataBuffer()).getData();
        buffer.rewind();
        while (buffer.remaining() > 0) {
            int pos = buffer.position();
            int value = buffer.get() & 0x0000ffff;
            imageArray[pos] = value == 0 ? 0 : (short) (value * maxDepth / 255);
        }
    }
}

Related

  1. imageToGrayscale(BufferedImage image)
  2. imageToGrayscale(BufferedImage img)
  3. gray(BufferedImage src)
  4. grayImage(BufferedImage image)