use of java.awt.image.ColorModel in project imageio-ext by geosolutions-it.
the class JP2KKakaduWriteTest method test24BitGray.
public static void test24BitGray() throws IOException {
if (!isKakaduAvailable) {
LOGGER.warning("Kakadu libs not found: test are skipped ");
return;
}
final ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorModel cm = new ComponentColorModel(cs, new int[] { 24 }, false, false, Transparency.OPAQUE, DataBuffer.TYPE_INT);
final int w = 512;
final int h = 512;
SampleModel sm = cm.createCompatibleSampleModel(w, h);
final int bufferSize = w * h;
final int[] bufferValues = new int[bufferSize];
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) // bufferValues[j + (i * h)] = (int) (j + i) * (16777216 /
// 1024);
bufferValues[j + (i * h)] = (int) (Math.random() * 16777215d);
}
DataBuffer imageBuffer = new DataBufferInt(bufferValues, bufferSize);
BufferedImage bi = new BufferedImage(cm, Raster.createWritableRaster(sm, imageBuffer, null), false, null);
JP2KKakaduImageWriteParam param = new JP2KKakaduImageWriteParam();
param.setSourceSubsampling(2, 3, 0, 0);
write(outputFileName + "_gray24", bi, true, lossLessQuality);
write(outputFileName + "_gray24", bi, false, lossLessQuality);
write(outputFileName + "_gray24", bi, true, lossyQuality);
write(outputFileName + "_gray24", bi, false, lossyQuality);
write(outputFileName + "_JAI_gray24", bi, true, lossLessQuality, true);
write(outputFileName + "_JAI_gray24", bi, false, lossLessQuality, true);
write(outputFileName + "_JAI_subSampled_gray24", bi, true, lossyQuality, true, param);
write(outputFileName + "_JAI_subSampled_gray24", bi, false, lossyQuality, true, param);
LOGGER.info(writeOperations + " write operations performed");
}
use of java.awt.image.ColorModel in project imageio-ext by geosolutions-it.
the class ImageIOUtilities method createColorModel.
/**
* Creates a <code>ColorModel</code> that may be used with the
* specified <code>SampleModel</code>. If a suitable
* <code>ColorModel</code> cannot be found, this method returns
* <code>null</code>.
*
* <p> Suitable <code>ColorModel</code>s are guaranteed to exist
* for all instances of <code>ComponentSampleModel</code>.
* For 1- and 3- banded <code>SampleModel</code>s, the returned
* <code>ColorModel</code> will be opaque. For 2- and 4-banded
* <code>SampleModel</code>s, the output will use alpha transparency
* which is not premultiplied. 1- and 2-banded data will use a
* grayscale <code>ColorSpace</code>, and 3- and 4-banded data a sRGB
* <code>ColorSpace</code>. Data with 5 or more bands will have a
* <code>BogusColorSpace</code>.</p>
*
* <p>An instance of <code>DirectColorModel</code> will be created for
* instances of <code>SinglePixelPackedSampleModel</code> with no more
* than 4 bands.</p>
*
* <p>An instance of <code>IndexColorModel</code> will be created for
* instances of <code>MultiPixelPackedSampleModel</code>. The colormap
* will be a grayscale ramp with <code>1 << numberOfBits</code>
* entries ranging from zero to at most 255.</p>
*
* @return An instance of <code>ColorModel</code> that is suitable for
* the supplied <code>SampleModel</code>, or <code>null</code>.
*
* @throws IllegalArgumentException If <code>sampleModel</code> is
* <code>null</code>.
*/
public static final ColorModel createColorModel(SampleModel sampleModel) {
// Check the parameter.
if (sampleModel == null) {
throw new IllegalArgumentException("sampleModel == null!");
}
// Get the data type.
int dataType = sampleModel.getDataType();
// Check the data type
switch(dataType) {
case DataBuffer.TYPE_BYTE:
case DataBuffer.TYPE_USHORT:
case DataBuffer.TYPE_SHORT:
case DataBuffer.TYPE_INT:
case DataBuffer.TYPE_FLOAT:
case DataBuffer.TYPE_DOUBLE:
break;
default:
// Return null for other types.
return null;
}
// The return variable.
ColorModel colorModel = null;
// Get the sample size.
int[] sampleSize = sampleModel.getSampleSize();
// Create a Component ColorModel.
if (sampleModel instanceof ComponentSampleModel) {
// Get the number of bands.
int numBands = sampleModel.getNumBands();
// Determine the color space.
ColorSpace colorSpace = null;
if (numBands <= 2) {
colorSpace = ColorSpace.getInstance(ColorSpace.CS_GRAY);
} else if (numBands <= 4) {
colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
} else {
colorSpace = new BogusColorSpace(numBands);
}
boolean hasAlpha = (numBands == 2) || (numBands == 4);
boolean isAlphaPremultiplied = false;
int transparency = hasAlpha ? Transparency.TRANSLUCENT : Transparency.OPAQUE;
if (dataType == DataBuffer.TYPE_SHORT)
colorModel = new ComponentColorModel(colorSpace, sampleSize, hasAlpha, isAlphaPremultiplied, transparency, dataType);
else
colorModel = RasterFactory.createComponentColorModel(dataType, colorSpace, hasAlpha, isAlphaPremultiplied, transparency);
} else if (sampleModel.getNumBands() <= 4 && sampleModel instanceof SinglePixelPackedSampleModel) {
SinglePixelPackedSampleModel sppsm = (SinglePixelPackedSampleModel) sampleModel;
int[] bitMasks = sppsm.getBitMasks();
int rmask = 0;
int gmask = 0;
int bmask = 0;
int amask = 0;
int numBands = bitMasks.length;
if (numBands <= 2) {
rmask = gmask = bmask = bitMasks[0];
if (numBands == 2) {
amask = bitMasks[1];
}
} else {
rmask = bitMasks[0];
gmask = bitMasks[1];
bmask = bitMasks[2];
if (numBands == 4) {
amask = bitMasks[3];
}
}
int bits = 0;
for (int i = 0; i < sampleSize.length; i++) {
bits += sampleSize[i];
}
return new DirectColorModel(bits, rmask, gmask, bmask, amask);
} else if (sampleModel instanceof MultiPixelPackedSampleModel) {
// Load the colormap with a ramp.
int bitsPerSample = sampleSize[0];
int numEntries = 1 << bitsPerSample;
byte[] map = new byte[numEntries];
for (int i = 0; i < numEntries; i++) {
map[i] = (byte) (i * 255 / (numEntries - 1));
}
colorModel = new IndexColorModel(bitsPerSample, numEntries, map, map, map);
}
return colorModel;
}
use of java.awt.image.ColorModel in project imageio-ext by geosolutions-it.
the class GDALImageReader method read.
/**
* Read the raster and returns a <code>BufferedImage</code>
*
* @param imageIndex
* the index of the image to be retrieved.
* @param param
* an <code>ImageReadParam</code> used to control the
* reading process, or <code>null</code>. Actually,
* setting a destinationType allows to specify the number of
* bands in the destination image.
*
* @return the desired portion of the image as a <code>BufferedImage</code>
* @throws IllegalArgumentException
* if <code>param</code> contains an invalid specification
* of a source and/or destination band subset or of a
* destination image.
* @throws IOException
* if an error occurs when acquiring access to the
* underlying datasource
*/
public BufferedImage read(final int imageIndex, final ImageReadParam param) throws IOException {
// //
//
// Retrieving the requested dataset
//
// //
final GDALCommonIIOImageMetadata item = getDatasetMetadata(imageIndex);
int width = item.getWidth();
int height = item.getHeight();
final Dataset originalDataset = datasetsMap.get(item.getDatasetName());
if (originalDataset == null)
throw new IOException("Error while acquiring the input dataset " + item.getDatasetName());
Dataset dataset = originalDataset;
Dataset warpedDataset = null;
try {
if (param instanceof GDALImageReadParam) {
GDALImageReadParam gdalImageReadParam = (GDALImageReadParam) param;
// Check for source != destination
String sourceWkt = dataset.GetProjection();
String destinationWkt = gdalImageReadParam.getDestinationWkt();
SpatialReference sourceReference = new SpatialReference(sourceWkt);
SpatialReference destinationReference = new SpatialReference(destinationWkt);
// lets warp the image using GDAL.
if (sourceReference.IsSame(destinationReference) == 0) {
dataset = gdal.AutoCreateWarpedVRT(dataset, dataset.GetProjection(), destinationWkt, gdalImageReadParam.getResampleAlgorithm().getGDALResampleAlgorithm(), gdalImageReadParam.getMaxError());
warpedDataset = dataset;
// width and height may have changed from original metadata
width = warpedDataset.getRasterXSize();
height = warpedDataset.getRasterYSize();
}
}
final SampleModel itemSampleModel = item.getSampleModel();
int itemNBands = itemSampleModel.getNumBands();
int nDestBands;
BufferedImage bi = null;
final ImageReadParam imageReadParam;
if (param == null)
imageReadParam = getDefaultReadParam();
else
imageReadParam = param;
// //
//
// First, check for a specified ImageTypeSpecifier
//
// //
ImageTypeSpecifier imageType = imageReadParam.getDestinationType();
SampleModel destSampleModel = null;
if (imageType != null) {
destSampleModel = imageType.getSampleModel();
nDestBands = destSampleModel.getNumBands();
} else {
bi = imageReadParam.getDestination();
if (bi != null)
nDestBands = bi.getSampleModel().getNumBands();
else
nDestBands = itemNBands;
}
// //
//
// Second, bands settings check
//
// //
checkReadParamBandSettings(imageReadParam, itemNBands, nDestBands);
int[] srcBands = imageReadParam.getSourceBands();
// int[] destBands = imageReadParam.getDestinationBands();
//
// //
//
// Third, destination image check
//
// //
// if (bi != null && imageType == null) {
// if ((srcBands == null) && (destBands == null)) {
// SampleModel biSampleModel = bi.getSampleModel();
// if (!bi.getColorModel().equals(item.getColorModel())
// || biSampleModel.getDataType() != itemSampleModel
// .getDataType())
// throw new IllegalArgumentException(
// "Provided destination image does not have a valid ColorModel or
// SampleModel");
// }
// }
// //
//
// Computing regions of interest
//
// //
Rectangle srcRegion = new Rectangle(0, 0, 0, 0);
Rectangle destRegion = new Rectangle(0, 0, 0, 0);
computeRegions(imageReadParam, width, height, bi, srcRegion, destRegion);
if (imageReadParam != null) {
if (imageReadParam instanceof EnhancedImageReadParam) {
final EnhancedImageReadParam eparam = (EnhancedImageReadParam) imageReadParam;
final Rectangle dstRegion = eparam.getDestinationRegion();
if (dstRegion != null) {
destRegion.height = dstRegion.height;
destRegion.width = dstRegion.width;
}
}
}
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Source Region = " + srcRegion.toString());
LOGGER.fine("Destination Region = " + destRegion.toString());
}
//
if (bi == null) {
// //
//
// No destination image has been specified.
// Creating a new BufferedImage
//
// //
ColorModel cm;
if (imageType == null) {
cm = item.getColorModel();
bi = new BufferedImage(cm, (WritableRaster) readDatasetRaster(item.getSampleModel(), dataset, srcRegion, destRegion, srcBands), false, null);
} else {
cm = imageType.getColorModel();
bi = new BufferedImage(cm, (WritableRaster) readDatasetRaster(destSampleModel, dataset, srcRegion, destRegion, srcBands), false, null);
}
} else {
// //
//
// the destination image has been specified.
//
// //
// Rectangle destSize = (Rectangle) destRegion.clone();
// destSize.setLocation(0, 0);
Raster readRaster = readDatasetRaster(item.getSampleModel(), dataset, srcRegion, destRegion, srcBands);
WritableRaster raster = bi.getRaster().createWritableChild(0, 0, bi.getWidth(), bi.getHeight(), 0, 0, null);
// TODO: Work directly on a Databuffer avoiding setRect?
raster.setRect(destRegion.x, destRegion.y, readRaster);
// Raster readRaster = readDatasetRaster(item, srcRegion,
// destRegion,
// srcBands);
// WritableRaster raster = bi.getRaster().createWritableChild(
// destRegion.x, destRegion.y, destRegion.width,
// destRegion.height, destRegion.x, destRegion.y, null);
// //TODO: Work directly on a Databuffer avoiding setRect?
// raster.setRect(readRaster);
}
return bi;
} finally {
if (warpedDataset != null) {
GDALUtilities.closeDataSet(warpedDataset);
}
}
}
use of java.awt.image.ColorModel in project imageio-ext by geosolutions-it.
the class GDALImageWriter method setMetadata.
/**
* Set all the metadata available in the imageMetadata
* <code>IIOMetadata</code> instance
*
* @param dataset
* the dataset on which to set metadata and properties
* @param imageMetadata
* an instance of a {@link GDALCommonIIOImageMetadata}
* containing metadata
*/
private void setMetadata(Dataset dataset, GDALCommonIIOImageMetadata imageMetadata) {
// TODO: which metadata should be copied in the dataset?
// Should width, height and similar properties to be copied?
// //
//
// Setting GeoTransformation
//
// //
final double[] geoTransformation = imageMetadata.getGeoTransformation();
if (geoTransformation != null)
dataset.SetGeoTransform(geoTransformation);
// //
//
// Setting Projection
//
// //
final String projection = imageMetadata.getProjection();
if (projection != null && projection.trim().length() != 0)
dataset.SetProjection(projection);
// //
//
// Setting GCPs
//
// //
final int gcpNum = imageMetadata.getGcpNumber();
if (gcpNum != 0) {
final String gcpProj = imageMetadata.getGcpProjection();
List gcps = imageMetadata.getGCPs();
// TODO: Fix getGCPs access in SWIG's Java Bindings
// TODO: set GCPs. Not all dataset support GCPs settings
// dataset.SetGCPs(1, gcps, gcpProj);
}
// //
//
// Setting bands values
//
// //
final int nBands = imageMetadata.getNumBands();
for (int i = 0; i < nBands; i++) {
final Band band = dataset.GetRasterBand(i + 1);
final int colorInterpretation = imageMetadata.getColorInterpretations(i);
band.SetRasterColorInterpretation(colorInterpretation);
if (i == 0 && nBands == 1) {
// //
if (colorInterpretation == gdalconstConstants.GCI_PaletteIndex) {
ColorModel cm = imageMetadata.getColorModel();
if (cm instanceof IndexColorModel) {
IndexColorModel icm = (IndexColorModel) cm;
// //
//
// Setting color table
//
// //
final int size = icm.getMapSize();
ColorTable ct = new ColorTable(gdalconstConstants.GPI_RGB);
int j = 0;
for (; j < size; j++) ct.SetColorEntry(j, new Color(icm.getRGB(j)));
band.SetRasterColorTable(ct);
}
}
}
try {
final double noData = imageMetadata.getNoDataValue(i);
if (!Double.isNaN(noData))
band.SetNoDataValue(noData);
} catch (IllegalArgumentException iae) {
// NoDataValue not found or wrong bandIndex specified. Go on
}
}
// //
//
// Setting metadata
//
// TODO: Requires SWIG bindings extending since an HashTable as
// parameter crashes the JVM
//
// //
final List<String> domains = imageMetadata.getGdalMetadataDomainsList();
final int nDomains = domains.size();
for (int i = 0; i < nDomains; i++) {
final String domain = (String) domains.get(i);
Map metadataMap = imageMetadata.getGdalMetadataDomain(domain);
if (metadataMap != null) {
Iterator<String> keysIt = metadataMap.keySet().iterator();
while (keysIt.hasNext()) {
final String key = keysIt.next();
final String value = (String) metadataMap.get(key);
dataset.SetMetadataItem(key, value, domain);
}
}
}
}
use of java.awt.image.ColorModel in project digilib by robcast.
the class ImageLoaderDocuImage method colorOp.
/*
* (non-Javadoc)
*
* @see
* digilib.image.DocuImageImpl#colorOp(digilib.image.DocuImage.ColorOps)
*/
public void colorOp(ColorOp colop) throws ImageOpException {
if (colop == ColorOp.GRAYSCALE) {
/*
* convert image to grayscale
*/
logger.debug("Color op: grayscaling");
ColorModel cm = img.getColorModel();
if (cm.getNumColorComponents() < 3) {
// grayscale already
logger.debug("Color op: not grayscaling");
return;
}
ColorConvertOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), renderHint);
// let filter create new image
img = op.filter(img, null);
} else if (colop == ColorOp.NTSC_GRAY) {
/*
* convert image to grayscale NTSC-style: luminance = 0.2989*red +
* 0.5870*green + 0.1140*blue
*/
logger.debug("Color op: NTSC gray");
logger.debug("img=" + img);
ColorModel cm = img.getColorModel();
if (cm.getNumColorComponents() < 3 || cm instanceof IndexColorModel) {
// grayscale already or not possible
logger.debug("Color op: unable to NTSC gray");
return;
}
float[][] combineFn = new float[1][4];
combineFn[0] = new float[] { 0.299f, 0.587f, 0.114f, 0f };
BandCombineOp op = new BandCombineOp(combineFn, renderHint);
// BandCombineOp only works on Rasters so we create a
// new image and use its Raster
BufferedImage dest = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
op.filter(img.getRaster(), dest.getRaster());
img = dest;
} else if (colop == ColorOp.BITONAL) {
/*
* convert image to bitonal black and white
* (nothing clever is done)
*/
logger.debug("Color op: bitonal");
logger.debug("img=" + img);
BufferedImage dest = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
dest.createGraphics().drawImage(img, null, 0, 0);
img = dest;
logger.debug("bitonal img=" + img);
} else if (colop == ColorOp.INVERT) {
/*
* invert colors i.e. invert every channel
*/
logger.debug("Color op: inverting");
LookupTable invtbl = null;
ColorModel cm = img.getColorModel();
if (cm instanceof IndexColorModel) {
// invert not possible
// TODO: should we convert?
logger.debug("Color op: unable to invert");
return;
}
if (imageHacks.get(Hacks.needsInvertRgba) && cm.hasAlpha()) {
// fix for some cases
invtbl = invertRgbaByteTable;
} else {
invtbl = invertSingleByteTable;
}
LookupOp op = new LookupOp(invtbl, renderHint);
logger.debug("colop: image=" + img);
op.filter(img, img);
} else if (colop == ColorOp.MAP_GRAY_BGR) {
/*
* false color image from grayscale (0: blue, 128: green, 255: red)
*/
logger.debug("Color op: map_gray_bgr");
// convert to grayscale
ColorConvertOp grayOp = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), renderHint);
// create new 3-channel image
int destType = BufferedImage.TYPE_INT_RGB;
if (imageHacks.get(Hacks.needsMapBgr)) {
// special case for funny Java2D implementations
if (img.getColorModel().hasAlpha()) {
destType = BufferedImage.TYPE_4BYTE_ABGR_PRE;
} else {
destType = BufferedImage.TYPE_3BYTE_BGR;
}
}
BufferedImage dest = new BufferedImage(img.getWidth(), img.getHeight(), destType);
img = grayOp.filter(img, dest);
logger.debug("map_gray: image=" + img);
// convert to false color
LookupOp mapOp = new LookupOp(mapBgrByteTable, renderHint);
mapOp.filter(img, img);
logger.debug("mapped image=" + img);
}
}
Aggregations