Here you can find the source of floatBufferToGrayBufferedImage(FloatBuffer floatBuffer, BufferedImage bi)
BufferedImage
.
Parameter | Description |
---|---|
floatBuffer | contains float values. The size of the buffer must be at least as big as the size of the image. |
bi | <code>BufferedImage</code> with type TYPE_USHORT_GRAY. |
widthStep | number of float values per row in <code>floatBuffer</code>. |
public static BufferedImage floatBufferToGrayBufferedImage(FloatBuffer floatBuffer, BufferedImage bi)
//package com.java2s; /*// www . j a v a2 s. 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. */ import java.awt.image.BufferedImage; import java.awt.image.DataBufferUShort; import java.nio.FloatBuffer; public class Main { /** * Converts float values to an unsigned short <code>BufferedImage</code>. * * @param floatBuffer contains float values. The size of the buffer must be at * least as big as the size of the image. * @param bi <code>BufferedImage</code> with type TYPE_USHORT_GRAY. * @param widthStep number of float values per row in * <code>floatBuffer</code>. * @return */ public static BufferedImage floatBufferToGrayBufferedImage(FloatBuffer floatBuffer, 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; float min = Float.MAX_VALUE; float max = Float.MIN_VALUE; floatBuffer.rewind(); while (floatBuffer.remaining() > 0) { float value = floatBuffer.get(); min = Math.min(min, value); max = Math.max(max, value); } short[] array = ((DataBufferUShort) bi.getRaster().getDataBuffer()).getData(); float range = max - min; if (range == 0) range = 1; floatBuffer.rewind(); while (floatBuffer.remaining() > 0) { int pos = floatBuffer.position(); float value = floatBuffer.get(); int converted = Math.round(((value - min) * maxDepth / range)); array[pos] = (short) converted; } return bi; } }