Java examples for 2D Graphics:BufferedImage Convert
Converts float values to an unsigned short BufferedImage.
/*//from ww w. j a v a 2 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. */ //package com.java2s; 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 floatBuffer2UShortGrayBufferedImage( FloatBuffer floatBuffer, BufferedImage bi, int widthStep) { final int MAX = 65535; float min = Float.MAX_VALUE; float max = Float.MIN_VALUE; int width = bi.getWidth(); int height = bi.getHeight(); for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { float value = floatBuffer.get(h * widthStep + w); 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; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { float value = floatBuffer.get(h * widthStep + w); int converted = Math.round(((value - min) * MAX / range)); array[h * width + w] = (short) converted; } return bi; } }