diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..428133f
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+SOURCES/jai-imageio-core-cvs20100217-CLEANED.tar.xz
diff --git a/.rh-java-common-jai-imageio-core.metadata b/.rh-java-common-jai-imageio-core.metadata
new file mode 100644
index 0000000..a93838b
--- /dev/null
+++ b/.rh-java-common-jai-imageio-core.metadata
@@ -0,0 +1 @@
+a1abf7b272c965df019bd9abbb6b9326735f6f68 SOURCES/jai-imageio-core-cvs20100217-CLEANED.tar.xz
diff --git a/README.md b/README.md
deleted file mode 100644
index 98f42b4..0000000
--- a/README.md
+++ /dev/null
@@ -1,4 +0,0 @@
-The master branch has no content
-
-Look at the c7 branch if you are working with CentOS-7, or the c4/c5/c6 branch for CentOS-4, 5 or 6
-If you find this file in a distro specific branch, it means that no content has been checked in yet
diff --git a/SOURCES/README-RHSCL.txt b/SOURCES/README-RHSCL.txt
new file mode 100644
index 0000000..89a1786
--- /dev/null
+++ b/SOURCES/README-RHSCL.txt
@@ -0,0 +1,25 @@
+jai-imageio-core README for Red Hat Software Collections
+========================================================
+
+This package contains a CVS snapshot of jai-imageio-core from
+https://jai-imageio.dev.java.net/.
+
+Because of copyright issues, some functionality has been removed
+for packaging in Red Hat Software Collections:
+
+ * JAI Image I/O Operations
+ * JPEG 2000 support
+ * codecLib (C implementation of plugins for JPEG, PNG, and TIFF)
+
+
+Everything else should work, including java.nio based ImageIO streams,
+and ImageIO readers/writers for:
+
+ * BMP
+ * GIF
+ * PCX
+ * PNM
+ * "Raw" (not digital camera RAW)
+ * TIFF (some formats unavailable because of missing codecLib)
+ * PCX
+ * WBMP
diff --git a/SOURCES/generate-tarball.sh b/SOURCES/generate-tarball.sh
new file mode 100755
index 0000000..81c6e24
--- /dev/null
+++ b/SOURCES/generate-tarball.sh
@@ -0,0 +1,42 @@
+#!/bin/bash
+
+set -e
+
+if [ -z "$1" ]; then
+ echo "Please give your dev.java.net username on the command line."
+ exit 1
+fi
+
+if [ -z "$2" ]; then
+ echo "Please give the desired date on the command line."
+ exit 1
+fi
+
+CVSROOT=":pserver:${1}@cvs.dev.java.net:/cvs"
+MODULE=jai-imageio-core
+DIR=$MODULE-cvs$2-CLEANED
+
+if [ -e $DIR ]; then
+ echo "Please remove $DIR and try again."
+ exit 1
+fi
+
+cvs -d $CVSROOT -f login
+
+echo "Checking out"
+cvs -z 3 -d $CVSROOT -f export -D $2 -d $DIR $MODULE
+
+echo "Cleaning"
+cd $DIR
+rm -rf LICENSE-codecLibJIIO.txt src/share/classes/jj2000 src/share/jclib4jai www
+cd ..
+
+echo "Making tarball"
+find $DIR -type d -print0 | xargs -0 touch -d $2 -c
+tar cJf $DIR.tar.xz $DIR --owner 0 --group 0
+tar czf $DIR.tar.gz $DIR --owner 0 --group 0
+
+echo "Cleaning up"
+rm -rf $DIR
+
+echo "Results in $DIR.tar.xz and $DIR.tar.gz"
diff --git a/SOURCES/jai-imageio-core-no-sun-classes.patch b/SOURCES/jai-imageio-core-no-sun-classes.patch
new file mode 100644
index 0000000..2b78172
--- /dev/null
+++ b/SOURCES/jai-imageio-core-no-sun-classes.patch
@@ -0,0 +1,54 @@
+Index: src/share/classes/com/sun/media/imageioimpl/plugins/pnm/PNMImageReader.java
+===================================================================
+RCS file: /cvs/jai-imageio-core/src/share/classes/com/sun/media/imageioimpl/plugins/pnm/PNMImageReader.java,v
+retrieving revision 1.1
+diff -u -3 -p -r1.1 PNMImageReader.java
+--- src/share/classes/com/sun/media/imageioimpl/plugins/pnm/PNMImageReader.java 11 Feb 2005 05:01:40 -0000 1.1
++++ src/share/classes/com/sun/media/imageioimpl/plugins/pnm/PNMImageReader.java 11 Nov 2009 20:17:16 -0000
+@@ -72,6 +72,7 @@ import javax.imageio.spi.ImageReaderSpi;
+ import javax.imageio.stream.ImageInputStream;
+
+ import java.io.*;
++import java.security.PrivilegedAction;
+ import java.util.ArrayList;
+ import java.util.Iterator;
+ import java.util.StringTokenizer;
+@@ -97,7 +98,10 @@ public class PNMImageReader extends Imag
+ static {
+ if (lineSeparator == null) {
+ String ls = (String)java.security.AccessController.doPrivileged(
+- new sun.security.action.GetPropertyAction("line.separator"));
++ new PrivilegedAction(){
++ public Object run() {
++ return System.getProperty("line.separator");
++ }});
+ lineSeparator = ls.getBytes();
+ }
+ }
+Index: src/share/classes/com/sun/media/imageioimpl/plugins/pnm/PNMImageWriter.java
+===================================================================
+RCS file: /cvs/jai-imageio-core/src/share/classes/com/sun/media/imageioimpl/plugins/pnm/PNMImageWriter.java,v
+retrieving revision 1.1
+diff -u -3 -p -r1.1 PNMImageWriter.java
+--- src/share/classes/com/sun/media/imageioimpl/plugins/pnm/PNMImageWriter.java 11 Feb 2005 05:01:40 -0000 1.1
++++ src/share/classes/com/sun/media/imageioimpl/plugins/pnm/PNMImageWriter.java 11 Nov 2009 20:17:16 -0000
+@@ -60,6 +60,7 @@ import java.awt.image.WritableRaster;
+
+ import java.io.IOException;
+
++import java.security.PrivilegedAction;
+ import java.util.Iterator;
+
+ import javax.imageio.IIOImage;
+@@ -109,7 +110,10 @@ public class PNMImageWriter extends Imag
+ static {
+ if (lineSeparator == null) {
+ String ls = (String)java.security.AccessController.doPrivileged(
+- new sun.security.action.GetPropertyAction("line.separator"));
++ new PrivilegedAction(){
++ public Object run() {
++ return System.getProperty("line.separator");
++ }});
+ lineSeparator = ls.getBytes();
+ }
+ }
diff --git a/SOURCES/jai-imageio-core-remove-codeclib-plugins.patch b/SOURCES/jai-imageio-core-remove-codeclib-plugins.patch
new file mode 100644
index 0000000..3c6619c
--- /dev/null
+++ b/SOURCES/jai-imageio-core-remove-codeclib-plugins.patch
@@ -0,0 +1,10353 @@
+diff -urN jai-imageio-core-cvs20091111-CLEANED/build.xml zzx2/build.xml
+--- jai-imageio-core-cvs20091111-CLEANED/build.xml 2007-08-27 17:43:29.000000000 -0400
++++ zzx2/build.xml 2009-11-11 15:32:11.379823605 -0500
+@@ -517,7 +517,6 @@
+
+ This implementation first attempts to retrieve the property
+- * using the equivalent superclass method. If the returned value
+- * is not a valid property value, the requested property name is
+- * that of the image thumbnails property, the stream metadata
+- * property, or the image metadata property, and there has been no
+- * prior attempt to read the corresponding property value, then its
+- * reads the value and set the property. This implementation therefore
+- * defers reading of the image thumbnails, stream metadata, and image
+- * metadata values until the correpsonding property is actually
+- * requested. The "ImageRead" operation uses the
+- * Java
+- * Image I/O Framework to read images from an input source. Which formats
+- * may be read depends on which {@link javax.imageio.ImageReader} plug-ins are
+- * registered with the Image I/O Framework when the operation is invoked. The input source will usually be an
+- * {@link javax.imageio.stream.ImageInputStream}, but may be a
+- * {@link java.io.File}, {@link java.io.RandomAccessFile},
+- * {@link java.io.InputStream}, {@link java.net.URL},
+- * {@link java.net.Socket}, {@link java.nio.channels.ReadableByteChannel},
+- * file path represented as a The "ImageRead" operation supports rendered,
+- * renderable, and
+- * collection modes and requires no source image.
+- * A {@link java.awt.RenderingHints} object may be supplied when the operation
+- * is created. In addition to the {@link java.awt.RenderingHints.Key} hints
+- * recognized by the eventual Image properties are used to make available metadata and other
+- * information. Property provision is mode-specific.boolean
indicating whether codecLib is available.
+- */
+- public static final boolean isCodecLibAvailable() {
+- // Retrieve value of system property here to allow this to be
+- // modified dynamically.
+- Boolean result = (Boolean)
+- AccessController.doPrivileged(new PrivilegedAction() {
+- public Object run() {
+- String property = null;
+- try {
+- property =
+- System.getProperty("com.sun.media.imageio.disableCodecLib");
+- } catch(SecurityException se) {
+- // Do nothing: leave 'property' null.
+- }
+- return (property != null &&
+- property.equalsIgnoreCase("true")) ?
+- Boolean.TRUE : Boolean.FALSE;
+- }
+- });
+- boolean isCodecLibDisabled = result.booleanValue();
+-
+- return isCodecLibAvailable && !isCodecLibDisabled;
+- }
+-
+- /**
+ * Return a version string for the package.
+ */
+ public static final String getVersion() {
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/clib/CLibImageReader.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/clib/CLibImageReader.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/clib/CLibImageReader.java 2006-02-27 20:33:31.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/clib/CLibImageReader.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,766 +0,0 @@
+-/*
+- * $RCSfile: CLibImageReader.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.11 $
+- * $Date: 2006/02/28 01:33:31 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.clib;
+-
+-import java.awt.Point;
+-import java.awt.Rectangle;
+-import java.awt.Transparency;
+-import java.awt.color.ColorSpace;
+-import java.awt.geom.AffineTransform;
+-import java.awt.image.AffineTransformOp;
+-import java.awt.image.BufferedImage;
+-import java.awt.image.ColorModel;
+-import java.awt.image.ComponentColorModel;
+-import java.awt.image.ComponentSampleModel;
+-import java.awt.image.DataBuffer;
+-import java.awt.image.DataBufferByte;
+-import java.awt.image.DataBufferUShort;
+-import java.awt.image.IndexColorModel;
+-import java.awt.image.MultiPixelPackedSampleModel;
+-import java.awt.image.PixelInterleavedSampleModel;
+-import java.awt.image.Raster;
+-import java.awt.image.SampleModel;
+-import java.awt.image.WritableRaster;
+-import java.io.InputStream;
+-import java.io.IOException;
+-import java.util.ArrayList;
+-import java.util.Iterator;
+-import java.util.NoSuchElementException;
+-import javax.imageio.IIOException;
+-import javax.imageio.ImageReader;
+-import javax.imageio.ImageReadParam;
+-import javax.imageio.ImageTypeSpecifier;
+-import javax.imageio.metadata.IIOMetadata;
+-import javax.imageio.spi.ImageReaderSpi;
+-import javax.imageio.stream.ImageInputStream;
+-import com.sun.medialib.codec.jiio.Constants;
+-import com.sun.medialib.codec.jiio.mediaLibImage;
+-
+-// XXX Need to verify compliance of all methods with ImageReader specificaiton.
+-public abstract class CLibImageReader extends ImageReader {
+- // The current image index.
+- private int currIndex = -1;
+-
+- // The position of the byte after the last byte read so far.
+- private long highWaterMark = Long.MIN_VALUE;
+-
+- // An ArrayList
of Long
s indicating the stream
+- // positions of the start of each image. Entries are added as needed.
+- private ArrayList imageStartPosition = new ArrayList();
+-
+- // The number of images in the stream, if known, otherwise -1.
+- private int numImages = -1;
+-
+- // The image returned by the codecLib Decoder.
+- private mediaLibImage mlibImage = null;
+-
+- // The index of the cached image.
+- private int mlibImageIndex = -1;
+-
+- /**
+- * Returns true if and only if both arguments are null or
+- * both are non-null and have the same length and content.
+- */
+- private static boolean subBandsMatch(int[] sourceBands,
+- int[] destinationBands) {
+- if(sourceBands == null && destinationBands == null) {
+- return true;
+- } else if(sourceBands != null && destinationBands != null) {
+- if (sourceBands.length != destinationBands.length) {
+- // Shouldn't happen ...
+- return false;
+- }
+- for (int i = 0; i < sourceBands.length; i++) {
+- if (sourceBands[i] != destinationBands[i]) {
+- return false;
+- }
+- }
+- return true;
+- }
+-
+- return false;
+- }
+-
+- /**
+- * Creates a ImageTypeSpecifier
corresponding to a
+- * mediaLibImage
. The mediaLibImage
is
+- * assumed always to be either bilevel-packed (MLIB_BIT) or
+- * pixel interleaved in the order ((G|I)|RGB)[A] where 'I' indicates
+- * an index as for palette images.
+- */
+- protected static final ImageTypeSpecifier
+- createImageType(mediaLibImage mlImage,
+- ColorSpace colorSpace,
+- int bitDepth,
+- byte[] redPalette,
+- byte[] greenPalette,
+- byte[] bluePalette,
+- byte[] alphaPalette) throws IOException {
+-
+- // Get the mediaLibImage attributes.
+- int mlibType = mlImage.getType();
+- int mlibWidth = mlImage.getWidth();
+- int mlibHeight = mlImage.getHeight();
+- int mlibBands = mlImage.getChannels();
+- int mlibStride = mlImage.getStride();
+-
+- // Convert mediaLib type to Java2D type.
+- int dataType;
+- switch(mlibType) {
+- case Constants.MLIB_BIT:
+- case Constants.MLIB_BYTE:
+- dataType = DataBuffer.TYPE_BYTE;
+- break;
+- case Constants.MLIB_SHORT:
+- case Constants.MLIB_USHORT:
+- // Deliberately cast MLIB_SHORT to TYPE_USHORT.
+- dataType = DataBuffer.TYPE_USHORT;
+- break;
+- default:
+- throw new UnsupportedOperationException
+- (I18N.getString("Generic0")+" "+mlibType);
+- }
+-
+- // Set up the SampleModel.
+- SampleModel sampleModel = null;
+- if(mlibType == Constants.MLIB_BIT) {
+- // Bilevel-packed
+- sampleModel =
+- new MultiPixelPackedSampleModel(dataType,
+- mlibWidth,
+- mlibHeight,
+- 1,
+- mlibStride,
+- mlImage.getBitOffset());
+- } else {
+- // Otherwise has to be interleaved in the order ((G|I)|RGB)[A].
+- int[] bandOffsets = new int[mlibBands];
+- for(int i = 0; i < mlibBands; i++) {
+- bandOffsets[i] = i;
+- }
+-
+- sampleModel =
+- new PixelInterleavedSampleModel(dataType,
+- mlibWidth,
+- mlibHeight,
+- mlibBands,
+- mlibStride,
+- bandOffsets);
+- }
+-
+- // Set up the ColorModel.
+- ColorModel colorModel = null;
+- if(mlibBands == 1 &&
+- redPalette != null &&
+- greenPalette != null &&
+- bluePalette != null &&
+- redPalette.length == greenPalette.length &&
+- redPalette.length == bluePalette.length) {
+-
+- // Indexed image.
+- int paletteLength = redPalette.length;
+- if(alphaPalette != null) {
+- if(alphaPalette.length != paletteLength) {
+- byte[] alphaTmp = new byte[paletteLength];
+- if(alphaPalette.length > paletteLength) {
+- System.arraycopy(alphaPalette, 0,
+- alphaTmp, 0, paletteLength);
+- } else { // alphaPalette.length < paletteLength
+- System.arraycopy(alphaPalette, 0,
+- alphaTmp, 0, alphaPalette.length);
+- for(int i = alphaPalette.length; i < paletteLength; i++) {
+- alphaTmp[i] = (byte)255; // Opaque.
+- }
+- }
+- alphaPalette = alphaTmp;
+- }
+-
+- colorModel = new IndexColorModel(bitDepth, //XXX 8
+- paletteLength,
+- redPalette,
+- greenPalette,
+- bluePalette,
+- alphaPalette);
+- } else {
+- colorModel = new IndexColorModel(bitDepth, //XXX 8
+- paletteLength,
+- redPalette,
+- greenPalette,
+- bluePalette);
+- }
+- } else if(mlibType == Constants.MLIB_BIT) {
+- // Bilevel image with no palette: assume black-is-zero.
+- byte[] cmap = new byte[] { (byte)0x00, (byte)0xFF };
+- colorModel = new IndexColorModel(1, 2, cmap, cmap, cmap);
+- } else {
+- // Set the color space and the alpha flag.
+- ColorSpace cs;
+- boolean hasAlpha;
+- if(colorSpace != null &&
+- (colorSpace.getNumComponents() == mlibBands ||
+- colorSpace.getNumComponents() == mlibBands - 1)) {
+- // Use the provided ColorSpace.
+- cs = colorSpace;
+-
+- // Set alpha if numBands == numColorComponents + 1.
+- hasAlpha = colorSpace.getNumComponents() != mlibBands;
+- } else {
+- // RGB if more than 2 bands.
+- cs = ColorSpace.getInstance(mlibBands < 3 ?
+- ColorSpace.CS_GRAY :
+- ColorSpace.CS_sRGB);
+-
+- // Alpha if band count is even.
+- hasAlpha = mlibBands % 2 == 0;
+- }
+-
+- // All bands have same depth.
+- int[] bits = new int[mlibBands];
+- for(int i = 0; i < mlibBands; i++) {
+- bits[i] = bitDepth;
+- }
+-
+- colorModel =
+- new ComponentColorModel(cs,
+- bits,
+- hasAlpha,
+- false,
+- hasAlpha ?
+- Transparency.TRANSLUCENT :
+- Transparency.OPAQUE,
+- dataType);
+- }
+-
+- return new ImageTypeSpecifier(colorModel, sampleModel);
+- }
+-
+- private static final void subsample(Raster src, int subX, int subY,
+- WritableRaster dst) {
+- int sx0 = src.getMinX();
+- int sy0 = src.getMinY();
+- int sw = src.getWidth();
+- int syUB = sy0 + src.getHeight();
+-
+- int dx0 = dst.getMinX();
+- int dy0 = dst.getMinY();
+- int dw = dst.getWidth();
+-
+- int b = src.getSampleModel().getNumBands();
+- int t = src.getSampleModel().getDataType();
+-
+- int numSubSamples = (sw + subX - 1)/subX;
+-
+- if(t == DataBuffer.TYPE_FLOAT || t == DataBuffer.TYPE_DOUBLE) {
+- float[] fsamples = new float[sw];
+- float[] fsubsamples = new float[numSubSamples];
+-
+- for(int k = 0; k < b; k++) {
+- for(int sy = sy0, dy = dy0; sy < syUB; sy += subY, dy++) {
+- src.getSamples(sx0, sy, sw, 1, k, fsamples);
+- for(int i = 0, s = 0; i < sw; s++, i += subX) {
+- fsubsamples[s] = fsamples[i];
+- }
+- dst.setSamples(dx0, dy, dw, 1, k, fsubsamples);
+- }
+- }
+- } else {
+- int[] samples = new int[sw];
+- int[] subsamples = new int[numSubSamples];
+-
+- for(int k = 0; k < b; k++) {
+- for(int sy = sy0, dy = dy0; sy < syUB; sy += subY, dy++) {
+- src.getSamples(sx0, sy, sw, 1, k, samples);
+- for(int i = 0, s = 0; i < sw; s++, i += subX) {
+- subsamples[s] = samples[i];
+- }
+- dst.setSamples(dx0, dy, dw, 1, k, subsamples);
+- }
+- }
+- }
+- }
+-
+- protected CLibImageReader(ImageReaderSpi originatingProvider) {
+- super(originatingProvider);
+- }
+-
+- /**
+- * An Iterator
over a single element.
+- */
+- private class SoloIterator implements Iterator {
+- Object theObject;
+-
+- SoloIterator(Object o) {
+- if(o == null) {
+- new IllegalArgumentException
+- (I18N.getString("CLibImageReader0"));
+- }
+- theObject = o;
+- }
+-
+- public boolean hasNext() {
+- return theObject != null;
+- }
+-
+- public Object next() {
+- if(theObject == null) {
+- throw new NoSuchElementException();
+- }
+- Object theNextObject = theObject;
+- theObject = null;
+- return theNextObject;
+- }
+-
+- public void remove() {
+- throw new UnsupportedOperationException();
+- }
+- }
+-
+- // Stores the location of the image at the specified index in the
+- // imageStartPosition List.
+- private int locateImage(int imageIndex) throws IIOException {
+- if (imageIndex < 0) {
+- throw new IndexOutOfBoundsException("imageIndex < 0!");
+- }
+-
+- try {
+- // Find closest known index (which can be -1 if none read before).
+- int index = Math.min(imageIndex, imageStartPosition.size() - 1);
+-
+- ImageInputStream stream = (ImageInputStream)input;
+-
+- // Seek unless at beginning of stream
+- if(index >= 0) { // index == -1
+- if(index == imageIndex) {
+- // Seek to previously identified position and return.
+- Long l = (Long)imageStartPosition.get(index);
+- stream.seek(l.longValue());
+- return imageIndex;
+- } else if(highWaterMark >= 0) {
+- // index >= imageStartPosition.size()
+- // Seek to first unread byte.
+- stream.seek(highWaterMark);
+- }
+- }
+-
+- // Get the reader SPI.
+- ImageReaderSpi provider = getOriginatingProvider();
+-
+- // Search images until at desired index or last image found.
+- do {
+- try {
+- if(provider.canDecodeInput(stream)) {
+- // Append the image position.
+- long offset = stream.getStreamPosition();
+- imageStartPosition.add(new Long(offset));
+- } else {
+- return index;
+- }
+- } catch(IOException e) {
+- // Ignore it.
+- return index;
+- }
+-
+- // Incrememt the index.
+- if(++index == imageIndex) break;
+-
+- // Skip the image.
+- if(!skipImage()) return index - 1;
+- } while(true);
+- } catch (IOException e) {
+- throw new IIOException("IOException", e);
+- }
+-
+- currIndex = imageIndex;
+-
+- return imageIndex;
+- }
+-
+- // Verify that imageIndex is in bounds and find the image position.
+- protected void seekToImage(int imageIndex) throws IIOException {
+- // Check lower bound.
+- if (imageIndex < minIndex) {
+- throw new IndexOutOfBoundsException("imageIndex < minIndex!");
+- }
+-
+- // Update lower bound if cannot seek back.
+- if (seekForwardOnly) {
+- minIndex = imageIndex;
+- }
+-
+- // Locate the image.
+- int index = locateImage(imageIndex);
+-
+- // If the located is not the one sought => exception.
+- if (index != imageIndex) {
+- throw new IndexOutOfBoundsException("imageIndex out of bounds!");
+- }
+- }
+-
+- /**
+- * Skip the current image. If possible subclasses should override
+- * this method with a more efficient implementation.
+- *
+- * @return Whether the image was successfully skipped.
+- */
+- protected boolean skipImage() throws IOException {
+- boolean retval = false;
+-
+- if(input == null) {
+- throw new IllegalStateException("input == null");
+- }
+- InputStream stream = null;
+- if(input instanceof ImageInputStream) {
+- stream = new InputStreamAdapter((ImageInputStream)input);
+- } else {
+- throw new IllegalArgumentException
+- ("!(input instanceof ImageInputStream)");
+- }
+-
+- retval = decode(stream) != null;
+-
+- if(retval) {
+- long pos = ((ImageInputStream)input).getStreamPosition();
+- if(pos > highWaterMark) {
+- highWaterMark = pos;
+- }
+- }
+-
+- return retval;
+- }
+-
+- /**
+- * Decodes an image from the supplied InputStream
.
+- */
+- protected abstract mediaLibImage decode(InputStream stream)
+- throws IOException;
+-
+- /**
+- * Returns the value of the private mlibImage
instance
+- * variable initializing it first if it is null
.
+- */
+- protected synchronized mediaLibImage getImage(int imageIndex)
+- throws IOException {
+- if(mlibImage == null || imageIndex != mlibImageIndex) {
+- if(input == null) {
+- throw new IllegalStateException("input == null");
+- }
+- seekToImage(imageIndex);
+- InputStream stream = null;
+- if(input instanceof ImageInputStream) {
+- stream = new InputStreamAdapter((ImageInputStream)input);
+- } else {
+- throw new IllegalArgumentException
+- ("!(input instanceof ImageInputStream)");
+- }
+- mlibImage = decode(stream);
+- if(mlibImage != null) {
+- mlibImageIndex = imageIndex;
+- long pos = ((ImageInputStream)input).getStreamPosition();
+- if(pos > highWaterMark) {
+- highWaterMark = pos;
+- }
+- } else { // mlibImage == null
+- mlibImageIndex = -1;
+- }
+- }
+- return mlibImage;
+- }
+-
+- /**
+- * Returns the index of the image cached in the private
+- * mlibImage
instance variable or -1 if no
+- * image is currently cached.
+- */
+- protected int getImageIndex() {
+- return mlibImageIndex;
+- }
+-
+- public int getNumImages(boolean allowSearch) throws IOException {
+- if (input == null) {
+- throw new IllegalStateException("input == null");
+- }
+- if (seekForwardOnly && allowSearch) {
+- throw new IllegalStateException
+- ("seekForwardOnly && allowSearch!");
+- }
+-
+- if (numImages > 0) {
+- return numImages;
+- }
+- if (allowSearch) {
+- this.numImages = locateImage(Integer.MAX_VALUE) + 1;
+- }
+- return numImages;
+- }
+-
+- public int getWidth(int imageIndex) throws IOException {
+- seekToImage(imageIndex);
+-
+- return getImage(imageIndex).getWidth();
+- }
+-
+- public int getHeight(int imageIndex) throws IOException {
+- seekToImage(imageIndex);
+-
+- return getImage(imageIndex).getHeight();
+- }
+-
+- public IIOMetadata getStreamMetadata() throws IOException {
+- return null;
+- }
+-
+- public IIOMetadata getImageMetadata(int imageIndex) throws IOException {
+- seekToImage(imageIndex);
+-
+- return null;
+- }
+-
+- public synchronized BufferedImage read(int imageIndex,
+- ImageReadParam param)
+- throws IOException {
+-
+- processImageStarted(imageIndex);
+-
+- seekToImage(imageIndex);
+-
+- processImageProgress(0.0F);
+- processImageProgress(0.5F);
+-
+- ImageTypeSpecifier rawImageType = getRawImageType(imageIndex);
+-
+- processImageProgress(0.95F);
+-
+- mediaLibImage mlImage = getImage(imageIndex);
+- int dataOffset = mlImage.getOffset();
+-
+- SampleModel rawSampleModel = rawImageType.getSampleModel();
+-
+- DataBuffer db;
+- int smType = rawSampleModel.getDataType();
+- switch(smType) {
+- case DataBuffer.TYPE_BYTE:
+- byte[] byteData = mlImage.getType() == mediaLibImage.MLIB_BIT ?
+- mlImage.getBitData() : mlImage.getByteData();
+- db = new DataBufferByte(byteData,
+- byteData.length - dataOffset,
+- dataOffset);
+- break;
+- case DataBuffer.TYPE_USHORT:
+- // Deliberately cast MLIB_SHORT to TYPE_USHORT.
+- short[] shortData = mlImage.getShortData();
+- if(shortData == null) {
+- shortData = mlImage.getUShortData();
+- }
+- db = new DataBufferUShort(shortData,
+- shortData.length - dataOffset,
+- dataOffset);
+- break;
+- default:
+- throw new UnsupportedOperationException
+- (I18N.getString("Generic0")+" "+smType);
+- }
+-
+- WritableRaster rawRaster =
+- Raster.createWritableRaster(rawSampleModel, db, null);
+-
+- ColorModel rawColorModel = rawImageType.getColorModel();
+-
+- BufferedImage image =
+- new BufferedImage(rawColorModel,
+- rawRaster,
+- rawColorModel.isAlphaPremultiplied(),
+- null); // XXX getDestination()?
+-
+- Rectangle destRegion = new Rectangle(image.getWidth(),
+- image.getHeight());
+- int[] destinationBands = null;
+- int subX = 1;
+- int subY = 1;
+-
+- if(param != null) {
+- BufferedImage destination = param.getDestination();
+- destinationBands = param.getDestinationBands();
+- Point destinationOffset = param.getDestinationOffset();
+- int[] sourceBands = param.getSourceBands();
+- Rectangle sourceRegion = param.getSourceRegion();
+- subX = param.getSourceXSubsampling();
+- subY = param.getSourceYSubsampling();
+-
+- boolean isNominal =
+- destination == null &&
+- destinationBands == null &
+- destinationOffset.x == 0 && destinationOffset.y == 0 &&
+- sourceBands == null &&
+- sourceRegion == null &&
+- subX == 1 && subY == 1;
+-
+- if(!isNominal) {
+- int srcWidth = image.getWidth();
+- int srcHeight = image.getHeight();
+-
+- if(destination == null) {
+- destination = getDestination(param,
+- getImageTypes(imageIndex),
+- srcWidth,
+- srcHeight);
+- }
+-
+- checkReadParamBandSettings(param,
+- image.getSampleModel().getNumBands(),
+- destination.getSampleModel().getNumBands());
+-
+- Rectangle srcRegion = new Rectangle();
+- computeRegions(param, srcWidth, srcHeight, destination,
+- srcRegion, destRegion);
+-
+- WritableRaster dst =
+- destination.getWritableTile(0, 0).createWritableChild(
+- destRegion.x, destRegion.y,
+- destRegion.width, destRegion.height,
+- destRegion.x, destRegion.y,
+- destinationBands);
+-
+- if(subX != 1 || subY != 1) { // Subsampling
+- WritableRaster src =
+- image.getWritableTile(0, 0).createWritableChild(
+- srcRegion.x, srcRegion.y,
+- srcRegion.width, srcRegion.height,
+- srcRegion.x, srcRegion.y,
+- sourceBands);
+- subsample(src, subX, subY, dst);
+- } else { // No subsampling
+- WritableRaster src =
+- image.getWritableTile(0, 0).createWritableChild(
+- srcRegion.x, srcRegion.y,
+- srcRegion.width, srcRegion.height,
+- destRegion.x, destRegion.y,
+- sourceBands);
+- dst.setRect(src);
+- }
+-
+- image = destination;
+- } else if(param.getDestinationType() != null) {
+- // Check for image type other than raw image type.
+- ImageTypeSpecifier destImageType = param.getDestinationType();
+- ColorSpace rawColorSpace = rawColorModel.getColorSpace();
+- ColorSpace destColorSpace =
+- destImageType.getColorModel().getColorSpace();
+- if(!destColorSpace.equals(rawColorSpace) ||
+- !destImageType.equals(rawImageType)) {
+- // Look for destination type in legal types list.
+- Iterator imageTypes = getImageTypes(imageIndex);
+- boolean isLegalType = false;
+- while(imageTypes.hasNext()) {
+- ImageTypeSpecifier imageType =
+- (ImageTypeSpecifier)imageTypes.next();
+- if(imageType.equals(destImageType)) {
+- isLegalType = true;
+- break;
+- }
+- }
+-
+- if(isLegalType) {
+- // Set the destination raster.
+- WritableRaster raster;
+- if(rawSampleModel.equals(destImageType.getSampleModel())) {
+- // Re-use the raw raster.
+- raster = rawRaster;
+- } else {
+- // Create a new raster and copy the data.
+- SampleModel sm = destImageType.getSampleModel();
+- raster = Raster.createWritableRaster(sm, null);
+- raster.setRect(rawRaster);
+- }
+-
+- // Replace the output image.
+- ColorModel cm = destImageType.getColorModel();
+- image = new BufferedImage(cm,
+- raster,
+- cm.isAlphaPremultiplied(),
+- null);
+- }
+- }
+- }
+- }
+-
+- processImageUpdate(image,
+- destRegion.x, destRegion.y,
+- destRegion.width, destRegion.height,
+- subX, subY, destinationBands);
+-
+- processImageProgress(1.0F);
+- processImageComplete();
+-
+- return image;
+- }
+-
+- public void reset() {
+- resetLocal();
+- super.reset();
+- }
+-
+- protected void resetLocal() {
+- currIndex = -1;
+- highWaterMark = Long.MIN_VALUE;
+- imageStartPosition.clear();
+- numImages = -1;
+- mlibImage = null;
+- mlibImageIndex = -1;
+- }
+-
+- public void setInput(Object input,
+- boolean seekForwardOnly,
+- boolean ignoreMetadata) {
+- super.setInput(input, seekForwardOnly, ignoreMetadata);
+- if (input != null) {
+- // Check the class type.
+- if (!(input instanceof ImageInputStream)) {
+- throw new IllegalArgumentException
+- ("!(input instanceof ImageInputStream)");
+- }
+- }
+- resetLocal();
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/clib/CLibImageWriter.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/clib/CLibImageWriter.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/clib/CLibImageWriter.java 2007-02-06 17:14:59.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/clib/CLibImageWriter.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,818 +0,0 @@
+-/*
+- * $RCSfile: CLibImageWriter.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.6 $
+- * $Date: 2007/02/06 22:14:59 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.clib;
+-
+-import java.awt.Point;
+-import java.awt.Rectangle;
+-import java.awt.color.ColorSpace;
+-import java.awt.geom.AffineTransform;
+-import java.awt.image.AffineTransformOp;
+-import java.awt.image.ColorModel;
+-import java.awt.image.ComponentSampleModel;
+-import java.awt.image.DataBuffer;
+-import java.awt.image.DataBufferByte;
+-import java.awt.image.DataBufferUShort;
+-import java.awt.image.IndexColorModel;
+-import java.awt.image.MultiPixelPackedSampleModel;
+-import java.awt.image.PixelInterleavedSampleModel;
+-import java.awt.image.Raster;
+-import java.awt.image.RenderedImage;
+-import java.awt.image.SampleModel;
+-import java.awt.image.SinglePixelPackedSampleModel;
+-import java.awt.image.WritableRaster;
+-import java.io.IOException;
+-import javax.imageio.IIOImage;
+-import javax.imageio.ImageWriter;
+-import javax.imageio.ImageWriteParam;
+-import javax.imageio.ImageTypeSpecifier;
+-import javax.imageio.metadata.IIOMetadata;
+-import javax.imageio.spi.ImageWriterSpi;
+-import com.sun.medialib.codec.jiio.Constants;
+-import com.sun.medialib.codec.jiio.mediaLibImage;
+-
+-public abstract class CLibImageWriter extends ImageWriter {
+- /**
+- * Returns the data array from the DataBuffer
.
+- */
+- private static final Object getDataBufferData(DataBuffer db) {
+- Object data;
+-
+- int dType = db.getDataType();
+- switch (dType) {
+- case DataBuffer.TYPE_BYTE:
+- data = ((DataBufferByte)db).getData();
+- break;
+- case DataBuffer.TYPE_USHORT:
+- data = ((DataBufferUShort)db).getData();
+- break;
+- default:
+- throw new IllegalArgumentException
+- (I18N.getString("Generic0")+" "+dType);
+- }
+-
+- return data;
+- }
+-
+- /**
+- * Returns the mediaLib type enum given the Java2D type enum.
+- */
+- private static final int getMediaLibDataType(int dataType) {
+- int mlibType;
+-
+- switch (dataType) {
+- case DataBuffer.TYPE_BYTE:
+- mlibType = mediaLibImage.MLIB_BYTE;
+- break;
+- case DataBuffer.TYPE_USHORT:
+- mlibType = mediaLibImage.MLIB_USHORT;
+- break;
+- default:
+- throw new IllegalArgumentException
+- (I18N.getString("Generic0")+" "+dataType);
+- }
+-
+- return mlibType;
+- }
+-
+- /**
+- * Returns the mediaLib format enum given the SampleModel
+- * and ColorModel
of an image. If the format cannot be
+- * determined to be anything more specific, the value
+- * Constants.MLIB_FORMAT_UNKNOWN
will be returned.
+- *
+- * @param sampleModel The SampleModel
describing the
+- * layout of the DataBuffer
; may be null
.
+- * @param colorModel The ColorModel
describing the
+- * mapping of the samples in a pixel to a color.
+- *
+- * @throws IllegalArgumentExcaption if sampleModel
is
+- * null
.
+- *
+- * @return One of the Constants.MLIB_FORMAT
constants.
+- */
+- private static final int getMediaLibFormat(SampleModel sampleModel,
+- ColorModel colorModel) {
+- if(sampleModel == null) {
+- throw new IllegalArgumentException("sampleModel == null!");
+- }
+-
+- int mlibFormat = Constants.MLIB_FORMAT_UNKNOWN;
+-
+- if(sampleModel instanceof SinglePixelPackedSampleModel &&
+- sampleModel.getNumBands() == 4 &&
+- colorModel != null &&
+- colorModel.hasAlpha()) {
+- int[] masks =
+- ((SinglePixelPackedSampleModel)sampleModel).getBitMasks();
+- if(masks[3] == 0xff000000) {
+- if(masks[0] == 0xff &&
+- masks[1] == 0xff00 &&
+- masks[2] == 0xff0000) {
+- mlibFormat = Constants.MLIB_FORMAT_PACKED_ABGR;
+- } else if(masks[0] == 0xff0000 &&
+- masks[1] == 0xff00 &&
+- masks[2] == 0xff) {
+- mlibFormat = Constants.MLIB_FORMAT_PACKED_ARGB;
+- }
+- }
+- } else if(sampleModel instanceof ComponentSampleModel) {
+- ComponentSampleModel csm = (ComponentSampleModel)sampleModel;
+- int bandOffsets[] = csm.getBandOffsets();
+- int pixelStride = csm.getPixelStride();
+-
+- if (pixelStride == bandOffsets.length) {
+- int numBands = pixelStride; // for clarity
+-
+- boolean hasOneBank = true;
+- int bankIndices[] = csm.getBankIndices();
+- for (int i = 1; i < bankIndices.length; i++) {
+- if(bankIndices[i] != bankIndices[0]) {
+- hasOneBank = false;
+- }
+- }
+-
+- if(hasOneBank) {
+- if(colorModel instanceof IndexColorModel) {
+- mlibFormat = Constants.MLIB_FORMAT_INDEXED;
+- } else if(numBands == 1) {
+- mlibFormat = Constants.MLIB_FORMAT_GRAYSCALE;
+- } else if(numBands == 2 &&
+- bandOffsets[0] == 0 &&
+- bandOffsets[1] == 1) {
+- mlibFormat = Constants.MLIB_FORMAT_GRAYSCALE_ALPHA;
+- } else if(numBands == 3) {
+- int csType = colorModel != null ?
+- colorModel.getColorSpace().getType() :
+- ColorSpace.TYPE_RGB;
+- if(csType == ColorSpace.TYPE_RGB) {
+- if(bandOffsets[0] == 2 &&
+- bandOffsets[1] == 1 &&
+- bandOffsets[2] == 0) {
+- mlibFormat = Constants.MLIB_FORMAT_BGR;
+- } else if(bandOffsets[0] == 0 &&
+- bandOffsets[1] == 1 &&
+- bandOffsets[2] == 2) {
+- mlibFormat = Constants.MLIB_FORMAT_RGB;
+- }
+- } else if(csType == ColorSpace.TYPE_Yxy &&
+- bandOffsets[0] == 0 &&
+- bandOffsets[1] == 1 &&
+- bandOffsets[2] == 2) {
+- mlibFormat = Constants.MLIB_FORMAT_YCC;
+- }
+- } else if(numBands == 4) {
+- int csType = colorModel != null ?
+- colorModel.getColorSpace().getType() :
+- ColorSpace.TYPE_RGB;
+- if(csType == ColorSpace.TYPE_RGB) {
+- if(bandOffsets[3] == 0) {
+- if(bandOffsets[0] == 3 &&
+- bandOffsets[1] == 2 &&
+- bandOffsets[2] == 1) {
+- mlibFormat = Constants.MLIB_FORMAT_ABGR;
+- } else if(bandOffsets[0] == 1 &&
+- bandOffsets[1] == 2 &&
+- bandOffsets[2] == 3) {
+- mlibFormat = Constants.MLIB_FORMAT_ARGB;
+- }
+- } else if(bandOffsets[3] == 3) {
+- if(bandOffsets[0] == 0 &&
+- bandOffsets[1] == 1 &&
+- bandOffsets[2] == 2) {
+- mlibFormat = Constants.MLIB_FORMAT_RGBA;
+- } else if(bandOffsets[0] == 2 &&
+- bandOffsets[1] == 1 &&
+- bandOffsets[2] == 0) {
+- mlibFormat = Constants.MLIB_FORMAT_BGRA;
+- }
+- }
+- } else if(csType == ColorSpace.TYPE_CMYK &&
+- bandOffsets[0] == 0 &&
+- bandOffsets[1] == 1 &&
+- bandOffsets[2] == 2 &&
+- bandOffsets[3] == 3) {
+- mlibFormat = Constants.MLIB_FORMAT_CMYK;
+- } else if(csType == ColorSpace.TYPE_Yxy &&
+- bandOffsets[0] == 0 &&
+- bandOffsets[1] == 1 &&
+- bandOffsets[2] == 2 &&
+- bandOffsets[3] == 3) {
+- if(colorModel != null &&
+- colorModel.hasAlpha()) {
+- mlibFormat = Constants.MLIB_FORMAT_YCCA;
+- } else {
+- mlibFormat = Constants.MLIB_FORMAT_YCCK;
+- }
+- }
+- }
+- }
+- }
+- }
+-
+- return mlibFormat;
+- }
+-
+- /**
+- * Returns a contiguous Raster
of data over the specified
+- * Rectangle
. If the region is a sub-region of a single
+- * tile, then a child of that tile will be returned. If the region
+- * overlaps more than one tile and has 8 bits per sample, then a
+- * pixel interleaved Raster having band offsets 0,1,... will be returned.
+- * Otherwise the Raster returned by im.copyData(null)
will
+- * be returned.
+- */
+- private static final Raster getContiguousData(RenderedImage im,
+- Rectangle region) {
+- if(im == null) {
+- throw new IllegalArgumentException("im == null");
+- } else if(region == null) {
+- throw new IllegalArgumentException("region == null");
+- }
+-
+- Raster raster;
+- if(im.getNumXTiles() == 1 && im.getNumYTiles() == 1) {
+- // Image is not tiled so just get a reference to the tile.
+- raster = im.getTile(im.getMinTileX(), im.getMinTileY());
+-
+- // Ensure result has requested coverage.
+- Rectangle bounds = raster.getBounds();
+- if (!bounds.equals(region)) {
+- raster = raster.createChild(region.x, region.y,
+- region.width, region.height,
+- region.x, region.y,
+- null);
+- }
+- } else {
+- // Image is tiled.
+-
+- // Create an interleaved raster for copying for 8-bit case.
+- // This ensures that for RGB data the band offsets are {0,1,2}.
+- SampleModel sampleModel = im.getSampleModel();
+- WritableRaster target = sampleModel.getSampleSize(0) == 8 ?
+- Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE,
+- im.getWidth(),
+- im.getHeight(),
+- sampleModel.getNumBands(),
+- new Point(im.getMinX(),
+- im.getMinY())) :
+- null;
+-
+- // Copy the data.
+- raster = im.copyData(target);
+- }
+-
+- return raster;
+- }
+-
+- /**
+- * Subsamples and sub-bands the input Raster
over a
+- * sub-region and stores the result in a WritableRaster
.
+- *
+- * @param src The source Raster
+- * @param sourceBands The source bands to use; may be null
+- * @param subsampleX The subsampling factor along the horizontal axis.
+- * @param subsampleY The subsampling factor along the vertical axis.
+- * in which case all bands will be used.
+- * @param dst The destination WritableRaster
.
+- * @throws IllegalArgumentException if source
is
+- * null
or empty, dst
is null
,
+- * sourceBands.length
exceeds the number of bands in
+- * source
, or sourcBands
contains an element
+- * which is negative or greater than or equal to the number of bands
+- * in source
.
+- */
+- private static void reformat(Raster source,
+- int[] sourceBands,
+- int subsampleX,
+- int subsampleY,
+- WritableRaster dst) {
+- // Check for nulls.
+- if(source == null) {
+- throw new IllegalArgumentException("source == null!");
+- } else if(dst == null) {
+- throw new IllegalArgumentException("dst == null!");
+- }
+-
+- // Validate the source bounds. XXX is this needed?
+- Rectangle sourceBounds = source.getBounds();
+- if(sourceBounds.isEmpty()) {
+- throw new IllegalArgumentException
+- ("source.getBounds().isEmpty()!");
+- }
+-
+- // Check sub-banding.
+- boolean isSubBanding = false;
+- int numSourceBands = source.getSampleModel().getNumBands();
+- if(sourceBands != null) {
+- if(sourceBands.length > numSourceBands) {
+- throw new IllegalArgumentException
+- ("sourceBands.length > numSourceBands!");
+- }
+-
+- boolean isRamp = sourceBands.length == numSourceBands;
+- for(int i = 0; i < sourceBands.length; i++) {
+- if(sourceBands[i] < 0 || sourceBands[i] >= numSourceBands) {
+- throw new IllegalArgumentException
+- ("sourceBands[i] < 0 || sourceBands[i] >= numSourceBands!");
+- } else if(sourceBands[i] != i) {
+- isRamp = false;
+- }
+- }
+-
+- isSubBanding = !isRamp;
+- }
+-
+- // Allocate buffer for a single source row.
+- int sourceWidth = sourceBounds.width;
+- int[] pixels = new int[sourceWidth*numSourceBands];
+-
+- // Initialize variables used in loop.
+- int sourceX = sourceBounds.x;
+- int sourceY = sourceBounds.y;
+- int numBands = sourceBands != null ?
+- sourceBands.length : numSourceBands;
+- int dstWidth = dst.getWidth();
+- int dstYMax = dst.getHeight() - 1;
+- int copyFromIncrement = numSourceBands*subsampleX;
+-
+- // Loop over source rows, subsample each, and store in destination.
+- for(int dstY = 0; dstY <= dstYMax; dstY++) {
+- // Read one row.
+- source.getPixels(sourceX, sourceY, sourceWidth, 1, pixels);
+-
+- // Copy within the same buffer by left shifting.
+- if(isSubBanding) {
+- int copyFrom = 0;
+- int copyTo = 0;
+- for(int i = 0; i < dstWidth; i++) {
+- for(int j = 0; j < numBands; j++) {
+- pixels[copyTo++] = pixels[copyFrom + sourceBands[j]];
+- }
+- copyFrom += copyFromIncrement;
+- }
+- } else {
+- int copyFrom = copyFromIncrement;
+- int copyTo = numSourceBands;
+- // Start from index 1 as no need to copy the first pixel.
+- for(int i = 1; i < dstWidth; i++) {
+- int k = copyFrom;
+- for(int j = 0; j < numSourceBands; j++) {
+- pixels[copyTo++] = pixels[k++];
+- }
+- copyFrom += copyFromIncrement;
+- }
+- }
+-
+- // Set the destionation row.
+- dst.setPixels(0, dstY, dstWidth, 1, pixels);
+-
+- // Increment the source row.
+- sourceY += subsampleY;
+- }
+- }
+-
+- protected CLibImageWriter(ImageWriterSpi originatingProvider) {
+- super(originatingProvider);
+- }
+-
+- public IIOMetadata convertImageMetadata(IIOMetadata inData,
+- ImageTypeSpecifier imageType,
+- ImageWriteParam param) {
+- return null;
+- }
+-
+- public IIOMetadata convertStreamMetadata(IIOMetadata inData,
+- ImageWriteParam param) {
+- return null;
+- }
+-
+- public IIOMetadata
+- getDefaultImageMetadata(ImageTypeSpecifier imageType,
+- ImageWriteParam param) {
+- return null;
+- }
+-
+- public IIOMetadata getDefaultStreamMetadata(ImageWriteParam param) {
+- return null;
+- }
+-
+- /* XXX
+- protected int getSignificantBits(RenderedImage image) {
+- SampleModel sampleModel = image.getSampleModel();
+- int numBands = sampleModel.getNumBands();
+- int[] sampleSize = sampleModel.getSampleSize();
+- int significantBits = sampleSize[0];
+- for(int i = 1; i < numBands; i++) {
+- significantBits = Math.max(significantBits, sampleSize[i]);
+- }
+-
+- return significantBits;
+- }
+- */
+-
+- // Code copied from ImageReader.java with ImageReadParam replaced
+- // by ImageWriteParam.
+- private static final Rectangle getSourceRegion(ImageWriteParam param,
+- int sourceMinX,
+- int sourceMinY,
+- int srcWidth,
+- int srcHeight) {
+- Rectangle sourceRegion =
+- new Rectangle(sourceMinX, sourceMinY, srcWidth, srcHeight);
+- if (param != null) {
+- Rectangle region = param.getSourceRegion();
+- if (region != null) {
+- sourceRegion = sourceRegion.intersection(region);
+- }
+-
+- int subsampleXOffset = param.getSubsamplingXOffset();
+- int subsampleYOffset = param.getSubsamplingYOffset();
+- sourceRegion.x += subsampleXOffset;
+- sourceRegion.y += subsampleYOffset;
+- sourceRegion.width -= subsampleXOffset;
+- sourceRegion.height -= subsampleYOffset;
+- }
+-
+- return sourceRegion;
+- }
+-
+- /**
+- * Returns a mediaLibImage
for a specific encoder to use
+- * to encode image
.
+- *
+- * @param image The image to encode.
+- * @param param The write parameters.
+- * @param allowBilevel Whether bilevel images are allowed. A bilevel
+- * image must have one 1-bit sample per pixel, have data type
+- * DataBuffer.TYE_BYTE
, and have a
+- * MultiPixelPackedSampleModel
.
+- * @param supportedFormats An array containing constan values from
+- * the set of mediaLibImage.MLIB_FORMAT
enums.
+- *
+- * @throws IllegalArgumentException if supportedFormats
+- * is null
.
+- *
+- * @return A mediaLibImage in a format capable of being written
+- * by the encoder.
+- */
+- protected mediaLibImage getMediaLibImage(RenderedImage image,
+- ImageWriteParam param,
+- boolean allowBilevel,
+- int[] supportedFormats) {
+- if(supportedFormats == null) {
+- throw new IllegalArgumentException("supportedFormats == null!");
+- }
+-
+- // Determine the source region.
+- Rectangle sourceRegion = getSourceRegion(param,
+- image.getMinX(),
+- image.getMinY(),
+- image.getWidth(),
+- image.getHeight());
+-
+- if(sourceRegion.isEmpty()) {
+- throw new IllegalArgumentException("sourceRegion.isEmpty()");
+- }
+-
+- // Check whether reformatting is necessary to conform to mediaLib
+- // image format (packed bilevel if allowed or ((G|I)|(RGB))[A]).
+-
+- // Flag indicating need to reformat data.
+- boolean reformatData = false;
+-
+- // Flag indicating bilevel data.
+- boolean isBilevel = false;
+-
+- // Value indicating the mediaLib image format.
+- int mediaLibFormat = Constants.MLIB_FORMAT_UNKNOWN;
+-
+- // Get the SampleModel.
+- SampleModel sampleModel = image.getSampleModel();
+-
+- // Get the number of bands.
+- int numSourceBands = sampleModel.getNumBands();
+-
+- // Get the source sub-banding array.
+- int[] sourceBands = param != null ? param.getSourceBands() : null;
+-
+- // Check for non-nominal sub-banding.
+- int numBands;
+- if(sourceBands != null) {
+- numBands = sourceBands.length;
+- if(numBands != numSourceBands) {
+- // The number of bands must be the same.
+- reformatData = true;
+- } else {
+- // The band order must not change.
+- for(int i = 0; i < numSourceBands; i++) {
+- if(sourceBands[i] != i) {
+- reformatData = true;
+- break;
+- }
+- }
+- }
+- } else {
+- numBands = numSourceBands;
+- }
+-
+- // If sub-banding does not dictate reformatting, check subsampling..
+- if(!reformatData && param != null &&
+- (param.getSourceXSubsampling() != 1 ||
+- param.getSourceXSubsampling() != 1)) {
+- reformatData = true;
+- }
+-
+- // If sub-banding does not dictate reformatting check SampleModel.
+- if(!reformatData) {
+- if(allowBilevel &&
+- sampleModel.getNumBands() == 1 &&
+- sampleModel.getSampleSize(0) == 1 &&
+- sampleModel instanceof MultiPixelPackedSampleModel &&
+- sampleModel.getDataType() == DataBuffer.TYPE_BYTE) {
+- // Need continguous packed bits.
+- MultiPixelPackedSampleModel mppsm =
+- (MultiPixelPackedSampleModel)sampleModel;
+- if(mppsm.getPixelBitStride() == 1) {
+- isBilevel = true;
+- } else {
+- reformatData = true;
+- }
+- } else {
+- // Set the mediaLib format flag.
+- mediaLibFormat = getMediaLibFormat(sampleModel,
+- image.getColorModel());
+-
+- // Set the data reformatting flag.
+- reformatData = true;
+- int len = supportedFormats.length;
+- for(int i = 0; i < len; i++) {
+- if(mediaLibFormat == supportedFormats[i]) {
+- reformatData = false;
+- break;
+- }
+- }
+- }
+- }
+-
+- // Variable for the eventual destination data.
+- Raster raster = null;
+-
+- if(reformatData) {
+- // Determine the maximum bit depth.
+- int[] sampleSize = sampleModel.getSampleSize();
+- int bitDepthMax = sampleSize[0];
+- for(int i = 1; i < numSourceBands; i++) {
+- bitDepthMax = Math.max(bitDepthMax, sampleSize[i]);
+- }
+-
+- // Set the data type as a function of bit depth.
+- int dataType;
+- if(bitDepthMax <= 8) {
+- dataType = DataBuffer.TYPE_BYTE;
+- } else if(bitDepthMax <= 16) {
+- dataType = DataBuffer.TYPE_USHORT;
+- } else {
+- throw new UnsupportedOperationException
+- (I18N.getString("CLibImageWriter0")+" "+bitDepthMax);
+- }
+-
+- // Determine the width and height.
+- int width;
+- int height;
+- if(param != null) {
+- int subsampleX = param.getSourceXSubsampling();
+- int subsampleY = param.getSourceYSubsampling();
+- width = (sourceRegion.width + subsampleX - 1)/subsampleX;
+- height = (sourceRegion.height + subsampleY - 1)/subsampleY;
+- } else {
+- width = sourceRegion.width;
+- height = sourceRegion.height;
+- }
+-
+- // Load a ramp for band offsets.
+- int[] newBandOffsets = new int[numBands];
+- for(int i = 0; i < numBands; i++) {
+- newBandOffsets[i] = i;
+- }
+-
+- // Create a new SampleModel.
+- SampleModel newSampleModel;
+- if(allowBilevel &&
+- sampleModel.getNumBands() == 1 &&
+- bitDepthMax == 1) {
+- // Bilevel image.
+- newSampleModel =
+- new MultiPixelPackedSampleModel(dataType,
+- width,
+- height,
+- 1);
+- isBilevel = true;
+- } else {
+- // Pixel interleaved image.
+- newSampleModel =
+- new PixelInterleavedSampleModel(dataType,
+- width,
+- height,
+- newBandOffsets.length,
+- width*numSourceBands,
+- newBandOffsets);
+- }
+-
+- // Create a new Raster at (0,0).
+- WritableRaster newRaster =
+- Raster.createWritableRaster(newSampleModel, null);
+-
+- // Populate the new Raster.
+- if(param != null &&
+- (param.getSourceXSubsampling() != 1 ||
+- param.getSourceXSubsampling() != 1)) {
+- // Subsampling, possibly with sub-banding.
+- reformat(getContiguousData(image, sourceRegion),
+- sourceBands,
+- param.getSourceXSubsampling(),
+- param.getSourceYSubsampling(),
+- newRaster);
+- } else if(sourceBands == null &&
+- image.getSampleModel().getClass().isInstance
+- (newSampleModel) &&
+- newSampleModel.getTransferType() ==
+- image.getSampleModel().getTransferType()) {
+- // Neither subsampling nor sub-banding.
+- WritableRaster translatedChild =
+- newRaster.createWritableTranslatedChild(sourceRegion.x,
+- sourceRegion.y);
+- // Use copyData() to avoid potentially cobbling the entire
+- // source region into an extra Raster via getData().
+- image.copyData(translatedChild);
+- } else {
+- // Cannot use copyData() so use getData() to retrieve and
+- // possibly sub-band the source data and use setRect().
+- WritableRaster translatedChild =
+- newRaster.createWritableTranslatedChild(sourceRegion.x,
+- sourceRegion.y);
+- Raster sourceRaster = getContiguousData(image, sourceRegion);
+- if(sourceBands != null) {
+- // Copy only the requested bands.
+- sourceRaster =
+- sourceRaster.createChild(sourceRegion.x,
+- sourceRegion.y,
+- sourceRegion.width,
+- sourceRegion.height,
+- sourceRegion.x,
+- sourceRegion.y,
+- sourceBands);
+- }
+-
+- // Get the region from the image and set it into the Raster.
+- translatedChild.setRect(sourceRaster);
+- }
+-
+- // Replace Raster and SampleModel.
+- raster = newRaster;
+- sampleModel = newRaster.getSampleModel();
+- } else { // !reformatData
+- // No reformatting needed.
+- raster = getContiguousData(image, sourceRegion).createTranslatedChild(0, 0);
+- sampleModel = raster.getSampleModel();
+-
+- // Update mediaLibFormat indicator in case getContiguousData()
+- // has changed the layout of the data.
+- mediaLibFormat = getMediaLibFormat(sampleModel, image.getColorModel());
+- }
+-
+- // The mediaLib image.
+- mediaLibImage mlibImage = null;
+-
+- // Create a mediaLibImage with reference to the Raster data.
+- if(isBilevel) {
+- // Bilevel image: either is was already bilevel or was
+- // formatted to bilevel.
+-
+- MultiPixelPackedSampleModel mppsm =
+- ((MultiPixelPackedSampleModel)sampleModel);
+-
+- // Get the line stride.
+- int stride = mppsm.getScanlineStride();
+-
+- // Determine the offset to the start of the data.
+- int offset =
+- raster.getDataBuffer().getOffset() -
+- raster.getSampleModelTranslateY()*stride -
+- raster.getSampleModelTranslateX()/8 +
+- mppsm.getOffset(0, 0);
+-
+- // Get a reference to the internal data array.
+- Object bitData = getDataBufferData(raster.getDataBuffer());
+-
+- mlibImage = new mediaLibImage(mediaLibImage.MLIB_BIT,
+- 1,
+- raster.getWidth(),
+- raster.getHeight(),
+- stride,
+- offset,
+- (byte)mppsm.getBitOffset(0),
+- bitData);
+- } else {
+- // If the image is not bilevel then it has to be component.
+- ComponentSampleModel csm = (ComponentSampleModel)sampleModel;
+-
+- // Set the mediaLib data type
+- int mlibDataType = getMediaLibDataType(sampleModel.getDataType());
+-
+- // Get a reference to the internal data array.
+- Object data = getDataBufferData(raster.getDataBuffer());
+-
+- // Get the line stride.
+- int stride = csm.getScanlineStride();
+-
+- // Determine the offset of the first sample from the offset
+- // indicated by the (x,y) coordinates. This offset is the
+- // minimum valued offset, not the offset of, e.g., red (index 0)
+- // as the Raster is by now in a contiguous format that
+- // the encoder is guaranteed to handle regardless of whether
+- // the smallest offset is to the, e.g., red band.
+- int[] bandOffsets = csm.getBandOffsets();
+- int minBandOffset = bandOffsets[0];
+- for(int i = 1; i < bandOffsets.length; i++) {
+- if(bandOffsets[i] < minBandOffset) {
+- minBandOffset = bandOffsets[i];
+- }
+- }
+-
+- // Determine the offset to the start of the data. The
+- // sampleModelTranslate parameters are the translations from
+- // Raster to SampleModel coordinates and must be subtracted
+- // from the Raster coordinates.
+- int offset =
+- (raster.getMinY() -
+- raster.getSampleModelTranslateY())*stride +
+- (raster.getMinX() -
+- raster.getSampleModelTranslateX())*numSourceBands +
+- minBandOffset;
+-
+- // Create the image.
+- mlibImage =
+- !reformatData &&
+- mediaLibFormat != Constants.MLIB_FORMAT_UNKNOWN ?
+- new mediaLibImage(mlibDataType,
+- numSourceBands,
+- raster.getWidth(),
+- raster.getHeight(),
+- stride,
+- offset,
+- mediaLibFormat,
+- data) :
+- new mediaLibImage(mlibDataType,
+- numSourceBands,
+- raster.getWidth(),
+- raster.getHeight(),
+- stride,
+- offset,
+- data);
+- }
+-
+- return mlibImage;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/clib/I18N.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/clib/I18N.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/clib/I18N.java 2005-02-11 00:01:27.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/clib/I18N.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,53 +0,0 @@
+-/*
+- * $RCSfile: I18N.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:27 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.clib;
+-
+-import com.sun.media.imageioimpl.common.I18NImpl;
+-
+-final class I18N extends I18NImpl {
+- static String getString(String key) {
+- return getString("com.sun.media.imageioimpl.plugins.clib.I18N", key);
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/clib/InputStreamAdapter.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/clib/InputStreamAdapter.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/clib/InputStreamAdapter.java 2005-02-11 00:01:28.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/clib/InputStreamAdapter.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,94 +0,0 @@
+-/*
+- * $RCSfile: InputStreamAdapter.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:28 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.clib;
+-
+-import java.io.IOException;
+-import java.io.InputStream;
+-import javax.imageio.stream.ImageInputStream;
+-
+-/**
+- */
+-public final class InputStreamAdapter extends InputStream {
+-
+- ImageInputStream stream;
+-
+- public InputStreamAdapter(ImageInputStream stream) {
+- super();
+-
+- this.stream = stream;
+- }
+-
+- public void close() throws IOException {
+- stream.close();
+- }
+-
+- public void mark(int readlimit) {
+- stream.mark();
+- }
+-
+- public boolean markSupported() {
+- return true;
+- }
+-
+- public int read() throws IOException {
+- return stream.read();
+- }
+-
+- public int read(byte b[], int off, int len) throws IOException {
+- return stream.read(b, off, len);
+- }
+-
+- public void reset() throws IOException {
+- stream.reset();
+- }
+-
+- public long skip(long n) throws IOException {
+- return stream.skipBytes(n);
+- }
+-
+- public ImageInputStream getWrappedStream() {
+- return stream;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/clib/OutputStreamAdapter.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/clib/OutputStreamAdapter.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/clib/OutputStreamAdapter.java 2005-02-11 00:01:28.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/clib/OutputStreamAdapter.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,78 +0,0 @@
+-/*
+- * $RCSfile: OutputStreamAdapter.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:28 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.clib;
+-
+-import java.io.IOException;
+-import java.io.OutputStream;
+-import javax.imageio.stream.ImageOutputStream;
+-
+-/**
+- */
+-public final class OutputStreamAdapter extends OutputStream {
+-
+- ImageOutputStream stream;
+-
+- public OutputStreamAdapter(ImageOutputStream stream) {
+- super();
+-
+- this.stream = stream;
+- }
+-
+- public void close() throws IOException {
+- stream.close();
+- }
+-
+- public void write(byte[] b) throws IOException {
+- stream.write(b);
+- }
+-
+- public void write(byte[] b, int off, int len) throws IOException {
+- stream.write(b, off, len);
+- }
+-
+- public void write(int b) throws IOException {
+- stream.write(b);
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/clib/properties zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/clib/properties
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/clib/properties 2005-02-11 00:01:28.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/clib/properties 1969-12-31 19:00:00.000000000 -0500
+@@ -1,16 +0,0 @@
+-#
+-# $RCSfile: properties,v $
+-#
+-# Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
+-#
+-# Use is subject to license terms.
+-#
+-# $Revision: 1.1 $
+-# $Date: 2005/02/11 05:01:28 $
+-# $State: Exp $
+-#
+-# Internationalization file for com.sun.media.imageioimpl.plugins.clib
+-
+-Generic0=Unsupported data type
+-CLibImageReader0=Parameter may not be null.
+-CLibImageWriter0=Unsupported data depth
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg/CLibJPEGImageReader.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg/CLibJPEGImageReader.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg/CLibJPEGImageReader.java 2006-04-24 16:53:01.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg/CLibJPEGImageReader.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,352 +0,0 @@
+-/*
+- * $RCSfile: CLibJPEGImageReader.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.10 $
+- * $Date: 2006/04/24 20:53:01 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg;
+-
+-import java.awt.color.ColorSpace;
+-import java.awt.color.ICC_ColorSpace;
+-import java.awt.color.ICC_Profile;
+-import java.awt.image.BufferedImage;
+-import java.awt.image.ColorModel;
+-import java.awt.image.DataBuffer;
+-import java.awt.image.MultiPixelPackedSampleModel;
+-import java.awt.image.PixelInterleavedSampleModel;
+-import java.awt.image.SampleModel;
+-import java.io.File;
+-import java.io.FileInputStream;
+-import java.io.InputStream;
+-import java.io.IOException;
+-import java.util.ArrayList;
+-import java.util.HashMap;
+-import java.util.Iterator;
+-import javax.imageio.IIOException;
+-import javax.imageio.IIOImage;
+-import javax.imageio.ImageReader;
+-import javax.imageio.ImageReadParam;
+-import javax.imageio.ImageTypeSpecifier;
+-import javax.imageio.metadata.IIOMetadata;
+-import javax.imageio.spi.ImageReaderSpi;
+-import javax.imageio.stream.ImageInputStream;
+-import com.sun.media.imageioimpl.common.InvertedCMYKColorSpace;
+-import com.sun.media.imageioimpl.plugins.clib.CLibImageReader;
+-import com.sun.media.imageioimpl.plugins.clib.InputStreamAdapter;
+-import com.sun.medialib.codec.jpeg.Decoder;
+-import com.sun.medialib.codec.jiio.mediaLibImage;
+-
+-final class CLibJPEGImageReader extends CLibImageReader {
+- private static final boolean DEBUG = false; // XXX false for release
+-
+- private mediaLibImage infoImage = null;
+- private int infoImageIndex = -1;
+- private byte[] iccProfileData = null;
+- private IIOMetadata imageMetadata = null;
+- private int imageMetadataIndex = -1;
+- private HashMap imageTypes = new HashMap();
+- private int bitDepth; // XXX Should depend on imageIndex.
+-
+- CLibJPEGImageReader(ImageReaderSpi originatingProvider) {
+- super(originatingProvider);
+- }
+-
+- // Implement abstract method defined in superclass.
+- protected final synchronized mediaLibImage decode(InputStream stream)
+- throws IOException {
+- if(DEBUG) System.out.println("In decode()");
+-
+- mediaLibImage mlImage = null;
+- Decoder decoder = null;
+- try {
+- if(stream instanceof InputStreamAdapter) {
+- ImageInputStream iis =
+- ((InputStreamAdapter)stream).getWrappedStream();
+- decoder = new Decoder(iis);
+- } else {
+- decoder = new Decoder(stream);
+- }
+- //decoder.setType(Decoder.JPEG_TYPE_UNKNOWN);
+- mlImage = decoder.decode(null);
+-
+- // Set the ICC profile data.
+- iccProfileData = decoder.getEmbeddedICCProfile();
+-
+- // If there is a profile need to invert the data if they
+- // are YCCK or CMYK originally.
+- if(iccProfileData != null &&
+- mlImage.getType() == mediaLibImage.MLIB_BYTE) {
+- int format = mlImage.getFormat();
+- if(format == mediaLibImage.MLIB_FORMAT_CMYK ||
+- format == mediaLibImage.MLIB_FORMAT_YCCK) {
+- long t0 = System.currentTimeMillis();
+- byte[] data = mlImage.getByteData();
+- int len = data.length;
+- for(int i = mlImage.getOffset(); i < len; i++) {
+- data[i] = (byte)(255 - data[i]&0xff);
+- }
+- }
+- }
+-
+- } catch(Throwable t) {
+- throw new IIOException("codecLib error", t);
+- }
+-
+- if(mlImage == null) {
+- throw new IIOException(I18N.getString("CLibJPEGImageReader0"));
+- }
+-
+- // Set variable indicating bit depth.
+- try {
+- bitDepth = decoder.getDepth();
+- } catch(Throwable t) {
+- throw new IIOException("codecLib error", t);
+- }
+-
+- // Free native resources.
+- decoder.dispose();
+-
+- if(DEBUG) {
+- System.out.println("type = "+mlImage.getType());
+- System.out.println("channels = "+mlImage.getChannels());
+- System.out.println("width = "+mlImage.getWidth());
+- System.out.println("height = "+mlImage.getHeight());
+- System.out.println("stride = "+mlImage.getStride());
+- System.out.println("offset = "+mlImage.getOffset());
+- System.out.println("bitOffset = "+mlImage.getBitOffset());
+- System.out.println("format = "+mlImage.getFormat());
+- }
+-
+- return mlImage;
+- }
+-
+- // Retrieve mediaLibImage containing everything except possibly the
+- // decoded image data. If the real image has already been decoded
+- // then it will be returned.
+- private synchronized mediaLibImage getInfoImage(int imageIndex)
+- throws IOException {
+- if(DEBUG) System.out.println("In getInfoImage()");
+- if(infoImage == null || imageIndex != infoImageIndex) {
+- // Use the cached image if it has the correct index.
+- if(imageIndex == getImageIndex()) {
+- if(DEBUG) {
+- System.out.println("Using cached image.");
+- }
+- infoImage = getImage(imageIndex);
+- infoImageIndex = imageIndex;
+- return infoImage;
+- }
+-
+- if(input == null) {
+- throw new IllegalStateException("input == null");
+- }
+-
+- // Check the input and set local variable.
+- ImageInputStream iis = null;
+- if(input instanceof ImageInputStream) {
+- iis = (ImageInputStream)input;
+- } else {
+- throw new IllegalArgumentException
+- ("!(input instanceof ImageInputStream)");
+- }
+-
+- seekToImage(imageIndex);
+-
+- // Mark the input.
+- iis.mark();
+-
+- Decoder decoder = null;
+- try {
+- // Create the decoder
+- decoder = new Decoder(iis);
+-
+- // Set the informational image.
+- infoImage = decoder.getSize();
+-
+- // Set the ICC profile data.
+- iccProfileData = decoder.getEmbeddedICCProfile();
+- } catch(Throwable t) {
+- throw new IIOException("codecLib error", t);
+- }
+-
+- // XXX The lines marked "XXX" are a workaround for getSize()
+- // not correctly setting the format of infoImage.
+- if(infoImage == null ||
+- (infoImage.getFormat() == // XXX
+- mediaLibImage.MLIB_FORMAT_UNKNOWN && // XXX
+- ((infoImage = getImage(imageIndex)) == null))) { // XXX
+- throw new IIOException(I18N.getString("CLibJPEGImageReader0"));
+- }
+-
+- infoImageIndex = imageIndex;
+-
+- try {
+- // Set variable indicating bit depth.
+- bitDepth = decoder.getDepth();
+- } catch(Throwable t) {
+- throw new IIOException("codecLib error", t);
+- }
+-
+- // Reset the input to the marked position.
+- iis.reset();
+-
+- // Free native resources.
+- decoder.dispose();
+-
+- if(DEBUG) {
+- System.out.println("type = "+infoImage.getType());
+- System.out.println("channels = "+infoImage.getChannels());
+- System.out.println("width = "+infoImage.getWidth());
+- System.out.println("height = "+infoImage.getHeight());
+- System.out.println("stride = "+infoImage.getStride());
+- System.out.println("offset = "+infoImage.getOffset());
+- System.out.println("bitOffset = "+infoImage.getBitOffset());
+- System.out.println("format = "+infoImage.getFormat());
+- }
+- }
+-
+- return infoImage;
+- }
+-
+- public int getWidth(int imageIndex) throws IOException {
+- if(DEBUG) System.out.println("In getWidth()");
+-
+- return getInfoImage(imageIndex).getWidth();
+- }
+-
+- public int getHeight(int imageIndex) throws IOException {
+- if(DEBUG) System.out.println("In getHeight()");
+-
+- return getInfoImage(imageIndex).getHeight();
+- }
+-
+- public Iterator getImageTypes(int imageIndex) throws IOException {
+- if(DEBUG) System.out.println("In getImageTypes()");
+- seekToImage(imageIndex);
+-
+- ArrayList types = null;
+- synchronized(imageTypes) {
+- Integer key = new Integer(imageIndex);
+- if(imageTypes.containsKey(key)) {
+- types = (ArrayList)imageTypes.get(key);
+- } else {
+- types = new ArrayList();
+-
+- // Get the informational image.
+- mediaLibImage mlImage = getInfoImage(imageIndex);
+-
+- ColorSpace cs;
+-
+- // Add profile-based type if an ICC profile is present.
+- if(iccProfileData != null) {
+- ICC_Profile profile =
+- ICC_Profile.getInstance(iccProfileData);
+- cs = new ICC_ColorSpace(profile);
+- types.add(createImageType(mlImage, cs, bitDepth,
+- null, null, null, null));
+- }
+-
+- // Add a standard type.
+- cs = mlImage.getFormat() == mediaLibImage.MLIB_FORMAT_CMYK ?
+- InvertedCMYKColorSpace.getInstance() : null;
+- types.add(createImageType(mlImage, cs, bitDepth,
+- null, null, null, null));
+- }
+- }
+-
+- return types.iterator();
+- }
+-
+- public synchronized IIOMetadata getImageMetadata(int imageIndex)
+- throws IOException {
+- if(input == null) {
+- throw new IllegalStateException("input == null");
+- }
+-
+- if(imageMetadata == null || imageIndex != imageMetadataIndex) {
+- seekToImage(imageIndex);
+-
+- ImageInputStream stream = (ImageInputStream)input;
+- long pos = stream.getStreamPosition();
+-
+- try {
+- imageMetadata = new CLibJPEGMetadata(stream);
+- imageMetadataIndex = imageIndex;
+- } catch(IIOException e) {
+- throw e;
+- } finally {
+- stream.seek(pos);
+- }
+- }
+-
+- return imageMetadata;
+- }
+-
+- // Override thumbnail methods.
+-
+- public boolean readerSupportsThumbnails() {
+- return true;
+- }
+-
+- public int getNumThumbnails(int imageIndex) throws IOException {
+- CLibJPEGMetadata metadata =
+- (CLibJPEGMetadata)getImageMetadata(imageIndex);
+- return metadata.getNumThumbnails();
+- }
+-
+- public BufferedImage readThumbnail(int imageIndex,
+- int thumbnailIndex) throws IOException {
+- CLibJPEGMetadata metadata =
+- (CLibJPEGMetadata)getImageMetadata(imageIndex);
+- return metadata.getThumbnail(thumbnailIndex);
+- }
+-
+- // Override superclass method.
+- protected void resetLocal() {
+- infoImage = null;
+- infoImageIndex = -1;
+- iccProfileData = null;
+- imageMetadata = null;
+- imageMetadataIndex = -1;
+- imageTypes.clear();
+- super.resetLocal();
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg/CLibJPEGImageReaderSpi.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg/CLibJPEGImageReaderSpi.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg/CLibJPEGImageReaderSpi.java 2006-04-24 16:53:01.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg/CLibJPEGImageReaderSpi.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,169 +0,0 @@
+-/*
+- * $RCSfile: CLibJPEGImageReaderSpi.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.4 $
+- * $Date: 2006/04/24 20:53:01 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg;
+-
+-import java.util.Arrays;
+-import java.util.Iterator;
+-import java.util.List;
+-import java.util.Locale;
+-import javax.imageio.spi.ImageReaderSpi;
+-import javax.imageio.spi.ServiceRegistry;
+-import javax.imageio.stream.ImageInputStream;
+-import java.io.IOException;
+-import javax.imageio.ImageReader;
+-import javax.imageio.IIOException;
+-import com.sun.media.imageioimpl.common.PackageUtil;
+-import com.sun.media.imageioimpl.common.ImageUtil;
+-
+-public class CLibJPEGImageReaderSpi extends ImageReaderSpi {
+-
+- private static final String[] names =
+- {"jpeg", "JPEG", "jpg", "JPG", "jfif", "JFIF",
+- "jpeg-lossless", "JPEG-LOSSLESS", "jpeg-ls", "JPEG-LS"};
+-
+- private static final String[] suffixes = {"jpeg", "jpg", "jfif", "jls"};
+-
+- private static final String[] MIMETypes = {"image/jpeg"};
+-
+- private static final String readerClassName =
+- "com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageReader";
+-
+- private static final String[] writerSpiNames = {
+- "com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageWriterSpi"
+- };
+-
+- private boolean registered = false;
+-
+- public CLibJPEGImageReaderSpi() {
+- super(PackageUtil.getVendor(),
+- PackageUtil.getVersion(),
+- names,
+- suffixes,
+- MIMETypes,
+- readerClassName,
+- STANDARD_INPUT_TYPE,
+- writerSpiNames,
+- false, // supportsStandardStreamMetadataFormat
+- null, // nativeStreamMetadataFormatName
+- null, // nativeStreamMetadataFormatClassName
+- null, // extraStreamMetadataFormatNames
+- null, // extraStreamMetadataFormatClassNames
+- true, // supportsStandardImageMetadataFormat
+- CLibJPEGMetadata.NATIVE_FORMAT,
+- CLibJPEGMetadata.NATIVE_FORMAT_CLASS,
+- new String[] {CLibJPEGMetadata.TIFF_FORMAT},
+- new String[] {CLibJPEGMetadata.TIFF_FORMAT_CLASS});
+- }
+-
+- public void onRegistration(ServiceRegistry registry,
+- Class category) {
+- if (registered) {
+- return;
+- }
+-
+- registered = true;
+-
+- // Branch as a function of codecLib availability.
+- if(!PackageUtil.isCodecLibAvailable()) {
+- // Deregister provider.
+- registry.deregisterServiceProvider(this);
+- } else {
+-
+- List list =
+- ImageUtil.getJDKImageReaderWriterSPI(registry, "JPEG", true);
+-
+- for (int i=0; i
null
.
+- * @throws IllegalArgumentException if the source does is not indexed.
+- */
+- private static BufferedImage convertTo3BandRGB(RenderedImage im) {
+- // Check parameter.
+- if(im == null) {
+- throw new IllegalArgumentException("im == null");
+- }
+-
+- ColorModel cm = im.getColorModel();
+- if(!(cm instanceof IndexColorModel)) {
+- throw new IllegalArgumentException
+- ("!(im.getColorModel() instanceof IndexColorModel)");
+- }
+-
+- Raster src;
+- if(im.getNumXTiles() == 1 && im.getNumYTiles() == 1) {
+- // Image is not tiled so just get a reference to the tile.
+- src = im.getTile(im.getMinTileX(), im.getMinTileY());
+-
+- if (src.getWidth() != im.getWidth() ||
+- src.getHeight() != im.getHeight()) {
+- src = src.createChild(src.getMinX(), src.getMinY(),
+- im.getWidth(), im.getHeight(),
+- src.getMinX(), src.getMinY(),
+- null);
+- }
+- } else {
+- // Image is tiled so need to get a contiguous raster.
+- src = im.getData();
+- }
+-
+- // This is probably not the most efficient approach given that
+- // the mediaLibImage will eventually need to be in component form.
+- BufferedImage dst =
+- ((IndexColorModel)cm).convertToIntDiscrete(src, false);
+-
+- if(dst.getSampleModel().getNumBands() == 4) {
+- //
+- // Without copying data create a BufferedImage which has
+- // only the RGB bands, not the alpha band.
+- //
+- WritableRaster rgbaRas = dst.getRaster();
+- WritableRaster rgbRas =
+- rgbaRas.createWritableChild(0, 0,
+- dst.getWidth(), dst.getHeight(),
+- 0, 0,
+- new int[] {0, 1, 2});
+- PackedColorModel pcm = (PackedColorModel)dst.getColorModel();
+- int bits =
+- pcm.getComponentSize(0) +
+- pcm.getComponentSize(1) +
+- pcm.getComponentSize(2);
+- DirectColorModel dcm = new DirectColorModel(bits,
+- pcm.getMask(0),
+- pcm.getMask(1),
+- pcm.getMask(2));
+- dst = new BufferedImage(dcm, rgbRas, false, null);
+- }
+-
+- return dst;
+- }
+-
+- CLibJPEGImageWriter(ImageWriterSpi originatingProvider)
+- throws IOException {
+- super(originatingProvider);
+-
+- try {
+- encoder = new Encoder();
+- encoder.setExtend(Encoder.JPEG_IMAGE_NONEXTENDED);
+- } catch(Throwable t) {
+- throw new IIOException("codecLib error", t);
+- }
+- }
+-
+- public ImageWriteParam getDefaultWriteParam() {
+- return new CLibJPEGImageWriteParam(getLocale());
+- }
+-
+- public void write(IIOMetadata streamMetadata,
+- IIOImage image,
+- ImageWriteParam param) throws IOException {
+- if(output == null) {
+- throw new IllegalStateException("output == null");
+- }
+-
+- OutputStream stream = null;
+- if(output instanceof ImageOutputStream) {
+- stream = new OutputStreamAdapter((ImageOutputStream)output);
+- } else {
+- throw new IllegalArgumentException
+- ("!(output instanceof ImageOutputStream)");
+- }
+-
+- RenderedImage renderedImage = image.getRenderedImage();
+-
+- if(renderedImage.getColorModel() instanceof IndexColorModel) {
+- renderedImage = convertTo3BandRGB(renderedImage);
+- }
+-
+- // Test for all.
+- ImageUtil.canEncodeImage(this, renderedImage.getColorModel(),
+- renderedImage.getSampleModel());
+-
+- // Test for baseline.
+- int bitDepth = renderedImage.getColorModel().getComponentSize(0);
+- if((param == null ||
+- (param.getCompressionMode() == ImageWriteParam.MODE_EXPLICIT &&
+- !param.isCompressionLossless())) &&
+- bitDepth > 12) {
+- throw new IIOException
+- ("JPEG baseline encoding is limited to 12 bits: "+this);
+- }
+-
+- // Set compression mode and quality from ImageWriteParam, if any.
+- if(param != null &&
+- param.getCompressionMode() == ImageWriteParam.MODE_EXPLICIT) {
+- if(param.isCompressionLossless()) {
+- try {
+- if(bitDepth >= 2 && bitDepth <= 16 && bitDepth % 8 != 0) {
+- encoder.setDepth(bitDepth);
+- }
+- if(param.getCompressionType().equalsIgnoreCase
+- (CLibJPEGImageWriteParam.LOSSLESS_COMPRESSION_TYPE)) {
+- encoder.setMode(Encoder.JPEG_MODE_LOSSLESS);
+- } else {
+- encoder.setMode(Encoder.JPEG_MODE_HPLOCO);
+- }
+- } catch(Throwable t) {
+- throw new IIOException("codecLib error", t);
+- }
+- } else {
+- try {
+- encoder.setMode(Encoder.JPEG_MODE_BASELINE);
+- // XXX Q == 100 caused a core dump during testing.
+- encoder.setQuality((int)(param.getCompressionQuality()*100));
+- } catch(Throwable t) {
+- throw new IIOException("codecLib error", t);
+- }
+- }
+- } else {
+- try {
+- encoder.setMode(Encoder.JPEG_MODE_BASELINE);
+- encoder.setQuality(75);
+- } catch(Throwable t) {
+- throw new IIOException("codecLib error", t);
+- }
+- }
+-
+- int[] supportedFormats =
+- param == null ||
+- (param.getCompressionMode() == ImageWriteParam.MODE_EXPLICIT &&
+- !param.isCompressionLossless()) ?
+- new int [] {Constants.MLIB_FORMAT_GRAYSCALE,
+- Constants.MLIB_FORMAT_GRAYSCALE_ALPHA,
+- Constants.MLIB_FORMAT_BGR,
+- Constants.MLIB_FORMAT_RGB,
+- Constants.MLIB_FORMAT_CMYK } : // baseline
+- new int [] {Constants.MLIB_FORMAT_GRAYSCALE,
+- Constants.MLIB_FORMAT_RGB}; // lossless & LS
+- mediaLibImage mlibImage = getMediaLibImage(renderedImage,
+- param,
+- false,
+- supportedFormats);
+-
+- try {
+- if(mlibImage.getChannels() == 2) {
+- // GRAYSCALE_ALPHA
+- encoder.setType(Encoder.JPEG_TYPE_GRAYSCALE);
+- } else if(mlibImage.getChannels() == 4) {
+- // XXX The selection of CMYK (Adobe transform 0) or
+- // YCCK (Adobe transform 2) should probably be made
+- // on the basis of image metadata passed in so this
+- // code should be modified once the writer supports
+- // image metadata. Until then select CMYK type which
+- // will generate Adobe transform 0 and non-subsampled
+- // data.
+- if(mlibImage.getFormat() == Constants.MLIB_FORMAT_CMYK) {
+- // CMYK
+- encoder.setType(Encoder.JPEG_TYPE_CMYK);
+- } else if(mlibImage.getFormat() ==
+- Constants.MLIB_FORMAT_YCCK) {
+- // YCCK
+- encoder.setType(Encoder.JPEG_TYPE_YCCK);
+- }
+- }
+- encoder.encode(stream, mlibImage);
+- } catch(Throwable t) {
+- throw new IIOException("codecLib error", t);
+- }
+- }
+-}
+-
+-/**
+- * This differs from the core JPEG ImageWriteParam in that:
+- *
+- *
+- *
+- */
+-final class CLibJPEGImageWriteParam extends ImageWriteParam {
+- private static final float DEFAULT_COMPRESSION_QUALITY = 0.75F;
+-
+- static final String LOSSY_COMPRESSION_TYPE = "JPEG";
+- static final String LOSSLESS_COMPRESSION_TYPE = "JPEG-LOSSLESS";
+- static final String LS_COMPRESSION_TYPE = "JPEG-LS";
+-
+- private static final String[] compressionQualityDescriptions =
+- new String[] {
+- I18N.getString("CLibJPEGImageWriteParam0"),
+- I18N.getString("CLibJPEGImageWriteParam1"),
+- I18N.getString("CLibJPEGImageWriteParam2")
+- };
+-
+- CLibJPEGImageWriteParam(Locale locale) {
+- super(locale);
+-
+- canWriteCompressed = true;
+- compressionMode = MODE_EXPLICIT;
+- compressionQuality = DEFAULT_COMPRESSION_QUALITY;
+- compressionType = LOSSY_COMPRESSION_TYPE;
+- compressionTypes = new String[] {LOSSY_COMPRESSION_TYPE,
+- LOSSLESS_COMPRESSION_TYPE,
+- LS_COMPRESSION_TYPE};
+- }
+-
+- public String[] getCompressionQualityDescriptions() {
+- super.getCompressionQualityDescriptions(); // Performs checks.
+-
+- return compressionQualityDescriptions;
+- }
+-
+- public float[] getCompressionQualityValues() {
+- super.getCompressionQualityValues(); // Performs checks.
+-
+- return new float[] { 0.05F, // "Minimum useful"
+- 0.75F, // "Visually lossless"
+- 0.95F }; // "Maximum useful"
+- }
+-
+- public boolean isCompressionLossless() {
+- super.isCompressionLossless(); // Performs checks.
+-
+- return !compressionType.equalsIgnoreCase(LOSSY_COMPRESSION_TYPE);
+- }
+-
+- public void setCompressionMode(int mode) {
+- if(mode == MODE_DISABLED ||
+- mode == MODE_COPY_FROM_METADATA) {
+- throw new UnsupportedOperationException
+- ("mode == MODE_DISABLED || mode == MODE_COPY_FROM_METADATA");
+- }
+-
+- super.setCompressionMode(mode); // This sets the instance variable.
+- }
+-
+- public void unsetCompression() {
+- super.unsetCompression(); // Performs checks.
+-
+- compressionQuality = DEFAULT_COMPRESSION_QUALITY;
+- compressionType = LOSSY_COMPRESSION_TYPE;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg/CLibJPEGImageWriterSpi.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg/CLibJPEGImageWriterSpi.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg/CLibJPEGImageWriterSpi.java 2006-04-25 20:45:06.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg/CLibJPEGImageWriterSpi.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,179 +0,0 @@
+-/*
+- * $RCSfile: CLibJPEGImageWriterSpi.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.4 $
+- * $Date: 2006/04/26 00:45:06 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg;
+-
+-import java.awt.image.ColorModel;
+-import java.awt.image.IndexColorModel;
+-import java.awt.image.SampleModel;
+-import java.io.IOException;
+-import java.util.List;
+-import java.util.Locale;
+-import javax.imageio.ImageWriter;
+-import javax.imageio.ImageTypeSpecifier;
+-import javax.imageio.metadata.IIOMetadataFormat;
+-import javax.imageio.metadata.IIOMetadataFormatImpl;
+-import javax.imageio.spi.ImageWriterSpi;
+-import javax.imageio.spi.ServiceRegistry;
+-import com.sun.media.imageioimpl.common.PackageUtil;
+-import com.sun.media.imageioimpl.common.ImageUtil;
+-
+-/**
+- */
+-public class CLibJPEGImageWriterSpi extends ImageWriterSpi {
+-
+- private static final String[] names =
+- {"jpeg", "JPEG", "jpg", "JPG", "jfif", "JFIF",
+- "jpeg-lossless", "JPEG-LOSSLESS", "jpeg-ls", "JPEG-LS"};
+-
+- private static final String[] suffixes = {"jpeg", "jpg", "jfif", "jls"};
+-
+- private static final String[] MIMETypes = { "image/jpeg" };
+-
+- private static final String writerClassName =
+- "com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageWriter";
+-
+- private static final String[] readerSpiNames = {
+- "com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageReaderSpi"
+- };
+-
+- private boolean registered = false;
+-
+- public CLibJPEGImageWriterSpi() {
+- super(PackageUtil.getVendor(),
+- PackageUtil.getVersion(),
+- names,
+- suffixes,
+- MIMETypes,
+- writerClassName,
+- STANDARD_OUTPUT_TYPE,
+- readerSpiNames,
+- false,
+- null, null,
+- null, null,
+- false,
+- null, null,
+- null, null);
+- }
+-
+- public void onRegistration(ServiceRegistry registry,
+- Class category) {
+- if (registered) {
+- return;
+- }
+-
+- registered = true;
+-
+- // Branch as a function of codecLib availability.
+- if(!PackageUtil.isCodecLibAvailable()) {
+- // Deregister provider.
+- registry.deregisterServiceProvider(this);
+- } else {
+-
+- List list =
+- ImageUtil.getJDKImageReaderWriterSPI(registry, "JPEG", false);
+-
+- for (int i=0; iString
which contains
+- * only printable Latin-1 characters but not leading, trailing, or
+- * consecutive spaces.
+- *
+- * @param s the String
to convert.
+- * @return a printable Latin-1 String
sans superfluous spaces.
+- */
+- static String toPrintableLatin1(String s) {
+- // Pass a null right back.
+- if(s == null) return null;
+-
+- // Get Latin-1 characters.
+- byte[] data = null;
+- try {
+- data = s.getBytes("ISO-8859-1");
+- } catch(UnsupportedEncodingException e) {
+- // In theory this should not happen (assert).
+- data = s.getBytes();
+- }
+-
+- // Copy printable characters omitting leading spaces and
+- // all but first trailing space.
+- int len = 0;
+- int prev = 0;
+- for (int i = 0; i < data.length; i++) {
+- int d = data[i] & 0xFF;
+- if (prev == 32 && d == 32)
+- continue;
+- if ((d > 32 && d <=126) || (d >= 161 && d <=255) ||
+- (d == 32 && len != 0))
+- data[len++] = (byte)d;
+- prev = d;
+- }
+-
+- // Return an empty string if no acceptable characters.
+- if(len == 0) return "";
+-
+- // Omit trailing space, if any.
+- if(data[len - 1] == 32) len--;
+-
+- return new String(data, 0, len);
+- }
+-
+- public CLibPNGMetadata() {
+- super(true,
+- nativeMetadataFormatName,
+- nativeMetadataFormatClassName,
+- null, null);
+- }
+-
+- public CLibPNGMetadata(IIOMetadata metadata)
+- throws IIOInvalidTreeException {
+-
+- this();
+-
+- if(metadata != null) {
+- List formats = Arrays.asList(metadata.getMetadataFormatNames());
+-
+- if(formats.contains(nativeMetadataFormatName)) {
+- // Initialize from native image metadata format.
+- String format = nativeMetadataFormatName;
+- setFromTree(format, metadata.getAsTree(format));
+- } else if(metadata.isStandardMetadataFormatSupported()) {
+- // Initialize from standard metadata form of the input tree.
+- String format =
+- IIOMetadataFormatImpl.standardMetadataFormatName;
+- setFromTree(format, metadata.getAsTree(format));
+- }
+- }
+- }
+-
+- /**
+- * Sets the instance variables of the IHDR and if necessary PLTE and
+- * tRNS chunks. The numBands
parameter is necessary since
+- * we may only be writing a subset of the image bands.
+- */
+- public void initialize(ImageTypeSpecifier imageType,
+- int numBands,
+- ImageWriteParam param,
+- int interlaceMethod) {
+- ColorModel colorModel = imageType.getColorModel();
+- SampleModel sampleModel = imageType.getSampleModel();
+-
+- // Intialize IHDR_width and IHDR_height
+- IHDR_width = sampleModel.getWidth();
+- IHDR_height = sampleModel.getHeight();
+-
+- // Initialize IHDR_bitDepth
+- int[] sampleSize = sampleModel.getSampleSize();
+- int bitDepth = sampleSize[0];
+- // Choose max bit depth over all channels
+- // Fixes bug 4413109
+- for (int i = 1; i < sampleSize.length; i++) {
+- if (sampleSize[i] > bitDepth) {
+- bitDepth = sampleSize[i];
+- }
+- }
+- // Multi-channel images must have a bit depth of 8 or 16
+- if (sampleSize.length > 1 && bitDepth < 8) {
+- bitDepth = 8;
+- }
+-
+- // Round bit depth up to a power of 2
+- if (bitDepth > 2 && bitDepth < 4) {
+- bitDepth = 4;
+- } else if (bitDepth > 4 && bitDepth < 8) {
+- bitDepth = 8;
+- } else if (bitDepth > 8 && bitDepth < 16) {
+- bitDepth = 16;
+- } else if (bitDepth > 16) {
+- throw new RuntimeException("bitDepth > 16!");
+- }
+- IHDR_bitDepth = bitDepth;
+-
+- // Initialize IHDR_colorType
+- if (colorModel instanceof IndexColorModel) {
+- IndexColorModel icm = (IndexColorModel)colorModel;
+- int size = icm.getMapSize();
+-
+- byte[] reds = new byte[size];
+- icm.getReds(reds);
+- byte[] greens = new byte[size];
+- icm.getGreens(greens);
+- byte[] blues = new byte[size];
+- icm.getBlues(blues);
+-
+- // Determine whether the color tables are actually a gray ramp
+- // if the color type has not been set previously
+- boolean isGray = false;
+- if (!IHDR_present ||
+- (IHDR_colorType != PNG_COLOR_PALETTE)) {
+- isGray = true;
+- int scale = 255/((1 << IHDR_bitDepth) - 1);
+- for (int i = 0; i < size; i++) {
+- byte red = reds[i];
+- if ((red != (byte)(i*scale)) ||
+- (red != greens[i]) ||
+- (red != blues[i])) {
+- isGray = false;
+- break;
+- }
+- }
+- }
+-
+- // Determine whether transparency exists
+- boolean hasAlpha = colorModel.hasAlpha();
+-
+- byte[] alpha = null;
+- if (hasAlpha) {
+- alpha = new byte[size];
+- icm.getAlphas(alpha);
+- }
+-
+- if (isGray && hasAlpha) {
+- IHDR_colorType = PNG_COLOR_GRAY_ALPHA;
+- } else if (isGray) {
+- IHDR_colorType = PNG_COLOR_GRAY;
+- } else {
+- IHDR_colorType = PNG_COLOR_PALETTE;
+-
+- // Initialize PLTE chunk
+- PLTE_present = true;
+- PLTE_red = (byte[])reds.clone();
+- PLTE_green = (byte[])greens.clone();
+- PLTE_blue = (byte[])blues.clone();
+-
+- if (hasAlpha) {
+- // Initialize tRNS chunk
+- tRNS_present = true;
+- tRNS_colorType = PNG_COLOR_PALETTE;
+- tRNS_alpha = (byte[])alpha.clone();
+- }
+- }
+- } else {
+- if (numBands == 1) {
+- IHDR_colorType = PNG_COLOR_GRAY;
+- } else if (numBands == 2) {
+- IHDR_colorType = PNG_COLOR_GRAY_ALPHA;
+- } else if (numBands == 3) {
+- IHDR_colorType = PNG_COLOR_RGB;
+- } else if (numBands == 4) {
+- IHDR_colorType = PNG_COLOR_RGB_ALPHA;
+- } else {
+- throw new RuntimeException("Number of bands not 1-4!");
+- }
+- }
+-
+- // Initialize IHDR_compressionMethod and IHDR_filterMethod
+- IHDR_compressionMethod = IHDR_filterMethod = 0; // Only supported value
+-
+- // Initialize IHDR_interlaceMethod
+- if(param != null &&
+- param.getProgressiveMode() == ImageWriteParam.MODE_DISABLED) {
+- IHDR_interlaceMethod = 0; // No interlacing.
+- } else if(param != null &&
+- param.getProgressiveMode() == ImageWriteParam.MODE_DEFAULT) {
+- IHDR_interlaceMethod = 1; // Adam7
+- } else {
+- // param == null ||
+- // param.getProgressiveMode() ==
+- // ImageWriteParam.MODE_COPY_FROM_METADATA
+- IHDR_interlaceMethod = interlaceMethod;
+- }
+-
+- IHDR_present = true;
+- }
+-
+- public boolean isReadOnly() {
+- return false;
+- }
+-
+- private ArrayList cloneBytesArrayList(ArrayList in) {
+- if (in == null) {
+- return null;
+- } else {
+- ArrayList list = new ArrayList(in.size());
+- Iterator iter = in.iterator();
+- while (iter.hasNext()) {
+- Object o = iter.next();
+- if (o == null) {
+- list.add(null);
+- } else {
+- list.add(((byte[])o).clone());
+- }
+- }
+-
+- return list;
+- }
+- }
+-
+- // Deep clone
+- public Object clone() {
+- CLibPNGMetadata metadata;
+- try {
+- metadata = (CLibPNGMetadata)super.clone();
+- } catch (CloneNotSupportedException e) {
+- return null;
+- }
+-
+- // unknownChunkData needs deep clone
+- metadata.unknownChunkData =
+- cloneBytesArrayList(this.unknownChunkData);
+-
+- return metadata;
+- }
+-
+- public Node getAsTree(String formatName) {
+- if (formatName.equals(nativeMetadataFormatName)) {
+- return getNativeTree();
+- } else if (formatName.equals
+- (IIOMetadataFormatImpl.standardMetadataFormatName)) {
+- return getStandardTree();
+- } else {
+- throw new IllegalArgumentException("Not a recognized format!");
+- }
+- }
+-
+- private Node getNativeTree() {
+- IIOMetadataNode node = null; // scratch node
+- IIOMetadataNode root = new IIOMetadataNode(nativeMetadataFormatName);
+-
+- // IHDR
+- if (IHDR_present) {
+- IIOMetadataNode IHDR_node = new IIOMetadataNode("IHDR");
+- IHDR_node.setAttribute("width", Integer.toString(IHDR_width));
+- IHDR_node.setAttribute("height", Integer.toString(IHDR_height));
+- IHDR_node.setAttribute("bitDepth",
+- Integer.toString(IHDR_bitDepth));
+- IHDR_node.setAttribute("colorType",
+- IHDR_colorTypeNames[IHDR_colorType]);
+- // IHDR_compressionMethod must be 0 in PNG 1.1
+- IHDR_node.setAttribute("compressionMethod",
+- IHDR_compressionMethodNames[IHDR_compressionMethod]);
+- // IHDR_filterMethod must be 0 in PNG 1.1
+- IHDR_node.setAttribute("filterMethod",
+- IHDR_filterMethodNames[IHDR_filterMethod]);
+- IHDR_node.setAttribute("interlaceMethod",
+- IHDR_interlaceMethodNames[IHDR_interlaceMethod]);
+- root.appendChild(IHDR_node);
+- }
+-
+- // PLTE
+- if (PLTE_present) {
+- IIOMetadataNode PLTE_node = new IIOMetadataNode("PLTE");
+- int numEntries = PLTE_red.length;
+- for (int i = 0; i < numEntries; i++) {
+- IIOMetadataNode entry = new IIOMetadataNode("PLTEEntry");
+- entry.setAttribute("index", Integer.toString(i));
+- entry.setAttribute("red",
+- Integer.toString(PLTE_red[i] & 0xff));
+- entry.setAttribute("green",
+- Integer.toString(PLTE_green[i] & 0xff));
+- entry.setAttribute("blue",
+- Integer.toString(PLTE_blue[i] & 0xff));
+- PLTE_node.appendChild(entry);
+- }
+-
+- root.appendChild(PLTE_node);
+- }
+-
+- // bKGD
+- if (bKGD_present) {
+- IIOMetadataNode bKGD_node = new IIOMetadataNode("bKGD");
+-
+- if (bKGD_colorType == PNG_COLOR_PALETTE) {
+- node = new IIOMetadataNode("bKGD_Palette");
+- node.setAttribute("index", Integer.toString(bKGD_index));
+- } else if (bKGD_colorType == PNG_COLOR_GRAY) {
+- node = new IIOMetadataNode("bKGD_Grayscale");
+- node.setAttribute("gray", Integer.toString(bKGD_gray));
+- } else if (bKGD_colorType == PNG_COLOR_RGB) {
+- node = new IIOMetadataNode("bKGD_RGB");
+- node.setAttribute("red", Integer.toString(bKGD_red));
+- node.setAttribute("green", Integer.toString(bKGD_green));
+- node.setAttribute("blue", Integer.toString(bKGD_blue));
+- }
+- bKGD_node.appendChild(node);
+-
+- root.appendChild(bKGD_node);
+- }
+-
+- // cHRM
+- if (cHRM_present) {
+- IIOMetadataNode cHRM_node = new IIOMetadataNode("cHRM");
+- cHRM_node.setAttribute("whitePointX",
+- Integer.toString(cHRM_whitePointX));
+- cHRM_node.setAttribute("whitePointY",
+- Integer.toString(cHRM_whitePointY));
+- cHRM_node.setAttribute("redX", Integer.toString(cHRM_redX));
+- cHRM_node.setAttribute("redY", Integer.toString(cHRM_redY));
+- cHRM_node.setAttribute("greenX", Integer.toString(cHRM_greenX));
+- cHRM_node.setAttribute("greenY", Integer.toString(cHRM_greenY));
+- cHRM_node.setAttribute("blueX", Integer.toString(cHRM_blueX));
+- cHRM_node.setAttribute("blueY", Integer.toString(cHRM_blueY));
+-
+- root.appendChild(cHRM_node);
+- }
+-
+- // gAMA
+- if (gAMA_present) {
+- IIOMetadataNode gAMA_node = new IIOMetadataNode("gAMA");
+- gAMA_node.setAttribute("value", Integer.toString(gAMA_gamma));
+-
+- root.appendChild(gAMA_node);
+- }
+-
+- // hIST
+- if (hIST_present) {
+- IIOMetadataNode hIST_node = new IIOMetadataNode("hIST");
+-
+- for (int i = 0; i < hIST_histogram.length; i++) {
+- IIOMetadataNode hist =
+- new IIOMetadataNode("hISTEntry");
+- hist.setAttribute("index", Integer.toString(i));
+- hist.setAttribute("value",
+- Integer.toString(hIST_histogram[i]));
+- hIST_node.appendChild(hist);
+- }
+-
+- root.appendChild(hIST_node);
+- }
+-
+- // iCCP
+- if (iCCP_present) {
+- IIOMetadataNode iCCP_node = new IIOMetadataNode("iCCP");
+- iCCP_node.setAttribute("profileName", iCCP_profileName);
+- iCCP_node.setAttribute("compressionMethod",
+- iCCP_compressionMethodNames[iCCP_compressionMethod]);
+-
+- Object profile = iCCP_compressedProfile;
+- if (profile != null) {
+- profile = ((byte[])profile).clone();
+- }
+- iCCP_node.setUserObject(profile);
+-
+- root.appendChild(iCCP_node);
+- }
+-
+- // iTXt
+- if (iTXt_keyword.size() > 0) {
+- IIOMetadataNode iTXt_parent = new IIOMetadataNode("iTXt");
+- for (int i = 0; i < iTXt_keyword.size(); i++) {
+- Integer val;
+-
+- IIOMetadataNode iTXt_node = new IIOMetadataNode("iTXtEntry");
+- iTXt_node.setAttribute("keyword", (String)iTXt_keyword.get(i));
+- val = (Integer)iTXt_compressionFlag.get(i);
+- iTXt_node.setAttribute("compressionFlag", val.toString());
+- val = (Integer)iTXt_compressionMethod.get(i);
+- iTXt_node.setAttribute("compressionMethod", val.toString());
+- iTXt_node.setAttribute("languageTag",
+- (String)iTXt_languageTag.get(i));
+- iTXt_node.setAttribute("translatedKeyword",
+- (String)iTXt_translatedKeyword.get(i));
+- iTXt_node.setAttribute("text", (String)iTXt_text.get(i));
+-
+- iTXt_parent.appendChild(iTXt_node);
+- }
+-
+- root.appendChild(iTXt_parent);
+- }
+-
+- // pHYs
+- if (pHYs_present) {
+- IIOMetadataNode pHYs_node = new IIOMetadataNode("pHYs");
+- pHYs_node.setAttribute("pixelsPerUnitXAxis",
+- Integer.toString(pHYs_pixelsPerUnitXAxis));
+- pHYs_node.setAttribute("pixelsPerUnitYAxis",
+- Integer.toString(pHYs_pixelsPerUnitYAxis));
+- pHYs_node.setAttribute("unitSpecifier",
+- unitSpecifierNames[pHYs_unitSpecifier]);
+-
+- root.appendChild(pHYs_node);
+- }
+-
+- // sBIT
+- if (sBIT_present) {
+- IIOMetadataNode sBIT_node = new IIOMetadataNode("sBIT");
+-
+- if (sBIT_colorType == PNG_COLOR_GRAY) {
+- node = new IIOMetadataNode("sBIT_Grayscale");
+- node.setAttribute("gray",
+- Integer.toString(sBIT_grayBits));
+- } else if (sBIT_colorType == PNG_COLOR_GRAY_ALPHA) {
+- node = new IIOMetadataNode("sBIT_GrayAlpha");
+- node.setAttribute("gray",
+- Integer.toString(sBIT_grayBits));
+- node.setAttribute("alpha",
+- Integer.toString(sBIT_alphaBits));
+- } else if (sBIT_colorType == PNG_COLOR_RGB) {
+- node = new IIOMetadataNode("sBIT_RGB");
+- node.setAttribute("red",
+- Integer.toString(sBIT_redBits));
+- node.setAttribute("green",
+- Integer.toString(sBIT_greenBits));
+- node.setAttribute("blue",
+- Integer.toString(sBIT_blueBits));
+- } else if (sBIT_colorType == PNG_COLOR_RGB_ALPHA) {
+- node = new IIOMetadataNode("sBIT_RGBAlpha");
+- node.setAttribute("red",
+- Integer.toString(sBIT_redBits));
+- node.setAttribute("green",
+- Integer.toString(sBIT_greenBits));
+- node.setAttribute("blue",
+- Integer.toString(sBIT_blueBits));
+- node.setAttribute("alpha",
+- Integer.toString(sBIT_alphaBits));
+- } else if (sBIT_colorType == PNG_COLOR_PALETTE) {
+- node = new IIOMetadataNode("sBIT_Palette");
+- node.setAttribute("red",
+- Integer.toString(sBIT_redBits));
+- node.setAttribute("green",
+- Integer.toString(sBIT_greenBits));
+- node.setAttribute("blue",
+- Integer.toString(sBIT_blueBits));
+- }
+- sBIT_node.appendChild(node);
+-
+- root.appendChild(sBIT_node);
+- }
+-
+- // sPLT
+- if (sPLT_present) {
+- IIOMetadataNode sPLT_node = new IIOMetadataNode("sPLT");
+-
+- sPLT_node.setAttribute("name", sPLT_paletteName);
+- sPLT_node.setAttribute("sampleDepth",
+- Integer.toString(sPLT_sampleDepth));
+-
+- int numEntries = sPLT_red.length;
+- for (int i = 0; i < numEntries; i++) {
+- IIOMetadataNode entry = new IIOMetadataNode("sPLTEntry");
+- entry.setAttribute("index", Integer.toString(i));
+- entry.setAttribute("red", Integer.toString(sPLT_red[i]));
+- entry.setAttribute("green", Integer.toString(sPLT_green[i]));
+- entry.setAttribute("blue", Integer.toString(sPLT_blue[i]));
+- entry.setAttribute("alpha", Integer.toString(sPLT_alpha[i]));
+- entry.setAttribute("frequency",
+- Integer.toString(sPLT_frequency[i]));
+- sPLT_node.appendChild(entry);
+- }
+-
+- root.appendChild(sPLT_node);
+- }
+-
+- // sRGB
+- if (sRGB_present) {
+- IIOMetadataNode sRGB_node = new IIOMetadataNode("sRGB");
+- sRGB_node.setAttribute("renderingIntent",
+- renderingIntentNames[sRGB_renderingIntent]);
+-
+- root.appendChild(sRGB_node);
+- }
+-
+- // tEXt
+- if (tEXt_keyword.size() > 0) {
+- IIOMetadataNode tEXt_parent = new IIOMetadataNode("tEXt");
+- for (int i = 0; i < tEXt_keyword.size(); i++) {
+- IIOMetadataNode tEXt_node = new IIOMetadataNode("tEXtEntry");
+- tEXt_node.setAttribute("keyword" , (String)tEXt_keyword.get(i));
+- tEXt_node.setAttribute("value" , (String)tEXt_text.get(i));
+-
+- tEXt_parent.appendChild(tEXt_node);
+- }
+-
+- root.appendChild(tEXt_parent);
+- }
+-
+- // tIME
+- if (tIME_present) {
+- IIOMetadataNode tIME_node = new IIOMetadataNode("tIME");
+- tIME_node.setAttribute("year", Integer.toString(tIME_year));
+- tIME_node.setAttribute("month", Integer.toString(tIME_month));
+- tIME_node.setAttribute("day", Integer.toString(tIME_day));
+- tIME_node.setAttribute("hour", Integer.toString(tIME_hour));
+- tIME_node.setAttribute("minute", Integer.toString(tIME_minute));
+- tIME_node.setAttribute("second", Integer.toString(tIME_second));
+-
+- root.appendChild(tIME_node);
+- }
+-
+- // tRNS
+- if (tRNS_present) {
+- IIOMetadataNode tRNS_node = new IIOMetadataNode("tRNS");
+-
+- if (tRNS_colorType == PNG_COLOR_PALETTE) {
+- node = new IIOMetadataNode("tRNS_Palette");
+-
+- for (int i = 0; i < tRNS_alpha.length; i++) {
+- IIOMetadataNode entry =
+- new IIOMetadataNode("tRNS_PaletteEntry");
+- entry.setAttribute("index", Integer.toString(i));
+- entry.setAttribute("alpha",
+- Integer.toString(tRNS_alpha[i] & 0xff));
+- node.appendChild(entry);
+- }
+- } else if (tRNS_colorType == PNG_COLOR_GRAY) {
+- node = new IIOMetadataNode("tRNS_Grayscale");
+- node.setAttribute("gray", Integer.toString(tRNS_gray));
+- } else if (tRNS_colorType == PNG_COLOR_RGB) {
+- node = new IIOMetadataNode("tRNS_RGB");
+- node.setAttribute("red", Integer.toString(tRNS_red));
+- node.setAttribute("green", Integer.toString(tRNS_green));
+- node.setAttribute("blue", Integer.toString(tRNS_blue));
+- }
+- tRNS_node.appendChild(node);
+-
+- root.appendChild(tRNS_node);
+- }
+-
+- // zTXt
+- if (zTXt_keyword.size() > 0) {
+- IIOMetadataNode zTXt_parent = new IIOMetadataNode("zTXt");
+- for (int i = 0; i < zTXt_keyword.size(); i++) {
+- IIOMetadataNode zTXt_node = new IIOMetadataNode("zTXtEntry");
+- zTXt_node.setAttribute("keyword", (String)zTXt_keyword.get(i));
+-
+- int cm = ((Integer)zTXt_compressionMethod.get(i)).intValue();
+- zTXt_node.setAttribute("compressionMethod",
+- zTXt_compressionMethodNames[cm]);
+-
+- zTXt_node.setAttribute("text", (String)zTXt_text.get(i));
+-
+- zTXt_parent.appendChild(zTXt_node);
+- }
+-
+- root.appendChild(zTXt_parent);
+- }
+-
+- // Unknown chunks
+- if (unknownChunkType.size() > 0) {
+- IIOMetadataNode unknown_parent =
+- new IIOMetadataNode("UnknownChunks");
+- for (int i = 0; i < unknownChunkType.size(); i++) {
+- IIOMetadataNode unknown_node =
+- new IIOMetadataNode("UnknownChunk");
+- unknown_node.setAttribute("type",
+- (String)unknownChunkType.get(i));
+- unknown_node.setUserObject((byte[])unknownChunkData.get(i));
+-
+- unknown_parent.appendChild(unknown_node);
+- }
+-
+- root.appendChild(unknown_parent);
+- }
+-
+- return root;
+- }
+-
+- private int getNumChannels() {
+- // Determine number of channels
+- // Be careful about palette color with transparency
+- int numChannels = IHDR_numChannels[IHDR_colorType];
+- if (IHDR_colorType == PNG_COLOR_PALETTE &&
+- tRNS_present && tRNS_colorType == IHDR_colorType) {
+- numChannels = 4;
+- }
+- return numChannels;
+- }
+-
+- public IIOMetadataNode getStandardChromaNode() {
+- IIOMetadataNode chroma_node = new IIOMetadataNode("Chroma");
+- IIOMetadataNode node = null; // scratch node
+-
+- node = new IIOMetadataNode("ColorSpaceType");
+- node.setAttribute("name", colorSpaceTypeNames[IHDR_colorType]);
+- chroma_node.appendChild(node);
+-
+- node = new IIOMetadataNode("NumChannels");
+- node.setAttribute("value", Integer.toString(getNumChannels()));
+- chroma_node.appendChild(node);
+-
+- if (gAMA_present) {
+- node = new IIOMetadataNode("Gamma");
+- node.setAttribute("value", Float.toString(gAMA_gamma*1.0e-5F));
+- chroma_node.appendChild(node);
+- }
+-
+- node = new IIOMetadataNode("BlackIsZero");
+- node.setAttribute("value", "TRUE");
+- chroma_node.appendChild(node);
+-
+- if (PLTE_present) {
+- boolean hasAlpha = tRNS_present &&
+- (tRNS_colorType == PNG_COLOR_PALETTE);
+-
+- node = new IIOMetadataNode("Palette");
+- for (int i = 0; i < PLTE_red.length; i++) {
+- IIOMetadataNode entry =
+- new IIOMetadataNode("PaletteEntry");
+- entry.setAttribute("index", Integer.toString(i));
+- entry.setAttribute("red",
+- Integer.toString(PLTE_red[i] & 0xff));
+- entry.setAttribute("green",
+- Integer.toString(PLTE_green[i] & 0xff));
+- entry.setAttribute("blue",
+- Integer.toString(PLTE_blue[i] & 0xff));
+- if (hasAlpha) {
+- int alpha = (i < tRNS_alpha.length) ?
+- (tRNS_alpha[i] & 0xff) : 255;
+- entry.setAttribute("alpha", Integer.toString(alpha));
+- }
+- node.appendChild(entry);
+- }
+- chroma_node.appendChild(node);
+- }
+-
+- if (bKGD_present) {
+- if (bKGD_colorType == PNG_COLOR_PALETTE) {
+- node = new IIOMetadataNode("BackgroundIndex");
+- node.setAttribute("value", Integer.toString(bKGD_index));
+- } else {
+- node = new IIOMetadataNode("BackgroundColor");
+- int r, g, b;
+-
+- if (bKGD_colorType == PNG_COLOR_GRAY) {
+- r = g = b = bKGD_gray;
+- } else {
+- r = bKGD_red;
+- g = bKGD_green;
+- b = bKGD_blue;
+- }
+- node.setAttribute("red", Integer.toString(r));
+- node.setAttribute("green", Integer.toString(g));
+- node.setAttribute("blue", Integer.toString(b));
+- }
+- chroma_node.appendChild(node);
+- }
+-
+- return chroma_node;
+- }
+-
+- public IIOMetadataNode getStandardCompressionNode() {
+- IIOMetadataNode compression_node = new IIOMetadataNode("Compression");
+- IIOMetadataNode node = null; // scratch node
+-
+- node = new IIOMetadataNode("CompressionTypeName");
+- node.setAttribute("value", "deflate");
+- compression_node.appendChild(node);
+-
+- node = new IIOMetadataNode("Lossless");
+- node.setAttribute("value", "TRUE");
+- compression_node.appendChild(node);
+-
+- node = new IIOMetadataNode("NumProgressiveScans");
+- node.setAttribute("value",
+- (IHDR_interlaceMethod == 0) ? "1" : "7");
+- compression_node.appendChild(node);
+-
+- return compression_node;
+- }
+-
+- private String repeat(String s, int times) {
+- if (times == 1) {
+- return s;
+- }
+- StringBuffer sb = new StringBuffer((s.length() + 1)*times - 1);
+- sb.append(s);
+- for (int i = 1; i < times; i++) {
+- sb.append(" ");
+- sb.append(s);
+- }
+- return sb.toString();
+- }
+-
+- public IIOMetadataNode getStandardDataNode() {
+- IIOMetadataNode data_node = new IIOMetadataNode("Data");
+- IIOMetadataNode node = null; // scratch node
+-
+- node = new IIOMetadataNode("PlanarConfiguration");
+- node.setAttribute("value", "PixelInterleaved");
+- data_node.appendChild(node);
+-
+- node = new IIOMetadataNode("SampleFormat");
+- node.setAttribute("value",
+- IHDR_colorType == PNG_COLOR_PALETTE ?
+- "Index" : "UnsignedIntegral");
+- data_node.appendChild(node);
+-
+- String bitDepth = Integer.toString(IHDR_bitDepth);
+- node = new IIOMetadataNode("BitsPerSample");
+- node.setAttribute("value", repeat(bitDepth, getNumChannels()));
+- data_node.appendChild(node);
+-
+- if (sBIT_present) {
+- node = new IIOMetadataNode("SignificantBitsPerSample");
+- String sbits;
+- if (sBIT_colorType == PNG_COLOR_GRAY ||
+- sBIT_colorType == PNG_COLOR_GRAY_ALPHA) {
+- sbits = Integer.toString(sBIT_grayBits);
+- } else { // sBIT_colorType == PNG_COLOR_RGB ||
+- // sBIT_colorType == PNG_COLOR_RGB_ALPHA
+- sbits = Integer.toString(sBIT_redBits) + " " +
+- Integer.toString(sBIT_greenBits) + " " +
+- Integer.toString(sBIT_blueBits);
+- }
+-
+- if (sBIT_colorType == PNG_COLOR_GRAY_ALPHA ||
+- sBIT_colorType == PNG_COLOR_RGB_ALPHA) {
+- sbits += " " + Integer.toString(sBIT_alphaBits);
+- }
+-
+- node.setAttribute("value", sbits);
+- data_node.appendChild(node);
+- }
+-
+- // SampleMSB
+-
+- return data_node;
+- }
+-
+- public IIOMetadataNode getStandardDimensionNode() {
+- IIOMetadataNode dimension_node = new IIOMetadataNode("Dimension");
+- IIOMetadataNode node = null; // scratch node
+-
+- node = new IIOMetadataNode("PixelAspectRatio");
+- // aspect ratio is pixel width/height which is the ratio of the
+- // inverses of pixels per unit length.
+- float ratio = pHYs_present ?
+- (float)pHYs_pixelsPerUnitYAxis/pHYs_pixelsPerUnitXAxis : 1.0F;
+- node.setAttribute("value", Float.toString(ratio));
+- dimension_node.appendChild(node);
+-
+- node = new IIOMetadataNode("ImageOrientation");
+- node.setAttribute("value", "Normal");
+- dimension_node.appendChild(node);
+-
+- if (pHYs_present && pHYs_unitSpecifier == PHYS_UNIT_METER) {
+- node = new IIOMetadataNode("HorizontalPixelSize");
+- node.setAttribute("value",
+- Float.toString(1000.0F/pHYs_pixelsPerUnitXAxis));
+- dimension_node.appendChild(node);
+-
+- node = new IIOMetadataNode("VerticalPixelSize");
+- node.setAttribute("value",
+- Float.toString(1000.0F/pHYs_pixelsPerUnitYAxis));
+- dimension_node.appendChild(node);
+- }
+-
+- return dimension_node;
+- }
+-
+- public IIOMetadataNode getStandardDocumentNode() {
+- if (!tIME_present) {
+- return null;
+- }
+-
+- IIOMetadataNode document_node = new IIOMetadataNode("Document");
+- IIOMetadataNode node = null; // scratch node
+-
+- node = new IIOMetadataNode("ImageModificationTime");
+- node.setAttribute("year", Integer.toString(tIME_year));
+- node.setAttribute("month", Integer.toString(tIME_month));
+- node.setAttribute("day", Integer.toString(tIME_day));
+- node.setAttribute("hour", Integer.toString(tIME_hour));
+- node.setAttribute("minute", Integer.toString(tIME_minute));
+- node.setAttribute("second", Integer.toString(tIME_second));
+- document_node.appendChild(node);
+-
+- return document_node;
+- }
+-
+- public IIOMetadataNode getStandardTextNode() {
+- int numEntries = tEXt_keyword.size() +
+- iTXt_keyword.size() + zTXt_keyword.size();
+- if (numEntries == 0) {
+- return null;
+- }
+-
+- IIOMetadataNode text_node = new IIOMetadataNode("Text");
+- IIOMetadataNode node = null; // scratch node
+-
+- for (int i = 0; i < tEXt_keyword.size(); i++) {
+- node = new IIOMetadataNode("TextEntry");
+- node.setAttribute("keyword", (String)tEXt_keyword.get(i));
+- node.setAttribute("value", (String)tEXt_text.get(i));
+- node.setAttribute("encoding", "ISO-8859-1");
+- node.setAttribute("compression", "none");
+-
+- text_node.appendChild(node);
+- }
+-
+- for (int i = 0; i < iTXt_keyword.size(); i++) {
+- node = new IIOMetadataNode("TextEntry");
+- node.setAttribute("keyword", (String)iTXt_keyword.get(i));
+- node.setAttribute("value", (String)iTXt_text.get(i));
+- node.setAttribute("language",
+- (String)iTXt_languageTag.get(i));
+- if (((Integer)iTXt_compressionFlag.get(i)).intValue() == 1) {
+- node.setAttribute("compression", "deflate");
+- } else {
+- node.setAttribute("compression", "none");
+- }
+-
+- text_node.appendChild(node);
+- }
+-
+- for (int i = 0; i < zTXt_keyword.size(); i++) {
+- node = new IIOMetadataNode("TextEntry");
+- node.setAttribute("keyword", (String)zTXt_keyword.get(i));
+- node.setAttribute("value", (String)zTXt_text.get(i));
+- node.setAttribute("compression", "deflate");
+-
+- text_node.appendChild(node);
+- }
+-
+- return text_node;
+- }
+-
+- public IIOMetadataNode getStandardTransparencyNode() {
+- IIOMetadataNode transparency_node =
+- new IIOMetadataNode("Transparency");
+- IIOMetadataNode node = null; // scratch node
+-
+- node = new IIOMetadataNode("Alpha");
+- boolean hasAlpha =
+- (IHDR_colorType == PNG_COLOR_RGB_ALPHA) ||
+- (IHDR_colorType == PNG_COLOR_GRAY_ALPHA) ||
+- (IHDR_colorType == PNG_COLOR_PALETTE &&
+- tRNS_present &&
+- (tRNS_colorType == IHDR_colorType) &&
+- (tRNS_alpha != null));
+- node.setAttribute("value", hasAlpha ? "nonpremultiplied" : "none");
+- transparency_node.appendChild(node);
+-
+- if (tRNS_present) {
+- if(tRNS_colorType == PNG_COLOR_RGB ||
+- tRNS_colorType == PNG_COLOR_GRAY) {
+- node = new IIOMetadataNode("TransparentColor");
+- if (tRNS_colorType == PNG_COLOR_RGB) {
+- node.setAttribute("value",
+- Integer.toString(tRNS_red) + " " +
+- Integer.toString(tRNS_green) + " " +
+- Integer.toString(tRNS_blue));
+- } else if (tRNS_colorType == PNG_COLOR_GRAY) {
+- node.setAttribute("value", Integer.toString(tRNS_gray));
+- }
+- transparency_node.appendChild(node);
+- }
+- }
+-
+- return transparency_node;
+- }
+-
+- // Shorthand for throwing an IIOInvalidTreeException
+- private void fatal(Node node, String reason)
+- throws IIOInvalidTreeException {
+- throw new IIOInvalidTreeException(reason, node);
+- }
+-
+- // Get an integer-valued attribute
+- private int getIntAttribute(Node node, String name,
+- int defaultValue, boolean required)
+- throws IIOInvalidTreeException {
+- String value = getAttribute(node, name, null, required);
+- if (value == null) {
+- return defaultValue;
+- }
+- return Integer.parseInt(value);
+- }
+-
+- // Get a float-valued attribute
+- private float getFloatAttribute(Node node, String name,
+- float defaultValue, boolean required)
+- throws IIOInvalidTreeException {
+- String value = getAttribute(node, name, null, required);
+- if (value == null) {
+- return defaultValue;
+- }
+- return Float.parseFloat(value);
+- }
+-
+- // Get a required integer-valued attribute
+- private int getIntAttribute(Node node, String name)
+- throws IIOInvalidTreeException {
+- return getIntAttribute(node, name, -1, true);
+- }
+-
+- // Get a required float-valued attribute
+- private float getFloatAttribute(Node node, String name)
+- throws IIOInvalidTreeException {
+- return getFloatAttribute(node, name, -1.0F, true);
+- }
+-
+- // Get a boolean-valued attribute
+- private boolean getBooleanAttribute(Node node, String name,
+- boolean defaultValue,
+- boolean required)
+- throws IIOInvalidTreeException {
+- Node attr = node.getAttributes().getNamedItem(name);
+- if (attr == null) {
+- if (!required) {
+- return defaultValue;
+- } else {
+- fatal(node, "Required attribute " + name + " not present!");
+- }
+- }
+-
+- String value = attr.getNodeValue();
+-
+- if (value.equalsIgnoreCase("true")) {
+- return true;
+- } else if (value.equalsIgnoreCase("false")) {
+- return false;
+- } else {
+- fatal(node, "Attribute " + name + " must be 'true' or 'false'!");
+- return false;
+- }
+- }
+-
+- // Get a required boolean-valued attribute
+- private boolean getBooleanAttribute(Node node, String name)
+- throws IIOInvalidTreeException {
+- return getBooleanAttribute(node, name, false, true);
+- }
+-
+- // Get an enumerated attribute as an index into a String array
+- private int getEnumeratedAttribute(Node node,
+- String name, String[] legalNames,
+- int defaultValue, boolean required)
+- throws IIOInvalidTreeException {
+- Node attr = node.getAttributes().getNamedItem(name);
+- if (attr == null) {
+- if (!required) {
+- return defaultValue;
+- } else {
+- fatal(node, "Required attribute " + name + " not present!");
+- }
+- }
+-
+- String value = attr.getNodeValue();
+-
+- for (int i = 0; i < legalNames.length; i++) {
+- if (value.equals(legalNames[i])) {
+- return i;
+- }
+- }
+-
+- fatal(node, "Illegal value for attribute " + name + "!");
+- return -1;
+- }
+-
+- // Get a required enumerated attribute as an index into a String array
+- private int getEnumeratedAttribute(Node node,
+- String name, String[] legalNames)
+- throws IIOInvalidTreeException {
+- return getEnumeratedAttribute(node, name, legalNames, -1, true);
+- }
+-
+- // Get a String-valued attribute
+- private String getAttribute(Node node, String name,
+- String defaultValue, boolean required)
+- throws IIOInvalidTreeException {
+- Node attr = node.getAttributes().getNamedItem(name);
+- if (attr == null) {
+- if (!required) {
+- return defaultValue;
+- } else {
+- fatal(node, "Required attribute " + name + " not present!");
+- }
+- }
+- return attr.getNodeValue();
+- }
+-
+- // Get a required String-valued attribute
+- private String getAttribute(Node node, String name)
+- throws IIOInvalidTreeException {
+- return getAttribute(node, name, null, true);
+- }
+-
+- public void mergeTree(String formatName, Node root)
+- throws IIOInvalidTreeException {
+- if (formatName.equals(nativeMetadataFormatName)) {
+- if (root == null) {
+- throw new IllegalArgumentException("root == null!");
+- }
+- mergeNativeTree(root);
+- } else if (formatName.equals
+- (IIOMetadataFormatImpl.standardMetadataFormatName)) {
+- if (root == null) {
+- throw new IllegalArgumentException("root == null!");
+- }
+- mergeStandardTree(root);
+- } else {
+- throw new IllegalArgumentException("Not a recognized format!");
+- }
+- }
+-
+- private void mergeNativeTree(Node root)
+- throws IIOInvalidTreeException {
+- Node node = root;
+- if (!node.getNodeName().equals(nativeMetadataFormatName)) {
+- fatal(node, "Root must be " + nativeMetadataFormatName);
+- }
+-
+- node = node.getFirstChild();
+- while (node != null) {
+- String name = node.getNodeName();
+-
+- if (name.equals("IHDR")) {
+- IHDR_width = getIntAttribute(node, "width");
+- IHDR_height = getIntAttribute(node, "height");
+- IHDR_bitDepth = getEnumeratedAttribute(node, "bitDepth",
+- IHDR_bitDepths);
+- IHDR_colorType = getEnumeratedAttribute(node, "colorType",
+- IHDR_colorTypeNames);
+- IHDR_compressionMethod =
+- getEnumeratedAttribute(node, "compressionMethod",
+- IHDR_compressionMethodNames);
+- IHDR_filterMethod =
+- getEnumeratedAttribute(node,
+- "filterMethod",
+- IHDR_filterMethodNames);
+- IHDR_interlaceMethod =
+- getEnumeratedAttribute(node, "interlaceMethod",
+- IHDR_interlaceMethodNames);
+- IHDR_present = true;
+- } else if (name.equals("PLTE")) {
+- byte[] red = new byte[256];
+- byte[] green = new byte[256];
+- byte[] blue = new byte[256];
+- int maxindex = -1;
+-
+- Node PLTE_entry = node.getFirstChild();
+- if (PLTE_entry == null) {
+- fatal(node, "Palette has no entries!");
+- }
+-
+- while (PLTE_entry != null) {
+- if (!PLTE_entry.getNodeName().equals("PLTEEntry")) {
+- fatal(node,
+- "Only a PLTEEntry may be a child of a PLTE!");
+- }
+-
+- int index = getIntAttribute(PLTE_entry, "index");
+- if (index < 0 || index > 255) {
+- fatal(node,
+- "Bad value for PLTEEntry attribute index!");
+- }
+- if (index > maxindex) {
+- maxindex = index;
+- }
+- red[index] =
+- (byte)getIntAttribute(PLTE_entry, "red");
+- green[index] =
+- (byte)getIntAttribute(PLTE_entry, "green");
+- blue[index] =
+- (byte)getIntAttribute(PLTE_entry, "blue");
+-
+- PLTE_entry = PLTE_entry.getNextSibling();
+- }
+-
+- int numEntries = maxindex + 1;
+- PLTE_red = new byte[numEntries];
+- PLTE_green = new byte[numEntries];
+- PLTE_blue = new byte[numEntries];
+- System.arraycopy(red, 0, PLTE_red, 0, numEntries);
+- System.arraycopy(green, 0, PLTE_green, 0, numEntries);
+- System.arraycopy(blue, 0, PLTE_blue, 0, numEntries);
+- PLTE_present = true;
+- } else if (name.equals("bKGD")) {
+- bKGD_present = false; // Guard against partial overwrite
+- Node bKGD_node = node.getFirstChild();
+- if (bKGD_node == null) {
+- fatal(node, "bKGD node has no children!");
+- }
+- String bKGD_name = bKGD_node.getNodeName();
+- if (bKGD_name.equals("bKGD_Palette")) {
+- bKGD_index = getIntAttribute(bKGD_node, "index");
+- bKGD_colorType = PNG_COLOR_PALETTE;
+- } else if (bKGD_name.equals("bKGD_Grayscale")) {
+- bKGD_gray = getIntAttribute(bKGD_node, "gray");
+- bKGD_colorType = PNG_COLOR_GRAY;
+- } else if (bKGD_name.equals("bKGD_RGB")) {
+- bKGD_red = getIntAttribute(bKGD_node, "red");
+- bKGD_green = getIntAttribute(bKGD_node, "green");
+- bKGD_blue = getIntAttribute(bKGD_node, "blue");
+- bKGD_colorType = PNG_COLOR_RGB;
+- } else {
+- fatal(node, "Bad child of a bKGD node!");
+- }
+- if (bKGD_node.getNextSibling() != null) {
+- fatal(node, "bKGD node has more than one child!");
+- }
+-
+- bKGD_present = true;
+- } else if (name.equals("cHRM")) {
+- cHRM_whitePointX = getIntAttribute(node, "whitePointX");
+- cHRM_whitePointY = getIntAttribute(node, "whitePointY");
+- cHRM_redX = getIntAttribute(node, "redX");
+- cHRM_redY = getIntAttribute(node, "redY");
+- cHRM_greenX = getIntAttribute(node, "greenX");
+- cHRM_greenY = getIntAttribute(node, "greenY");
+- cHRM_blueX = getIntAttribute(node, "blueX");
+- cHRM_blueY = getIntAttribute(node, "blueY");
+-
+- cHRM_present = true;
+- } else if (name.equals("gAMA")) {
+- gAMA_gamma = getIntAttribute(node, "value");
+- gAMA_present = true;
+- } else if (name.equals("hIST")) {
+- char[] hist = new char[256];
+- int maxindex = -1;
+-
+- Node hIST_entry = node.getFirstChild();
+- if (hIST_entry == null) {
+- fatal(node, "hIST node has no children!");
+- }
+-
+- while (hIST_entry != null) {
+- if (!hIST_entry.getNodeName().equals("hISTEntry")) {
+- fatal(node,
+- "Only a hISTEntry may be a child of a hIST!");
+- }
+-
+- int index = getIntAttribute(hIST_entry, "index");
+- if (index < 0 || index > 255) {
+- fatal(node,
+- "Bad value for histEntry attribute index!");
+- }
+- if (index > maxindex) {
+- maxindex = index;
+- }
+- hist[index] =
+- (char)getIntAttribute(hIST_entry, "value");
+-
+- hIST_entry = hIST_entry.getNextSibling();
+- }
+-
+- int numEntries = maxindex + 1;
+- hIST_histogram = new char[numEntries];
+- System.arraycopy(hist, 0, hIST_histogram, 0, numEntries);
+-
+- hIST_present = true;
+- } else if (name.equals("iCCP")) {
+- iCCP_profileName =
+- toPrintableLatin1(getAttribute(node, "profileName"));
+- iCCP_compressionMethod =
+- getEnumeratedAttribute(node, "compressionMethod",
+- iCCP_compressionMethodNames);
+- Object compressedProfile =
+- ((IIOMetadataNode)node).getUserObject();
+- if (compressedProfile == null) {
+- fatal(node, "No ICCP profile present in user object!");
+- }
+- if (!(compressedProfile instanceof byte[])) {
+- fatal(node, "User object not a byte array!");
+- }
+-
+- iCCP_compressedProfile =
+- (byte[])((byte[])compressedProfile).clone();
+-
+- iCCP_present = true;
+- } else if (name.equals("iTXt")) {
+- Node iTXt_node = node.getFirstChild();
+- while (iTXt_node != null) {
+- if (!iTXt_node.getNodeName().equals("iTXtEntry")) {
+- fatal(node,
+- "Only an iTXtEntry may be a child of an iTXt!");
+- }
+-
+- String keyword =
+- toPrintableLatin1(getAttribute(iTXt_node, "keyword"));
+- iTXt_keyword.add(keyword);
+-
+- boolean compressionFlag =
+- getBooleanAttribute(iTXt_node, "compressionFlag");
+- iTXt_compressionFlag.add(new Boolean(compressionFlag));
+-
+- String compressionMethod =
+- getAttribute(iTXt_node, "compressionMethod");
+- iTXt_compressionMethod.add(compressionMethod);
+-
+- String languageTag =
+- getAttribute(iTXt_node, "languageTag");
+- iTXt_languageTag.add(languageTag);
+-
+- String translatedKeyword =
+- getAttribute(iTXt_node, "translatedKeyword");
+- iTXt_translatedKeyword.add(translatedKeyword);
+-
+- String text = getAttribute(iTXt_node, "text");
+- iTXt_text.add(text);
+-
+- iTXt_node = iTXt_node.getNextSibling();
+- }
+- } else if (name.equals("pHYs")) {
+- pHYs_pixelsPerUnitXAxis =
+- getIntAttribute(node, "pixelsPerUnitXAxis");
+- pHYs_pixelsPerUnitYAxis =
+- getIntAttribute(node, "pixelsPerUnitYAxis");
+- pHYs_unitSpecifier =
+- getEnumeratedAttribute(node, "unitSpecifier",
+- unitSpecifierNames);
+-
+- pHYs_present = true;
+- } else if (name.equals("sBIT")) {
+- sBIT_present = false; // Guard against partial overwrite
+- Node sBIT_node = node.getFirstChild();
+- if (sBIT_node == null) {
+- fatal(node, "sBIT node has no children!");
+- }
+- String sBIT_name = sBIT_node.getNodeName();
+- if (sBIT_name.equals("sBIT_Grayscale")) {
+- sBIT_grayBits = getIntAttribute(sBIT_node, "gray");
+- sBIT_colorType = PNG_COLOR_GRAY;
+- } else if (sBIT_name.equals("sBIT_GrayAlpha")) {
+- sBIT_grayBits = getIntAttribute(sBIT_node, "gray");
+- sBIT_alphaBits = getIntAttribute(sBIT_node, "alpha");
+- sBIT_colorType = PNG_COLOR_GRAY_ALPHA;
+- } else if (sBIT_name.equals("sBIT_RGB")) {
+- sBIT_redBits = getIntAttribute(sBIT_node, "red");
+- sBIT_greenBits = getIntAttribute(sBIT_node, "green");
+- sBIT_blueBits = getIntAttribute(sBIT_node, "blue");
+- sBIT_colorType = PNG_COLOR_RGB;
+- } else if (sBIT_name.equals("sBIT_RGBAlpha")) {
+- sBIT_redBits = getIntAttribute(sBIT_node, "red");
+- sBIT_greenBits = getIntAttribute(sBIT_node, "green");
+- sBIT_blueBits = getIntAttribute(sBIT_node, "blue");
+- sBIT_alphaBits = getIntAttribute(sBIT_node, "alpha");
+- sBIT_colorType = PNG_COLOR_RGB_ALPHA;
+- } else if (sBIT_name.equals("sBIT_Palette")) {
+- sBIT_redBits = getIntAttribute(sBIT_node, "red");
+- sBIT_greenBits = getIntAttribute(sBIT_node, "green");
+- sBIT_blueBits = getIntAttribute(sBIT_node, "blue");
+- sBIT_colorType = PNG_COLOR_PALETTE;
+- } else {
+- fatal(node, "Bad child of an sBIT node!");
+- }
+- if (sBIT_node.getNextSibling() != null) {
+- fatal(node, "sBIT node has more than one child!");
+- }
+-
+- sBIT_present = true;
+- } else if (name.equals("sPLT")) {
+- sPLT_paletteName =
+- toPrintableLatin1(getAttribute(node, "name"));
+- sPLT_sampleDepth = getIntAttribute(node, "sampleDepth");
+-
+- int[] red = new int[256];
+- int[] green = new int[256];
+- int[] blue = new int[256];
+- int[] alpha = new int[256];
+- int[] frequency = new int[256];
+- int maxindex = -1;
+-
+- Node sPLT_entry = node.getFirstChild();
+- if (sPLT_entry == null) {
+- fatal(node, "sPLT node has no children!");
+- }
+-
+- while (sPLT_entry != null) {
+- if (!sPLT_entry.getNodeName().equals("sPLTEntry")) {
+- fatal(node,
+- "Only an sPLTEntry may be a child of an sPLT!");
+- }
+-
+- int index = getIntAttribute(sPLT_entry, "index");
+- if (index < 0 || index > 255) {
+- fatal(node,
+- "Bad value for PLTEEntry attribute index!");
+- }
+- if (index > maxindex) {
+- maxindex = index;
+- }
+- red[index] = getIntAttribute(sPLT_entry, "red");
+- green[index] = getIntAttribute(sPLT_entry, "green");
+- blue[index] = getIntAttribute(sPLT_entry, "blue");
+- alpha[index] = getIntAttribute(sPLT_entry, "alpha");
+- frequency[index] =
+- getIntAttribute(sPLT_entry, "frequency");
+-
+- sPLT_entry = sPLT_entry.getNextSibling();
+- }
+-
+- int numEntries = maxindex + 1;
+- sPLT_red = new int[numEntries];
+- sPLT_green = new int[numEntries];
+- sPLT_blue = new int[numEntries];
+- sPLT_alpha = new int[numEntries];
+- sPLT_frequency = new int[numEntries];
+- System.arraycopy(red, 0, sPLT_red, 0, numEntries);
+- System.arraycopy(green, 0, sPLT_green, 0, numEntries);
+- System.arraycopy(blue, 0, sPLT_blue, 0, numEntries);
+- System.arraycopy(alpha, 0, sPLT_alpha, 0, numEntries);
+- System.arraycopy(frequency, 0,
+- sPLT_frequency, 0, numEntries);
+-
+- sPLT_present = true;
+- } else if (name.equals("sRGB")) {
+- sRGB_renderingIntent =
+- getEnumeratedAttribute(node, "renderingIntent",
+- renderingIntentNames);
+-
+- sRGB_present = true;
+- } else if (name.equals("tEXt")) {
+- Node tEXt_node = node.getFirstChild();
+- while (tEXt_node != null) {
+- if (!tEXt_node.getNodeName().equals("tEXtEntry")) {
+- fatal(node,
+- "Only an tEXtEntry may be a child of an tEXt!");
+- }
+-
+- String keyword =
+- toPrintableLatin1(getAttribute(tEXt_node, "keyword"));
+- tEXt_keyword.add(keyword);
+-
+- String text = getAttribute(tEXt_node, "value");
+- tEXt_text.add(text);
+-
+- tEXt_node = tEXt_node.getNextSibling();
+- }
+- } else if (name.equals("tIME")) {
+- tIME_year = getIntAttribute(node, "year");
+- tIME_month = getIntAttribute(node, "month");
+- tIME_day = getIntAttribute(node, "day");
+- tIME_hour = getIntAttribute(node, "hour");
+- tIME_minute = getIntAttribute(node, "minute");
+- tIME_second = getIntAttribute(node, "second");
+-
+- tIME_present = true;
+- } else if (name.equals("tRNS")) {
+- tRNS_present = false; // Guard against partial overwrite
+- Node tRNS_node = node.getFirstChild();
+- if (tRNS_node == null) {
+- fatal(node, "tRNS node has no children!");
+- }
+- String tRNS_name = tRNS_node.getNodeName();
+- if (tRNS_name.equals("tRNS_Palette")) {
+- byte[] alpha = new byte[256];
+- int maxindex = -1;
+-
+- Node tRNS_paletteEntry = tRNS_node.getFirstChild();
+- if (tRNS_paletteEntry == null) {
+- fatal(node, "tRNS_Palette node has no children!");
+- }
+- while (tRNS_paletteEntry != null) {
+- if (!tRNS_paletteEntry.getNodeName().equals(
+- "tRNS_PaletteEntry")) {
+- fatal(node,
+- "Only a tRNS_PaletteEntry may be a child of a tRNS_Palette!");
+- }
+- int index =
+- getIntAttribute(tRNS_paletteEntry, "index");
+- if (index < 0 || index > 255) {
+- fatal(node,
+- "Bad value for tRNS_PaletteEntry attribute index!");
+- }
+- if (index > maxindex) {
+- maxindex = index;
+- }
+- alpha[index] =
+- (byte)getIntAttribute(tRNS_paletteEntry,
+- "alpha");
+-
+- tRNS_paletteEntry =
+- tRNS_paletteEntry.getNextSibling();
+- }
+-
+- int numEntries = maxindex + 1;
+- tRNS_alpha = new byte[numEntries];
+- tRNS_colorType = PNG_COLOR_PALETTE;
+- System.arraycopy(alpha, 0, tRNS_alpha, 0, numEntries);
+- } else if (tRNS_name.equals("tRNS_Grayscale")) {
+- tRNS_gray = getIntAttribute(tRNS_node, "gray");
+- tRNS_colorType = PNG_COLOR_GRAY;
+- } else if (tRNS_name.equals("tRNS_RGB")) {
+- tRNS_red = getIntAttribute(tRNS_node, "red");
+- tRNS_green = getIntAttribute(tRNS_node, "green");
+- tRNS_blue = getIntAttribute(tRNS_node, "blue");
+- tRNS_colorType = PNG_COLOR_RGB;
+- } else {
+- fatal(node, "Bad child of a tRNS node!");
+- }
+- if (tRNS_node.getNextSibling() != null) {
+- fatal(node, "tRNS node has more than one child!");
+- }
+-
+- tRNS_present = true;
+- } else if (name.equals("zTXt")) {
+- Node zTXt_node = node.getFirstChild();
+- while (zTXt_node != null) {
+- if (!zTXt_node.getNodeName().equals("zTXtEntry")) {
+- fatal(node,
+- "Only an zTXtEntry may be a child of an zTXt!");
+- }
+-
+- String keyword =
+- toPrintableLatin1(getAttribute(zTXt_node, "keyword"));
+- zTXt_keyword.add(keyword);
+-
+- int compressionMethod =
+- getEnumeratedAttribute(zTXt_node, "compressionMethod",
+- zTXt_compressionMethodNames);
+- zTXt_compressionMethod.add(new Integer(compressionMethod));
+-
+- String text = getAttribute(zTXt_node, "text");
+- zTXt_text.add(text);
+-
+- zTXt_node = zTXt_node.getNextSibling();
+- }
+- } else if (name.equals("UnknownChunks")) {
+- Node unknown_node = node.getFirstChild();
+- while (unknown_node != null) {
+- if (!unknown_node.getNodeName().equals("UnknownChunk")) {
+- fatal(node,
+- "Only an UnknownChunk may be a child of an UnknownChunks!");
+- }
+- String chunkType = getAttribute(unknown_node, "type");
+- Object chunkData =
+- ((IIOMetadataNode)unknown_node).getUserObject();
+-
+- if (chunkType.length() != 4) {
+- fatal(unknown_node,
+- "Chunk type must be 4 characters!");
+- }
+- if (chunkData == null) {
+- fatal(unknown_node,
+- "No chunk data present in user object!");
+- }
+- if (!(chunkData instanceof byte[])) {
+- fatal(unknown_node,
+- "User object not a byte array!");
+- }
+- unknownChunkType.add(chunkType);
+- unknownChunkData.add(((byte[])chunkData).clone());
+-
+- unknown_node = unknown_node.getNextSibling();
+- }
+- } else {
+- fatal(node, "Unknown child of root node!");
+- }
+-
+- node = node.getNextSibling();
+- }
+- }
+-
+- private boolean isISOLatin(String s) {
+- int len = s.length();
+- for (int i = 0; i < len; i++) {
+- if (s.charAt(i) > 255) {
+- return false;
+- }
+- }
+- return true;
+- }
+-
+- private void mergeStandardTree(Node root)
+- throws IIOInvalidTreeException {
+- Node node = root;
+- if (!node.getNodeName()
+- .equals(IIOMetadataFormatImpl.standardMetadataFormatName)) {
+- fatal(node, "Root must be " +
+- IIOMetadataFormatImpl.standardMetadataFormatName);
+- }
+-
+- node = node.getFirstChild();
+- while(node != null) {
+- String name = node.getNodeName();
+-
+- if (name.equals("Chroma")) {
+- Node child = node.getFirstChild();
+- while (child != null) {
+- String childName = child.getNodeName();
+- if (childName.equals("Gamma")) {
+- float gamma = getFloatAttribute(child, "value");
+- gAMA_present = true;
+- gAMA_gamma = (int)(gamma*100000 + 0.5);
+- } else if (childName.equals("Palette")) {
+- byte[] red = new byte[256];
+- byte[] green = new byte[256];
+- byte[] blue = new byte[256];
+- int maxindex = -1;
+-
+- Node entry = child.getFirstChild();
+- while (entry != null) {
+- String entryName = entry.getNodeName();
+- if(entryName.equals("PaletteEntry")) {
+- int index = getIntAttribute(entry, "index");
+- if (index >= 0 && index <= 255) {
+- red[index] =
+- (byte)getIntAttribute(entry, "red");
+- green[index] =
+- (byte)getIntAttribute(entry, "green");
+- blue[index] =
+- (byte)getIntAttribute(entry, "blue");
+- if (index > maxindex) {
+- maxindex = index;
+- }
+- }
+- }
+- entry = entry.getNextSibling();
+- }
+-
+- int numEntries = maxindex + 1;
+- PLTE_red = new byte[numEntries];
+- PLTE_green = new byte[numEntries];
+- PLTE_blue = new byte[numEntries];
+- System.arraycopy(red, 0, PLTE_red, 0, numEntries);
+- System.arraycopy(green, 0, PLTE_green, 0, numEntries);
+- System.arraycopy(blue, 0, PLTE_blue, 0, numEntries);
+- PLTE_present = true;
+- } else if (childName.equals("BackgroundIndex")) {
+- bKGD_present = true;
+- bKGD_colorType = PNG_COLOR_PALETTE;
+- bKGD_index = getIntAttribute(child, "value");
+- } else if (childName.equals("BackgroundColor")) {
+- int red = getIntAttribute(child, "red");
+- int green = getIntAttribute(child, "green");
+- int blue = getIntAttribute(child, "blue");
+- if (red == green && red == blue) {
+- bKGD_colorType = PNG_COLOR_GRAY;
+- bKGD_gray = red;
+- } else {
+- bKGD_colorType = PNG_COLOR_RGB;
+- bKGD_red = red;
+- bKGD_green = green;
+- bKGD_blue = blue;
+- }
+- bKGD_present = true;
+- }
+- // } else if (childName.equals("ColorSpaceType")) {
+- // } else if (childName.equals("NumChannels")) {
+-
+- child = child.getNextSibling();
+- }
+- } else if (name.equals("Compression")) {
+- Node child = node.getFirstChild();
+- while (child != null) {
+- String childName = child.getNodeName();
+- if (childName.equals("NumProgressiveScans")) {
+- // Use Adam7 if NumProgressiveScans > 1
+- int scans = getIntAttribute(child, "value");
+- IHDR_interlaceMethod = (scans > 1) ? 1 : 0;
+- // } else if (childName.equals("CompressionTypeName")) {
+- // } else if (childName.equals("Lossless")) {
+- // } else if (childName.equals("BitRate")) {
+- }
+- child = child.getNextSibling();
+- }
+- } else if (name.equals("Data")) {
+- Node child = node.getFirstChild();
+- while (child != null) {
+- String childName = child.getNodeName();
+- if (childName.equals("BitsPerSample")) {
+- String s = getAttribute(child, "value");
+- StringTokenizer t = new StringTokenizer(s);
+- int maxBits = -1;
+- while (t.hasMoreTokens()) {
+- int bits = Integer.parseInt(t.nextToken());
+- if (bits > maxBits) {
+- maxBits = bits;
+- }
+- }
+- if (maxBits < 1) {
+- maxBits = 1;
+- } else if (maxBits == 3) {
+- maxBits = 4;
+- } else if (maxBits > 4 && maxBits < 8) {
+- maxBits = 8;
+- } else if (maxBits > 8) {
+- maxBits = 16;
+- }
+- IHDR_bitDepth = maxBits;
+- } else if (childName.equals("SignificantBitsPerSample")) {
+- String s = getAttribute(child, "value");
+- StringTokenizer t = new StringTokenizer(s);
+- int numTokens = t.countTokens();
+- if (numTokens == 1) {
+- sBIT_colorType = PNG_COLOR_GRAY;
+- sBIT_grayBits = Integer.parseInt(t.nextToken());
+- } else if (numTokens == 2) {
+- sBIT_colorType =
+- PNG_COLOR_GRAY_ALPHA;
+- sBIT_grayBits = Integer.parseInt(t.nextToken());
+- sBIT_alphaBits = Integer.parseInt(t.nextToken());
+- } else if (numTokens == 3) {
+- sBIT_colorType = PNG_COLOR_RGB;
+- sBIT_redBits = Integer.parseInt(t.nextToken());
+- sBIT_greenBits = Integer.parseInt(t.nextToken());
+- sBIT_blueBits = Integer.parseInt(t.nextToken());
+- } else if (numTokens == 4) {
+- sBIT_colorType =
+- PNG_COLOR_RGB_ALPHA;
+- sBIT_redBits = Integer.parseInt(t.nextToken());
+- sBIT_greenBits = Integer.parseInt(t.nextToken());
+- sBIT_blueBits = Integer.parseInt(t.nextToken());
+- sBIT_alphaBits = Integer.parseInt(t.nextToken());
+- }
+- if (numTokens >= 1 && numTokens <= 4) {
+- sBIT_present = true;
+- }
+- // } else if (childName.equals("PlanarConfiguration")) {
+- // } else if (childName.equals("SampleFormat")) {
+- // } else if (childName.equals("SampleMSB")) {
+- }
+- child = child.getNextSibling();
+- }
+- } else if (name.equals("Dimension")) {
+- boolean gotWidth = false;
+- boolean gotHeight = false;
+- boolean gotAspectRatio = false;
+-
+- float width = -1.0F;
+- float height = -1.0F;
+- float aspectRatio = -1.0F;
+-
+- Node child = node.getFirstChild();
+- while (child != null) {
+- String childName = child.getNodeName();
+- if (childName.equals("PixelAspectRatio")) {
+- aspectRatio = getFloatAttribute(child, "value");
+- gotAspectRatio = true;
+- } else if (childName.equals("HorizontalPixelSize")) {
+- width = getFloatAttribute(child, "value");
+- gotWidth = true;
+- } else if (childName.equals("VerticalPixelSize")) {
+- height = getFloatAttribute(child, "value");
+- gotHeight = true;
+- // } else if (childName.equals("ImageOrientation")) {
+- // } else if
+- // (childName.equals("HorizontalPhysicalPixelSpacing")) {
+- // } else if
+- // (childName.equals("VerticalPhysicalPixelSpacing")) {
+- // } else if (childName.equals("HorizontalPosition")) {
+- // } else if (childName.equals("VerticalPosition")) {
+- // } else if (childName.equals("HorizontalPixelOffset")) {
+- // } else if (childName.equals("VerticalPixelOffset")) {
+- }
+- child = child.getNextSibling();
+- }
+-
+- if (gotWidth && gotHeight) {
+- pHYs_present = true;
+- pHYs_unitSpecifier = 1;
+- pHYs_pixelsPerUnitXAxis = (int)(1000.0F/width + 0.5F);
+- pHYs_pixelsPerUnitYAxis = (int)(1000.0F/height + 0.5F);
+- } else if (gotAspectRatio) {
+- pHYs_present = true;
+- pHYs_unitSpecifier = 0;
+-
+- // Find a reasonable rational approximation
+- int denom = 1;
+- for (; denom < 100; denom++) {
+- int num = (int)(aspectRatio*denom);
+- if (Math.abs(num/denom - aspectRatio) < 0.001) {
+- break;
+- }
+- }
+- pHYs_pixelsPerUnitXAxis = (int)(aspectRatio*denom);
+- pHYs_pixelsPerUnitYAxis = denom;
+- }
+- } else if (name.equals("Document")) {
+- Node child = node.getFirstChild();
+- while (child != null) {
+- String childName = child.getNodeName();
+- if (childName.equals("ImageModificationTime")) {
+- tIME_present = true;
+- tIME_year = getIntAttribute(child, "year");
+- tIME_month = getIntAttribute(child, "month");
+- tIME_day = getIntAttribute(child, "day");
+- tIME_hour =
+- getIntAttribute(child, "hour", 0, false);
+- tIME_minute =
+- getIntAttribute(child, "minute", 0, false);
+- tIME_second =
+- getIntAttribute(child, "second", 0, false);
+- // } else if (childName.equals("SubimageInterpretation")) {
+- // } else if (childName.equals("ImageCreationTime")) {
+- }
+- child = child.getNextSibling();
+- }
+- } else if (name.equals("Text")) {
+- Node child = node.getFirstChild();
+- while (child != null) {
+- String childName = child.getNodeName();
+- if (childName.equals("TextEntry")) {
+- String keyword = getAttribute(child, "keyword",
+- "text", false);
+- String value = getAttribute(child, "value");
+- String encoding = getAttribute(child, "encoding",
+- "unknown", false);
+- String language = getAttribute(child, "language",
+- "unknown", false);
+- String compression =
+- getAttribute(child, "compression",
+- "other", false);
+-
+- if (isISOLatin(value)) {
+- if (compression.equals("zip")) {
+- // Use a zTXt node
+- zTXt_keyword.add(toPrintableLatin1(keyword));
+- zTXt_text.add(value);
+- zTXt_compressionMethod.add(new Integer(0));
+- } else {
+- // Use a tEXt node
+- tEXt_keyword.add(toPrintableLatin1(keyword));
+- tEXt_text.add(value);
+- }
+- } else {
+- int flag = compression.equals("zip") ?
+- 1 : 0;
+-
+- // Use an iTXt node
+- iTXt_keyword.add(toPrintableLatin1(keyword));
+- iTXt_compressionFlag.add(new Integer(flag));
+- iTXt_compressionMethod.add(new Integer(0));
+- iTXt_languageTag.add(language);
+- iTXt_translatedKeyword.add(keyword); // fake it
+- iTXt_text.add(value);
+- }
+- }
+- child = child.getNextSibling();
+- }
+- // } else if (name.equals("Transparency")) {
+- // Node child = node.getFirstChild();
+- // while (child != null) {
+- // String childName = child.getNodeName();
+- // if (childName.equals("Alpha")) {
+- // } else if (childName.equals("TransparentIndex")) {
+- // } else if (childName.equals("TransparentColor")) {
+- // } else if (childName.equals("TileTransparencies")) {
+- // } else if (childName.equals("TileOpacities")) {
+- // }
+- // child = child.getNextSibling();
+- // }
+- // } else {
+- // // fatal(node, "Unknown child of root node!");
+- }
+-
+- node = node.getNextSibling();
+- }
+- }
+-
+- // Reset all instance variables to their initial state
+- public void reset() {
+- IHDR_present = false;
+- PLTE_present = false;
+- bKGD_present = false;
+- cHRM_present = false;
+- gAMA_present = false;
+- hIST_present = false;
+- iCCP_present = false;
+- iTXt_keyword = new ArrayList();
+- iTXt_compressionFlag = new ArrayList();
+- iTXt_compressionMethod = new ArrayList();
+- iTXt_languageTag = new ArrayList();
+- iTXt_translatedKeyword = new ArrayList();
+- iTXt_text = new ArrayList();
+- pHYs_present = false;
+- sBIT_present = false;
+- sPLT_present = false;
+- sRGB_present = false;
+- tEXt_keyword = new ArrayList();
+- tEXt_text = new ArrayList();
+- tIME_present = false;
+- tRNS_present = false;
+- zTXt_keyword = new ArrayList();
+- zTXt_compressionMethod = new ArrayList();
+- zTXt_text = new ArrayList();
+- unknownChunkType = new ArrayList();
+- unknownChunkData = new ArrayList();
+- }
+-
+- // BEGIN metadata reading section.
+-
+- private boolean gotHeader = false;
+- private boolean gotMetadata = false;
+-
+- private Decoder decoder = null;
+- private CLibPNGImageReader reader = null;
+-
+- private static int chunkType(String typeString) {
+- char c0 = typeString.charAt(0);
+- char c1 = typeString.charAt(1);
+- char c2 = typeString.charAt(2);
+- char c3 = typeString.charAt(3);
+-
+- int type = (c0 << 24) | (c1 << 16) | (c2 << 8) | c3;
+- return type;
+- }
+-
+- private String readNullTerminatedString(ImageInputStream stream)
+- throws IOException {
+- StringBuffer b = new StringBuffer();
+- int c;
+-
+- while ((c = stream.read()) != 0) {
+- b.append((char)c);
+- }
+- return b.toString();
+- }
+-
+- private void readHeader() throws IIOException {
+- if (gotHeader) {
+- return;
+- }
+-
+- try {
+- mediaLibImage mlibImage = decoder.getImage();
+- int width = mlibImage.getWidth();
+- int height = mlibImage.getHeight();
+- int bitDepth = decoder.getBitDepth();
+- int colorType;
+- switch(mlibImage.getChannels()) {
+- case 1:
+- colorType = decoder.getPalette() == null?
+- PNG_COLOR_GRAY : PNG_COLOR_PALETTE;
+- break;
+- case 2:
+- colorType = PNG_COLOR_GRAY_ALPHA;
+- break;
+- case 3:
+- colorType = PNG_COLOR_RGB;
+- break;
+- case 4:
+- colorType = PNG_COLOR_RGB_ALPHA;
+- break;
+- default:
+- throw new IIOException("Unsupported image type.");
+- }
+-
+- // Compression method 0 (deflate/inflate) is only supported type.
+- int compressionMethod = 0;
+-
+- // Filter method 0 (adaptive filtering) is only supported type.
+- int filterMethod = 0;
+-
+- int interlaceMethod = decoder.getInterlaceMethod();
+-
+- if (width == 0) {
+- throw new IIOException("Image width == 0!");
+- }
+- if (height == 0) {
+- throw new IIOException("Image height == 0!");
+- }
+- if (bitDepth != 1 && bitDepth != 2 && bitDepth != 4 &&
+- bitDepth != 8 && bitDepth != 16) {
+- throw new IIOException("Bit depth must be 1, 2, 4, 8, or 16!");
+- }
+- if (colorType != 0 && colorType != 2 && colorType != 3 &&
+- colorType != 4 && colorType != 6) {
+- throw new IIOException("Color type must be 0, 2, 3, 4, or 6!");
+- }
+- if (colorType == PNG_COLOR_PALETTE && bitDepth == 16) {
+- throw new IIOException("Bad color type/bit depth combination!");
+- }
+- if ((colorType == PNG_COLOR_RGB ||
+- colorType == PNG_COLOR_RGB_ALPHA ||
+- colorType == PNG_COLOR_GRAY_ALPHA) &&
+- (bitDepth != 8 && bitDepth != 16)) {
+- throw new IIOException("Bad color type/bit depth combination!");
+- }
+- if (compressionMethod != 0) {
+- throw new IIOException("Unknown compression method (not 0)!");
+- }
+- if (filterMethod != 0) {
+- throw new IIOException("Unknown filter method (not 0)!");
+- }
+- if (interlaceMethod != 0 && interlaceMethod != 1) {
+- throw new IIOException("Unknown interlace method (not 0 or 1)!");
+- }
+-
+- IHDR_present = true;
+- IHDR_width = width;
+- IHDR_height = height;
+- IHDR_bitDepth = bitDepth;
+- IHDR_colorType = colorType;
+- IHDR_compressionMethod = compressionMethod;
+- IHDR_filterMethod = filterMethod;
+- IHDR_interlaceMethod = interlaceMethod;
+- gotHeader = true;
+- } catch (IOException e) {
+- throw new IIOException("I/O error reading PNG header!", e);
+- }
+- }
+-
+- private void parse_PLTE_chunk() throws IOException {
+- if (PLTE_present) {
+- processWarningOccurred(
+-"A PNG image may not contain more than one PLTE chunk.\n" +
+-"The chunk will be ignored.");
+- return;
+- } else if (IHDR_colorType == PNG_COLOR_GRAY ||
+- IHDR_colorType == PNG_COLOR_GRAY_ALPHA) {
+- processWarningOccurred(
+-"A PNG gray or gray alpha image cannot have a PLTE chunk.\n" +
+-"The chunk will be ignored.");
+- return;
+- }
+-
+- byte[] palette = decoder.getPalette();
+-
+- if(palette != null) {
+- int numEntries = palette.length/3;
+- if (IHDR_colorType == PNG_COLOR_PALETTE) {
+- int maxEntries = 1 << IHDR_bitDepth;
+- if (numEntries > maxEntries) {
+- processWarningOccurred(
+- "PLTE chunk contains too many entries for bit depth, ignoring extras.");
+- numEntries = maxEntries;
+- }
+- }
+-
+- // Round array sizes up to 2^2^n
+- int paletteEntries;
+- if (numEntries > 16) {
+- paletteEntries = 256;
+- } else if (numEntries > 4) {
+- paletteEntries = 16;
+- } else if (numEntries > 2) {
+- paletteEntries = 4;
+- } else {
+- paletteEntries = 2;
+- }
+-
+- PLTE_present = true;
+- PLTE_red = new byte[paletteEntries];
+- PLTE_green = new byte[paletteEntries];
+- PLTE_blue = new byte[paletteEntries];
+-
+- int index = 0;
+- for (int i = 0; i < numEntries; i++) {
+- PLTE_red[i] = palette[index++];
+- PLTE_green[i] = palette[index++];
+- PLTE_blue[i] = palette[index++];
+- }
+- }
+- }
+-
+- private void parse_bKGD_chunk() throws IOException {
+- int[] background = decoder.getBackground();
+- if(background != null) {
+- if (IHDR_colorType == PNG_COLOR_PALETTE) {
+- bKGD_colorType = PNG_COLOR_PALETTE;
+- bKGD_index = background[0];
+- } else if (IHDR_colorType == PNG_COLOR_GRAY ||
+- IHDR_colorType == PNG_COLOR_GRAY_ALPHA) {
+- bKGD_colorType = PNG_COLOR_GRAY;
+- bKGD_gray = background[0];
+- } else { // RGB or RGB_ALPHA
+- bKGD_colorType = PNG_COLOR_RGB;
+- bKGD_red = background[0];
+- bKGD_green = background[1];
+- bKGD_blue = background[2];
+- }
+-
+- bKGD_present = true;
+- }
+- }
+-
+- private void parse_cHRM_chunk() throws IOException {
+- int[] chrm = decoder.getAllPrimaryChromaticities();
+- if(chrm != null) {
+- int i = 0;
+- cHRM_whitePointX = chrm[i++];
+- cHRM_whitePointY = chrm[i++];
+- cHRM_redX = chrm[i++];
+- cHRM_redY = chrm[i++];
+- cHRM_greenX = chrm[i++];
+- cHRM_greenY = chrm[i++];
+- cHRM_blueX = chrm[i++];
+- cHRM_blueY = chrm[i++];
+-
+- cHRM_present = true;
+- }
+- }
+-
+- private void parse_gAMA_chunk() throws IOException {
+- int gamma = decoder.getImageGamma();
+- if(gamma != decoder.PNG_gAMA_DEFAULT) {
+- gAMA_gamma = gamma;
+-
+- gAMA_present = true;
+- }
+- }
+-
+- private void parse_hIST_chunk() throws IOException, IIOException {
+- short[] histogram = decoder.getHistogram();
+- if(histogram != null) {
+- if (!PLTE_present) {
+- throw new IIOException("hIST chunk without prior PLTE chunk!");
+- }
+-
+- int length = Math.min(PLTE_red.length, histogram.length);
+- hIST_histogram = new char[length];
+- for(int i = 0; i < length; i++) {
+- hIST_histogram[i] = (char)histogram[i];
+- }
+-
+- hIST_present = true;
+- }
+- }
+-
+- private void parse_iCCP_chunk() throws IOException {
+- String profileName = decoder.getEmbeddedICCProfileName();
+-
+- if(profileName != null) {
+- iCCP_profileName = profileName;
+-
+- byte[] uncompressedProfile = decoder.getEmbeddedICCProfile();
+-
+- // Need to compress this profile to match metadata specification.
+- Deflater compressor = new Deflater(Deflater.BEST_COMPRESSION);
+- compressor.setInput(uncompressedProfile);
+- compressor.finish();
+-
+- int off = 0;
+- int len = uncompressedProfile.length;
+- byte[] compressedProfile = new byte[uncompressedProfile.length];
+- do {
+- int count = compressor.deflate(compressedProfile, off, len);
+- off += count;
+- len -= count;
+- } while(!compressor.finished());
+-
+- int compressedDataLength = off;
+-
+- iCCP_compressedProfile = new byte[compressedDataLength];
+- System.arraycopy(compressedProfile, 0,
+- iCCP_compressedProfile, 0, compressedDataLength);
+-
+-
+- iCCP_present = true;
+- }
+- }
+-
+- private void parse_pHYs_chunk() throws IOException {
+- int unitSpecifier =
+- decoder.getPhysicalPixelDimensions(decoder.PNG_PIXELS_UNIT_SPECIFIER);
+- if(unitSpecifier != decoder.PNG_pHYs_NOT_DEFINED) {
+- pHYs_pixelsPerUnitXAxis =
+- decoder.getPhysicalPixelDimensions(decoder.PNG_PIXELS_UNIT_X);
+- pHYs_pixelsPerUnitYAxis =
+- decoder.getPhysicalPixelDimensions(decoder.PNG_PIXELS_UNIT_Y);
+- pHYs_unitSpecifier = unitSpecifier;
+-
+- pHYs_present = true;
+- }
+- }
+-
+- private void parse_sBIT_chunk() throws IOException {
+- byte[] sBits = decoder.getSignificantBits();
+- if(sBits != null) {
+- int i = 0;
+- int colorType = IHDR_colorType;
+- if (colorType == PNG_COLOR_GRAY ||
+- colorType == PNG_COLOR_GRAY_ALPHA) {
+- sBIT_grayBits = sBits[i++];
+- } else if (colorType == PNG_COLOR_RGB ||
+- colorType == PNG_COLOR_PALETTE ||
+- colorType == PNG_COLOR_RGB_ALPHA) {
+- sBIT_redBits = sBits[i++];
+- sBIT_greenBits = sBits[i++];
+- sBIT_blueBits = sBits[i++];
+- }
+-
+- if (colorType == PNG_COLOR_GRAY_ALPHA ||
+- colorType == PNG_COLOR_RGB_ALPHA) {
+- sBIT_alphaBits = sBits[i++];
+- }
+-
+- sBIT_colorType = colorType;
+- sBIT_present = true;
+- }
+- }
+-
+- private void parse_sPLT_chunk()
+- throws IOException, IIOException {
+-
+- PNGChunk[] sPLTChunks = decoder.getSuggestedPalette();
+-
+- if(sPLTChunks != null &&
+- sPLTChunks.length > 0 && sPLTChunks[0] != null) {
+- PNGChunk sPLTChunk = sPLTChunks[0];
+- byte[] chunkData = sPLTChunk.getData();
+- int chunkLength = chunkData.length;
+-
+- InputStream is = new ByteArrayInputStream(sPLTChunk.getData());
+- ImageInputStream stream = new MemoryCacheImageInputStream(is);
+-
+- sPLT_paletteName = readNullTerminatedString(stream);
+- chunkLength -= sPLT_paletteName.length() + 1;
+-
+- int sampleDepth = stream.readUnsignedByte();
+- sPLT_sampleDepth = sampleDepth;
+-
+- int numEntries = chunkLength/(4*(sampleDepth/8) + 2);
+- sPLT_red = new int[numEntries];
+- sPLT_green = new int[numEntries];
+- sPLT_blue = new int[numEntries];
+- sPLT_alpha = new int[numEntries];
+- sPLT_frequency = new int[numEntries];
+-
+- if (sampleDepth == 8) {
+- for (int i = 0; i < numEntries; i++) {
+- sPLT_red[i] = stream.readUnsignedByte();
+- sPLT_green[i] = stream.readUnsignedByte();
+- sPLT_blue[i] = stream.readUnsignedByte();
+- sPLT_alpha[i] = stream.readUnsignedByte();
+- sPLT_frequency[i] = stream.readUnsignedShort();
+- }
+- } else if (sampleDepth == 16) {
+- for (int i = 0; i < numEntries; i++) {
+- sPLT_red[i] = stream.readUnsignedShort();
+- sPLT_green[i] = stream.readUnsignedShort();
+- sPLT_blue[i] = stream.readUnsignedShort();
+- sPLT_alpha[i] = stream.readUnsignedShort();
+- sPLT_frequency[i] = stream.readUnsignedShort();
+- }
+- } else {
+- throw new IIOException("sPLT sample depth not 8 or 16!");
+- }
+-
+- sPLT_present = true;
+- }
+- }
+-
+- private void parse_sRGB_chunk() throws IOException {
+- int renderingIntent = decoder.getStandardRGB();
+- if(renderingIntent != decoder.PNG_sRGB_NOT_DEFINED) {
+- sRGB_renderingIntent = renderingIntent;
+- sRGB_present = true;
+- }
+- }
+-
+- private void parse_tIME_chunk() throws IOException {
+- Calendar cal = decoder.getLastModificationTime();
+- if(cal != null) {
+- tIME_year = cal.get(Calendar.YEAR);
+- tIME_month = cal.get(Calendar.MONTH) + 1;
+- tIME_day = cal.get(Calendar.DAY_OF_MONTH);
+- tIME_hour = cal.get(Calendar.HOUR_OF_DAY);
+- tIME_minute = cal.get(Calendar.MINUTE);
+- tIME_second = cal.get(Calendar.SECOND);
+-
+- tIME_present = true;
+- }
+- }
+-
+- private void parse_tRNS_chunk() throws IOException {
+- int[] transparency = decoder.getTransparency();
+-
+- if(transparency == null) {
+- return;
+- }
+-
+- int colorType = IHDR_colorType;
+- if (colorType == PNG_COLOR_PALETTE) {
+- if (!PLTE_present) {
+- processWarningOccurred(
+-"tRNS chunk without prior PLTE chunk, ignoring it.");
+- return;
+- }
+-
+- // Alpha table may have fewer entries than RGB palette
+- int maxEntries = PLTE_red.length;
+- int numEntries = transparency.length;
+- if (numEntries > maxEntries) {
+- processWarningOccurred(
+-"tRNS chunk has more entries than prior PLTE chunk, ignoring extras.");
+- numEntries = maxEntries;
+- }
+- tRNS_alpha = new byte[numEntries];
+- tRNS_colorType = PNG_COLOR_PALETTE;
+- for(int i = 0; i < numEntries; i++) {
+- tRNS_alpha[i] = (byte)transparency[i];
+- }
+- } else if (colorType == PNG_COLOR_GRAY) {
+- if (transparency.length != 1) {
+- processWarningOccurred(
+-"tRNS chunk for gray image must have length 2, ignoring chunk.");
+- return;
+- }
+- tRNS_gray = transparency[0];
+- tRNS_colorType = PNG_COLOR_GRAY;
+- } else if (colorType == PNG_COLOR_RGB) {
+- if (transparency.length != 3) {
+- processWarningOccurred(
+-"tRNS chunk for RGB image must have length 6, ignoring chunk.");
+- return;
+- }
+- tRNS_red = transparency[0];
+- tRNS_green = transparency[1];
+- tRNS_blue = transparency[2];
+- tRNS_colorType = PNG_COLOR_RGB;
+- } else {
+- processWarningOccurred(
+-"Gray+Alpha and RGBA images may not have a tRNS chunk, ignoring it.");
+- return;
+- }
+-
+- tRNS_present = true;
+- }
+-
+- // Parse all iTXt, tEXt, and zTXt chunks.
+- private void parseTextChunk() throws IOException {
+- PNGTextualData[] textualData = decoder.getTextualData();
+-
+- if(textualData != null) {
+- for(int i = 0; i < textualData.length; i++) {
+- PNGTextualData textData = textualData[i];
+- String keyword = textData.getKeyword();
+- String text = textData.getText();
+- String translatedKeyword = textData.getTranslatedKeyword();
+-
+- // No way to detect a zTXt chunk to use tEXt for zTXt.
+- // Also, all text is already decompressed.
+- if(keyword.equals(translatedKeyword)) { // tEXt and zTXt
+- tEXt_keyword.add(keyword);
+- tEXt_text.add(text);
+- } else { // iTXt
+- iTXt_keyword.add(keyword);
+- iTXt_text.add(text);
+- iTXt_translatedKeyword.add(translatedKeyword);
+-
+- // XXX No access to compression flag so set to 'false'
+- // as text is decompressed by codecLib.
+- int compressionFlag = 0;
+- iTXt_compressionFlag.add(new Integer(compressionFlag));
+-
+- // No access to compression method but only specified
+- // one is '0' (deflate compression with ZLib data stream).
+- int compressionMethod = 0;
+- iTXt_compressionMethod.add(new Integer(compressionMethod));
+-
+- String languageTag = textData.getEncoding();
+- iTXt_languageTag.add(languageTag);
+- }
+- }
+- }
+- }
+-
+- synchronized void readMetadata(CLibPNGImageReader reader,
+- Decoder decoder) throws IIOException {
+- if (gotMetadata) {
+- return;
+- }
+-
+- this.reader = reader;
+- this.decoder = decoder;
+-
+- readHeader();
+-
+- try {
+- parse_PLTE_chunk();
+- parse_bKGD_chunk();
+- parse_cHRM_chunk();
+- parse_gAMA_chunk();
+- parse_hIST_chunk();
+- parse_iCCP_chunk();
+- parse_pHYs_chunk();
+- parse_sBIT_chunk();
+- parse_sPLT_chunk();
+- parse_sRGB_chunk();
+- parse_tIME_chunk();
+- parse_tRNS_chunk();
+-
+- parseTextChunk();
+-
+- PNGChunk[] userChunks = decoder.getUserData();
+- if(userChunks != null) {
+- for(int i = 0; i < userChunks.length; i++) {
+- // Read an unknown chunk
+- PNGChunk userChunk = userChunks[i];
+-
+- int chunkType = userChunk.getID();
+- byte[] b = userChunk.getData();
+-
+- StringBuffer chunkName = new StringBuffer(4);
+- chunkName.append((char)(chunkType >>> 24));
+- chunkName.append((char)((chunkType >> 16) & 0xff));
+- chunkName.append((char)((chunkType >> 8) & 0xff));
+- chunkName.append((char)(chunkType & 0xff));
+-
+- int ancillaryBit = chunkType >>> 28;
+- if (ancillaryBit == 0) {
+- processWarningOccurred(
+- "Encountered unknown chunk with critical bit set!");
+- }
+-
+- unknownChunkType.add(chunkName.toString());
+- unknownChunkData.add(b);
+- }
+- }
+- } catch (IOException e) {
+- throw new IIOException("Error reading PNG metadata", e);
+- } finally {
+- this.reader = null;
+- this.decoder = null;
+- }
+-
+- gotMetadata = true;
+- }
+-
+- void processWarningOccurred(String warning) {
+- if(reader != null) {
+- reader.forwardWarningMessage(warning);
+- }
+- }
+-
+- // END metadata reading methods.
+-
+- // BEGIN metadata writing methods.
+-
+- synchronized void writeMetadata(Encoder encoder) throws IIOException {
+- if(IHDR_present) {
+- encoder.setBitDepth(IHDR_bitDepth);
+- encoder.setInterlaceMethod(IHDR_interlaceMethod == 0 ?
+- Encoder.PNG_INTERLACE_METHOD_DEFAULT :
+- Encoder.PNG_INTERLACE_METHOD_ADAM7);
+- }
+-
+- if(PLTE_present) {
+- int paletteLength = PLTE_red.length;
+- byte[] palette = new byte[3*paletteLength];
+- for(int i = 0, j= 0; i < paletteLength; i++) {
+- palette[j++] = PLTE_red[i];
+- palette[j++] = PLTE_green[i];
+- palette[j++] = PLTE_blue[i];
+- }
+- encoder.setPalette(palette);
+- }
+-
+- if(bKGD_present) {
+- int[] color;
+- switch(bKGD_colorType) {
+- case PNG_COLOR_GRAY:
+- color = new int[] {bKGD_gray};
+- break;
+- case PNG_COLOR_PALETTE:
+- color = new int[] {bKGD_index};
+- break;
+- default:
+- color = new int[] {bKGD_red, bKGD_green, bKGD_blue};
+- }
+- encoder.setBackground(color);
+- }
+-
+- if(cHRM_present) {
+- encoder.setPrimaryChromaticities(cHRM_whitePointX,
+- cHRM_whitePointY,
+- cHRM_redX, cHRM_redY,
+- cHRM_greenX, cHRM_greenY,
+- cHRM_blueX, cHRM_blueY);
+- }
+-
+- if(gAMA_present) {
+- encoder.setImageGamma(gAMA_gamma);
+- }
+-
+- if(hIST_present) {
+- int histogramLength = hIST_histogram.length;
+- short[] histogram = new short[histogramLength];
+- for(int i = 0; i < histogramLength; i++) {
+- histogram[i] = (short)hIST_histogram[i];
+- }
+- encoder.setHistogram(histogram);
+- }
+-
+- if(iCCP_present) {
+- // Encoder expects an uncompressed profile so decompress.
+- Inflater decompresser = new Inflater();
+- decompresser.setInput(iCCP_compressedProfile);
+- byte[] result = new byte[2*decompresser.getRemaining()];
+-
+- int off = 0;
+- try {
+- do {
+- off +=
+- decompresser.inflate(result, off, result.length - off);
+- if(off == result.length && !decompresser.finished()) {
+- byte[] tmpbuf = new byte[2*result.length];
+- System.arraycopy(result, 0, tmpbuf, 0, result.length);
+- result = tmpbuf;
+- }
+- } while(!decompresser.finished());
+- decompresser.end();
+-
+- byte[] uncompressedProfile;
+- if(off == result.length) {
+- uncompressedProfile = result;
+- } else {
+- uncompressedProfile = new byte[off];
+- System.arraycopy(result, 0, uncompressedProfile, 0, off);
+- }
+-
+- String iCCPName = toPrintableLatin1(iCCP_profileName);
+- encoder.setEmbeddedICCProfile(iCCPName, uncompressedProfile);
+- } catch(DataFormatException e) {
+- // XXX warning message?
+- }
+- }
+-
+- if(iTXt_keyword.size() > 0) {
+- int numChunks = iTXt_keyword.size();
+- for(int i = 0; i < numChunks; i++) {
+- Integer compressionFlag =
+- Integer.valueOf((String)iTXt_compressionFlag.get(i));
+- encoder.setUnicodeTextualData
+- ((String)iTXt_keyword.get(i),
+- (String)iTXt_translatedKeyword.get(i),
+- (String)iTXt_languageTag.get(i),
+- (String)iTXt_text.get(i),
+- compressionFlag.intValue() == 1);
+- }
+- }
+-
+- if(pHYs_present) {
+- encoder.setPhysicalPixelDimensions(pHYs_pixelsPerUnitXAxis,
+- pHYs_pixelsPerUnitYAxis,
+- pHYs_unitSpecifier);
+- }
+-
+- if(sBIT_present) {
+- byte[] bits;
+- switch(sBIT_colorType) {
+- case PNG_COLOR_GRAY:
+- bits = new byte[] {(byte)(sBIT_grayBits&0xff)};
+- break;
+- case PNG_COLOR_GRAY_ALPHA:
+- bits = new byte[] {(byte)(sBIT_grayBits&0xff),
+- (byte)(sBIT_alphaBits&0xff)};
+- break;
+- case PNG_COLOR_RGB_ALPHA:
+- bits = new byte[] {(byte)(sBIT_redBits&0xff),
+- (byte)(sBIT_greenBits&0xff),
+- (byte)(sBIT_blueBits&0xff),
+- (byte)(sBIT_alphaBits&0xff)};
+- break;
+- default: // RGB and PALETTE
+- bits = new byte[] {(byte)(sBIT_redBits&0xff),
+- (byte)(sBIT_greenBits&0xff),
+- (byte)(sBIT_blueBits&0xff)};
+- break;
+- }
+- encoder.setSignificantBits(bits);
+- }
+-
+- if(sPLT_present) {
+- if(sPLT_sampleDepth == 8) {
+- byte[] red = new byte[sPLT_red.length];
+- byte[] green = new byte[sPLT_green.length];
+- byte[] blue = new byte[sPLT_blue.length];
+- byte[] alpha = new byte[sPLT_alpha.length];
+- short[] frequency = new short[sPLT_frequency.length];
+-
+- int length = red.length;
+- for(int i = 0; i < length; i++) {
+- red[i] = (byte)(sPLT_red[i]&0xff);
+- green[i] = (byte)(sPLT_green[i]&0xff);
+- blue[i] = (byte)(sPLT_blue[i]&0xff);
+- alpha[i] = (byte)(sPLT_alpha[i]&0xff);
+- frequency[i] = (short)(sPLT_frequency[i]&0xffff);
+- }
+-
+- String sPLTName = toPrintableLatin1(sPLT_paletteName);
+- encoder.setSuggestedPalette(sPLTName,
+- red, green, blue, alpha,
+- frequency);
+- } else {
+- short[] red = new short[sPLT_red.length];
+- short[] green = new short[sPLT_green.length];
+- short[] blue = new short[sPLT_blue.length];
+- short[] alpha = new short[sPLT_alpha.length];
+- short[] frequency = new short[sPLT_frequency.length];
+-
+- int length = red.length;
+- for(int i = 0; i < length; i++) {
+- red[i] = (short)(sPLT_red[i]&0xffff);
+- green[i] = (short)(sPLT_green[i]&0xffff);
+- blue[i] = (short)(sPLT_blue[i]&0xffff);
+- alpha[i] = (short)(sPLT_alpha[i]&0xffff);
+- frequency[i] = (short)(sPLT_frequency[i]&0xffff);
+- }
+-
+- String sPLTName = toPrintableLatin1(sPLT_paletteName);
+- encoder.setSuggestedPalette(sPLTName,
+- red, green, blue, alpha,
+- frequency);
+- }
+- }
+-
+- if(sRGB_present) {
+- encoder.setStandardRGB(sRGB_renderingIntent);
+- }
+-
+- if(tEXt_keyword.size() > 0) {
+- int numChunks = tEXt_keyword.size();
+- for(int i = 0; i < numChunks; i++) {
+- encoder.setTextualData((String)tEXt_keyword.get(i),
+- (String)tEXt_text.get(i),
+- false);
+- }
+- }
+-
+- if(tIME_present) {
+- encoder.setLastModificationTime
+- (new GregorianCalendar(tIME_year, tIME_month - 1, tIME_day,
+- tIME_hour, tIME_minute, tIME_second));
+- }
+-
+- if(tRNS_present) {
+- if(tRNS_colorType == PNG_COLOR_GRAY) {
+- encoder.setTransparency(tRNS_gray, tRNS_gray, tRNS_gray);
+- } else if(tRNS_colorType == PNG_COLOR_PALETTE) {
+- int length = tRNS_alpha.length;
+- int[] color = new int[length];
+- for(int i = 0; i < length; i++) {
+- color[i] = tRNS_alpha[i]&0xff;
+- }
+- encoder.setTransparency(color);
+- } else {
+- encoder.setTransparency(tRNS_red, tRNS_green, tRNS_blue);
+- }
+- }
+-
+- if(zTXt_keyword.size() > 0) {
+- int numChunks = zTXt_keyword.size();
+- for(int i = 0; i < numChunks; i++) {
+- encoder.setTextualData((String)zTXt_keyword.get(i),
+- (String)zTXt_text.get(i),
+- true);
+- }
+- }
+-
+- if(unknownChunkType.size() > 0) {
+- int numChunks = unknownChunkType.size();
+- for(int i = 0; i < numChunks; i++) {
+- encoder.setUserData((String)unknownChunkType.get(i),
+- (byte[])unknownChunkData.get(i),
+- Encoder.PNG_SAVE_BEFORE_IMAGE_DATA);
+- }
+- }
+- }
+-
+- // END metadata writing methods.
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/png/I18N.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/png/I18N.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/png/I18N.java 2005-02-11 00:01:39.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/png/I18N.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,53 +0,0 @@
+-/*
+- * $RCSfile: I18N.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:39 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.png;
+-
+-import com.sun.media.imageioimpl.common.I18NImpl;
+-
+-final class I18N extends I18NImpl {
+- static String getString(String key) {
+- return getString("com.sun.media.imageioimpl.plugins.png.I18N", key);
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/png/properties zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/png/properties
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/png/properties 2005-05-10 20:09:34.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/png/properties 1969-12-31 19:00:00.000000000 -0500
+@@ -1,18 +0,0 @@
+-#
+-# $RCSfile: properties,v $
+-#
+-# Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
+-#
+-# Use is subject to license terms.
+-#
+-# $Revision: 1.2 $
+-# $Date: 2005/05/11 00:09:34 $
+-# $State: Exp $
+-#
+-# Internationalization file for com.sun.media.imageioimpl.plugins.png
+-
+-CLibPNGImageReader0=Decoder cannot decode input.
+-
+-CLibPNGImageWriteParam0=Best Compression
+-CLibPNGImageWriteParam1=Best Speed
+-CLibPNGImageWriteParam2=No Compression
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFCodecLibFaxDecompressor.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFCodecLibFaxDecompressor.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFCodecLibFaxDecompressor.java 2005-02-11 00:01:44.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFCodecLibFaxDecompressor.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,208 +0,0 @@
+-/*
+- * $RCSfile: TIFFCodecLibFaxDecompressor.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:44 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.tiff;
+-
+-import java.io.IOException;
+-import com.sun.media.imageio.plugins.tiff.BaselineTIFFTagSet;
+-import com.sun.media.imageio.plugins.tiff.TIFFDecompressor;
+-
+-public class TIFFCodecLibFaxDecompressor extends TIFFFaxDecompressor {
+-
+- private static final boolean DEBUG = false; // XXX 'false' for release!!!
+-
+- /**
+- * com.sun.medialib.codec.g3fax.Decoder for T.4 or
+- * com.sun.medialib.codec.g4fax.Decoder for T.6.
+- */
+- private Object decoder = null;
+-
+- /**
+- * Constructor which initializes the internal codecLib decoder.
+- *
+- * @throws RuntimeException if bilevelCompression
is
+- * not T.4 or T.6 compression or if codecLib is not available.
+- */
+- public TIFFCodecLibFaxDecompressor(int bilevelCompression) {
+- super();
+-
+- try {
+- // 'compression' is set in the superclass method.
+- if(bilevelCompression ==
+- BaselineTIFFTagSet.COMPRESSION_CCITT_T_4) {
+- com.sun.medialib.codec.g3fax.Decoder decoder =
+- new com.sun.medialib.codec.g3fax.Decoder();
+- this.decoder = decoder;
+- } else if(bilevelCompression ==
+- BaselineTIFFTagSet.COMPRESSION_CCITT_T_6) {
+- com.sun.medialib.codec.g4fax.Decoder decoder =
+- new com.sun.medialib.codec.g4fax.Decoder();
+- this.decoder = decoder;
+- } else {
+- throw new RuntimeException("Unknown compression = "+
+- bilevelCompression);
+- }
+- } catch (Throwable e) {
+- throw new RuntimeException("CodecLib not available");
+- }
+-}
+-
+- public synchronized final void decodeRaw(byte[] b, int dstOffset,
+- int pixelBitStride, // always 1
+- int scanlineStride)
+- throws IOException {
+-
+- int bytesPerRow = (srcWidth + 7)/8;
+- byte[] image = null;
+- byte[] code = new byte[byteCount];
+- stream.seek(offset);
+- stream.readFully(code, 0, byteCount);
+-
+- // Flip the bytes if fill order is LSB-to-MSB.
+- if(fillOrder == 2) {
+- for(int i = 0; i < byteCount; i++) {
+- code[i] = flipTable[code[i]&0xff];
+- }
+- }
+-
+- if (dstOffset == 0 && bytesPerRow == scanlineStride) {
+- image = b;
+- } else {
+- image = new byte[srcWidth*srcHeight];
+- }
+-
+- if (compression == BaselineTIFFTagSet.COMPRESSION_CCITT_T_6) {
+- com.sun.medialib.codec.g4fax.Decoder decoder =
+- (com.sun.medialib.codec.g4fax.Decoder)this.decoder;
+-
+- if(DEBUG) {
+- System.out.println("Using MediaLib G4 decoder");
+- }
+-
+- int result = com.sun.medialib.codec.g4fax.Constants.G4FAX_FAILURE;
+- try {
+- result = decoder.decode(image, code, srcWidth, srcHeight, 0);
+- } catch(Throwable t) {
+- ((TIFFImageReader)reader).forwardWarningMessage
+- ("codecLib T.6 decompressor failed; falling back to Java.");
+- result = com.sun.medialib.codec.g4fax.Constants.G4FAX_FAILURE;
+- }
+-
+- if(result ==
+- com.sun.medialib.codec.g4fax.Constants.G4FAX_FAILURE) {
+- // Fall back to Java decoder.
+- if(DEBUG) {
+- System.out.println("Falling back to Java G4 decoder");
+- }
+- super.decodeRaw(b, dstOffset, pixelBitStride, scanlineStride);
+- return;
+- }
+- } else {
+- com.sun.medialib.codec.g3fax.Decoder decoder =
+- (com.sun.medialib.codec.g3fax.Decoder)this.decoder;
+- if(DEBUG) {
+- System.out.println("Using MediaLib G3 decoder");
+- }
+-
+- int decodingFlags = 0;
+- if(oneD == 1) {
+- decodingFlags =
+- decoder.G3FAX_VERTICAL_CODING |
+- decoder.G3FAX_NORTC;
+- if(DEBUG) {
+- System.out.print("G3FAX_VERTICAL_CODING"+
+- " | G3FAX_NORTC");
+- }
+- } else {
+- decodingFlags =
+- decoder.G3FAX_HORIZONTAL_CODING |
+- decoder.G3FAX_NORTC;
+- if(DEBUG) {
+- System.out.print("G3FAX_HORIZONTAL_CODING"+
+- " | G3FAX_NORTC");
+- }
+- }
+-
+- if(fillBits == 1) {
+- if(DEBUG) {
+- System.out.print(" | G3FAX_EOLPADDING_CODING");
+- }
+- decodingFlags |= decoder.G3FAX_EOLPADDING;
+- }
+-
+- if(DEBUG) {
+- System.out.println("");
+- }
+-
+- int result = com.sun.medialib.codec.g3fax.Constants.G3FAX_FAILURE;
+- try {
+- result = decoder.decode(image, code, srcWidth, srcHeight,
+- decodingFlags);
+- } catch(Throwable t) {
+- ((TIFFImageReader)reader).forwardWarningMessage
+- ("codecLib T.4 decompressor failed; falling back to Java.");
+- result = com.sun.medialib.codec.g3fax.Constants.G3FAX_FAILURE;
+- }
+-
+- if(result ==
+- com.sun.medialib.codec.g3fax.Constants.G3FAX_FAILURE) {
+- // Fall back to Java decoder.
+- if(DEBUG) {
+- System.out.println("Falling back to Java G3 decoder");
+- }
+- super.decodeRaw(b, dstOffset, pixelBitStride, scanlineStride);
+- return;
+- }
+- }
+-
+- if (image != b) {
+- int srcOffset = 0;
+- for (int row = 0; row < srcHeight; row++) {
+- System.arraycopy(image, srcOffset, b, dstOffset, bytesPerRow);
+- srcOffset += bytesPerRow;
+- dstOffset += scanlineStride;
+- }
+- }
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFCodecLibRLECompressor.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFCodecLibRLECompressor.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFCodecLibRLECompressor.java 2006-04-21 20:04:23.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFCodecLibRLECompressor.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,145 +0,0 @@
+-/*
+- * $RCSfile: TIFFCodecLibRLECompressor.java,v $
+- *
+- *
+- * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2006/04/22 00:04:23 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.tiff;
+-
+-import java.io.IOException;
+-import javax.imageio.IIOException;
+-
+-public class TIFFCodecLibRLECompressor extends TIFFRLECompressor {
+-
+- private static final boolean DEBUG = false; // XXX 'false' for release!!!
+-
+- Object encoder;
+-
+- public TIFFCodecLibRLECompressor() {
+- super();
+-
+- try {
+- com.sun.medialib.codec.g3fax.Encoder encoder =
+- new com.sun.medialib.codec.g3fax.Encoder();
+- this.encoder = encoder;
+- } catch(Throwable t) {
+- throw new RuntimeException("CodecLib not available");
+- }
+- }
+-
+- public int encode(byte[] b, int off,
+- int width, int height,
+- int[] bitsPerSample,
+- int scanlineStride) throws IOException {
+- if (bitsPerSample.length != 1 || bitsPerSample[0] != 1) {
+- throw new IIOException
+- ("Bits per sample must be 1 for RLE compression!");
+- }
+-
+- // Set image to data if possible; otherwise copy.
+- int bytesPerRow = (width + 7)/8;
+- byte[] image = null;
+-
+- if(off == 0 && bytesPerRow == scanlineStride) {
+- image = b;
+- } else {
+- image = new byte[bytesPerRow*height];
+- int dataOffset = off;
+- int imageOffset = 0;
+- for(int row = 0; row < height; row++) {
+- System.arraycopy(b, dataOffset, image, imageOffset,
+- bytesPerRow);
+- dataOffset += scanlineStride;
+- imageOffset += bytesPerRow;
+- }
+- }
+-
+- // In the worst case, 2 bits of input will result in 9 bits of output,
+- // plus 2 extra bits if the row starts with black.
+- int maxBits = 9*((width + 1)/2) + 2;
+- byte[] compData = new byte[((maxBits + 7)/8)*height];
+-
+- // Attempt the codecLib encoder.
+- com.sun.medialib.codec.g3fax.Encoder clibEncoder =
+- (com.sun.medialib.codec.g3fax.Encoder)encoder;
+-
+- // Set RLE encoding flag.
+- int encodingFlags =
+- com.sun.medialib.codec.g3fax.Constants.G3FAX_RLE_CODING;
+- if(inverseFill) {
+- encodingFlags |=
+- com.sun.medialib.codec.g3fax.Constants.G3FAX_LSB2MSB;
+- if(DEBUG) {
+- System.out.println("Setting LSB flag");
+- }
+- }
+-
+- // Set result flag.
+- int result =
+- com.sun.medialib.codec.g3fax.Constants.G3FAX_FAILURE;
+- try {
+- if(DEBUG) {
+- System.out.println("Using MediaLib RLE encoder");
+- }
+- result = clibEncoder.encode(compData, image, width, height,
+- 2, // k parameter
+- encodingFlags);
+- stream.write(compData, 0, result);
+- } catch(Throwable t) {
+- if(DEBUG) {
+- System.out.println("MediaLib RLE encoder failed: "+t);
+- }
+- // XXX Should write a warning to listeners here.
+- result = com.sun.medialib.codec.g3fax.Constants.G3FAX_FAILURE;
+- }
+-
+- // If the codecLib encoder failed, try the superclass.
+- if(result == com.sun.medialib.codec.g3fax.Constants.G3FAX_FAILURE) {
+- if(DEBUG) {
+- System.out.println("Falling back to Java RLE encoder");
+- }
+- result = super.encode(b, off, width, height,
+- bitsPerSample, scanlineStride);
+- }
+-
+- return result;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFCodecLibT4Compressor.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFCodecLibT4Compressor.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFCodecLibT4Compressor.java 2006-01-30 18:22:03.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFCodecLibT4Compressor.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,162 +0,0 @@
+-/*
+- * $RCSfile: TIFFCodecLibT4Compressor.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.2 $
+- * $Date: 2006/01/30 23:22:03 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.tiff;
+-
+-public class TIFFCodecLibT4Compressor extends TIFFT4Compressor {
+-
+- private static final boolean DEBUG = false; // XXX 'false' for release!!!
+-
+- Object encoder;
+-
+- public TIFFCodecLibT4Compressor() {
+- super();
+-
+- try {
+- com.sun.medialib.codec.g3fax.Encoder encoder =
+- new com.sun.medialib.codec.g3fax.Encoder();
+- this.encoder = encoder;
+- } catch(Throwable t) {
+- throw new RuntimeException("CodecLib not available");
+- }
+- }
+-
+- /**
+- * Encode a buffer of data using CCITT T.4 Compression also known as
+- * Group 3 facsimile compression.
+- *
+- * @param is1DMode Whether to perform one-dimensional encoding.
+- * @param isEOLAligned Whether EOL bit sequences should be padded.
+- * @param data The row of data to compress.
+- * @param lineStride Byte step between the same sample in different rows.
+- * @param colOffset Bit offset within first data[rowOffset]
.
+- * @param width Number of bits in the row.
+- * @param height Number of rows in the buffer.
+- * @param compData The compressed data.
+- *
+- * @return The number of bytes saved in the compressed data array.
+- */
+- public final int encodeT4(boolean is1DMode,
+- boolean isEOLAligned,
+- byte[] data,
+- int lineStride,
+- int colOffset,
+- int width,
+- int height,
+- byte[] compData) {
+-
+- // Defer to superclass if bit offset is not byte-aligned.
+- if(colOffset % 8 != 0) {
+- return super.encodeT4(is1DMode, isEOLAligned,
+- data, lineStride, colOffset,
+- width, height, compData);
+- }
+-
+- // Set image to data if possible; otherwise copy.
+- int bytesPerRow = (width + 7)/8;
+- byte[] image = null;
+-
+- if(colOffset == 0 && bytesPerRow == lineStride) {
+- image = data;
+- } else {
+- image = new byte[bytesPerRow*height];
+- int dataOffset = colOffset / 8;
+- int imageOffset = 0;
+- for(int row = 0; row < height; row++) {
+- System.arraycopy(data, dataOffset, image, imageOffset,
+- bytesPerRow);
+- dataOffset += lineStride;
+- imageOffset += bytesPerRow;
+- }
+- }
+-
+- // Attempt the codecLib encoder.
+- com.sun.medialib.codec.g3fax.Encoder clibEncoder =
+- (com.sun.medialib.codec.g3fax.Encoder)encoder;
+- //System.out.println("Using codecLib G3 encoder");
+-
+- // Set encoding flags.
+- int encodingFlags =
+- is1DMode ?
+- com.sun.medialib.codec.g3fax.Constants.G3FAX_HORIZONTAL_CODING :
+- com.sun.medialib.codec.g3fax.Constants.G3FAX_VERTICAL_CODING;
+- if(isEOLAligned) {
+- encodingFlags |=
+- com.sun.medialib.codec.g3fax.Constants.G3FAX_EOLPADDING;
+- }
+- if(inverseFill) {
+- encodingFlags |=
+- com.sun.medialib.codec.g3fax.Constants.G3FAX_LSB2MSB;
+- }
+-
+- int result =
+- com.sun.medialib.codec.g3fax.Constants.G3FAX_FAILURE;
+- try {
+- if(DEBUG) {
+- System.out.println("Using MediaLib G3 encoder");
+- }
+- result = clibEncoder.encode(compData, image, width, height,
+- 2, // k parameter
+- encodingFlags);
+- } catch(Throwable t) {
+- if(DEBUG) {
+- System.out.println("MediaLib G3 encoder failed: "+t);
+- }
+- // XXX Should write a warning to listeners here.
+- result = com.sun.medialib.codec.g3fax.Constants.G3FAX_FAILURE;
+- }
+-
+- // If the codecLib encoder failed, try the superclass.
+- if(result == com.sun.medialib.codec.g3fax.Constants.G3FAX_FAILURE) {
+- if(DEBUG) {
+- System.out.println("Falling back to Java G3 encoder");
+- }
+- result = super.encodeT4(is1DMode, isEOLAligned,
+- data, lineStride, colOffset,
+- width, height, compData);
+- }
+-
+- return result;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFCodecLibT6Compressor.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFCodecLibT6Compressor.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFCodecLibT6Compressor.java 2006-01-30 18:22:34.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFCodecLibT6Compressor.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,145 +0,0 @@
+-/*
+- * $RCSfile: TIFFCodecLibT6Compressor.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.2 $
+- * $Date: 2006/01/30 23:22:34 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.tiff;
+-
+-public class TIFFCodecLibT6Compressor extends TIFFT6Compressor {
+-
+- private static final boolean DEBUG = false; // XXX 'false' for release!!!
+-
+- Object encoder;
+-
+- public TIFFCodecLibT6Compressor() {
+- super();
+-
+- try {
+- com.sun.medialib.codec.g4fax.Encoder encoder =
+- new com.sun.medialib.codec.g4fax.Encoder();
+- this.encoder = encoder;
+- } catch(Throwable t) {
+- throw new RuntimeException("CodecLib not available");
+- }
+- }
+-
+- /**
+- * Encode a buffer of data using CCITT T.6 Compression also known as
+- * Group 4 facsimile compression.
+- *
+- * @param data The row of data to compress.
+- * @param lineStride Byte step between the same sample in different rows.
+- * @param colOffset Bit offset within first data[rowOffset]
.
+- * @param width Number of bits in the row.
+- * @param height Number of rows in the buffer.
+- * @param compData The compressed data.
+- *
+- * @return The number of bytes saved in the compressed data array.
+- */
+- public synchronized final int encodeT6(byte[] data,
+- int lineStride,
+- int colOffset,
+- int width,
+- int height,
+- byte[] compData) {
+-
+- // Defer to superclass if bit offset is not byte-aligned.
+- if(colOffset % 8 != 0) {
+- return super.encodeT6(data, lineStride, colOffset,
+- width, height, compData);
+- }
+-
+- // Set image to data if possible; otherwise copy.
+- int bytesPerRow = (width + 7)/8;
+- byte[] image = null;
+-
+- if(colOffset == 0 && bytesPerRow == lineStride) {
+- image = data;
+- } else {
+- image = new byte[bytesPerRow*height];
+- int dataOffset = colOffset / 8;
+- int imageOffset = 0;
+- for(int row = 0; row < height; row++) {
+- System.arraycopy(data, dataOffset, image, imageOffset,
+- bytesPerRow);
+- dataOffset += lineStride;
+- imageOffset += bytesPerRow;
+- }
+- }
+-
+- // Attempt the codecLib encoder.
+- com.sun.medialib.codec.g4fax.Encoder clibEncoder =
+- (com.sun.medialib.codec.g4fax.Encoder)encoder;
+- //System.out.println("Using codecLib G4 encoder");
+-
+- // Set encoding flags.
+- int encodingFlags = inverseFill ?
+- com.sun.medialib.codec.g4fax.Constants.G4FAX_LSB2MSB : 0;
+-
+- int result =
+- com.sun.medialib.codec.g4fax.Constants.G4FAX_FAILURE;
+- try {
+- if(DEBUG) {
+- System.out.println("Using MediaLib G4 encoder");
+- }
+- result = clibEncoder.encode(compData, image, width, height,
+- encodingFlags);
+- } catch(Throwable t) {
+- if(DEBUG) {
+- System.out.println("MediaLib G4 encoder failed: "+t);
+- }
+- // XXX Should write a warning to listeners here.
+- result = com.sun.medialib.codec.g4fax.Constants.G4FAX_FAILURE;
+- }
+-
+- // If the codecLib encoder failed, try the superclass.
+- if(result == com.sun.medialib.codec.g4fax.Constants.G4FAX_FAILURE) {
+- if(DEBUG) {
+- System.out.println("Falling back to Java G4 encoder");
+- }
+- result = super.encodeT6(data, lineStride, colOffset,
+- width, height, compData);
+- }
+-
+- return result;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFImageReader.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFImageReader.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFImageReader.java 2007-12-19 15:17:02.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFImageReader.java 2009-11-11 12:52:31.490697135 -0500
+@@ -1227,56 +1227,16 @@
+ }
+ } else if (compression ==
+ BaselineTIFFTagSet.COMPRESSION_CCITT_T_6) {
+-
+- // Try to create the codecLib decompressor.
+- if(PackageUtil.isCodecLibAvailable()) {
+- try {
+- this.decompressor =
+- new TIFFCodecLibFaxDecompressor(compression);
+- if(DEBUG) {
+- System.out.println
+- ("Using codecLib T.6 decompressor");
+- }
+- } catch (RuntimeException re) {
+- if(DEBUG) {
+- System.out.println(re);
+- }
+- }
+- }
+-
+- // Fall back to the Java decompressor.
+- if (this.decompressor == null) {
+- if(DEBUG) {
+- System.out.println("Using Java T.6 decompressor");
+- }
+- this.decompressor = new TIFFFaxDecompressor();
++ if (DEBUG) {
++ System.out.println("Using Java T.6 decompressor");
+ }
++ this.decompressor = new TIFFFaxDecompressor();
+ } else if (compression ==
+ BaselineTIFFTagSet.COMPRESSION_CCITT_T_4) {
+-
+- if(PackageUtil.isCodecLibAvailable()) {
+- // Try to create the codecLib decompressor.
+- try {
+- this.decompressor =
+- new TIFFCodecLibFaxDecompressor(compression);
+- if(DEBUG) {
+- System.out.println
+- ("Using codecLib T.4 decompressor");
+- }
+- } catch (RuntimeException re) {
+- if(DEBUG) {
+- System.out.println(re);
+- }
+- }
+- }
+-
+- // Fall back to the Java decompressor.
+- if (this.decompressor == null) {
+- if(DEBUG) {
+- System.out.println("Using Java T.4 decompressor");
+- }
+- this.decompressor = new TIFFFaxDecompressor();
++ if (DEBUG) {
++ System.out.println("Using Java T.4 decompressor");
+ }
++ this.decompressor = new TIFFFaxDecompressor();
+ } else if (compression ==
+ BaselineTIFFTagSet.COMPRESSION_CCITT_RLE) {
+ this.decompressor = new TIFFFaxDecompressor();
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFImageWriter.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFImageWriter.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFImageWriter.java 2007-08-31 20:27:20.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/tiff/TIFFImageWriter.java 2009-11-11 12:53:17.688759818 -0500
+@@ -841,25 +841,9 @@
+
+ if (compressor == null) {
+ if (compression == BaselineTIFFTagSet.COMPRESSION_CCITT_RLE) {
+- if(PackageUtil.isCodecLibAvailable()) {
+- try {
+- compressor = new TIFFCodecLibRLECompressor();
+- if(DEBUG) {
+- System.out.println
+- ("Using codecLib RLE compressor");
+- }
+- } catch(RuntimeException e) {
+- if(DEBUG) {
+- System.out.println(e);
+- }
+- }
+- }
+-
+- if(compressor == null) {
+- compressor = new TIFFRLECompressor();
+- if(DEBUG) {
+- System.out.println("Using Java RLE compressor");
+- }
++ compressor = new TIFFRLECompressor();
++ if (DEBUG) {
++ System.out.println("Using Java RLE compressor");
+ }
+
+ if (!forcePhotometricInterpretation) {
+@@ -868,25 +852,9 @@
+ }
+ } else if (compression ==
+ BaselineTIFFTagSet.COMPRESSION_CCITT_T_4) {
+- if(PackageUtil.isCodecLibAvailable()) {
+- try {
+- compressor = new TIFFCodecLibT4Compressor();
+- if(DEBUG) {
+- System.out.println
+- ("Using codecLib T.4 compressor");
+- }
+- } catch(RuntimeException e) {
+- if(DEBUG) {
+- System.out.println(e);
+- }
+- }
+- }
+-
+- if(compressor == null) {
+- compressor = new TIFFT4Compressor();
+- if(DEBUG) {
+- System.out.println("Using Java T.4 compressor");
+- }
++ compressor = new TIFFT4Compressor();
++ if (DEBUG) {
++ System.out.println("Using Java T.4 compressor");
+ }
+
+ if (!forcePhotometricInterpretation) {
+@@ -895,25 +863,9 @@
+ }
+ } else if (compression ==
+ BaselineTIFFTagSet.COMPRESSION_CCITT_T_6) {
+- if(PackageUtil.isCodecLibAvailable()) {
+- try {
+- compressor = new TIFFCodecLibT6Compressor();
+- if(DEBUG) {
+- System.out.println
+- ("Using codecLib T.6 compressor");
+- }
+- } catch(RuntimeException e) {
+- if(DEBUG) {
+- System.out.println(e);
+- }
+- }
+- }
+-
+- if(compressor == null) {
+- compressor = new TIFFT6Compressor();
+- if(DEBUG) {
+- System.out.println("Using Java T.6 compressor");
+- }
++ compressor = new TIFFT6Compressor();
++ if (DEBUG) {
++ System.out.println("Using Java T.6 compressor");
+ }
+
+ if (!forcePhotometricInterpretation) {
diff --git a/SOURCES/jai-imageio-core-remove-imageio-services.patch b/SOURCES/jai-imageio-core-remove-imageio-services.patch
new file mode 100644
index 0000000..6808c93
--- /dev/null
+++ b/SOURCES/jai-imageio-core-remove-imageio-services.patch
@@ -0,0 +1,28 @@
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/services/javax.imageio.spi.ImageReaderSpi zzx2/src/share/services/javax.imageio.spi.ImageReaderSpi
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/services/javax.imageio.spi.ImageReaderSpi 2007-09-04 20:21:08.000000000 -0400
++++ zzx2/src/share/services/javax.imageio.spi.ImageReaderSpi 2009-11-11 13:32:55.845761231 -0500
+@@ -44,10 +44,6 @@
+ #
+ # --- JAI-Image I/O ImageReader plug-ins ---
+ #
+-com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageReaderSpi
+-com.sun.media.imageioimpl.plugins.png.CLibPNGImageReaderSpi
+-com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReaderSpi
+-com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReaderCodecLibSpi
+ com.sun.media.imageioimpl.plugins.wbmp.WBMPImageReaderSpi
+ com.sun.media.imageioimpl.plugins.bmp.BMPImageReaderSpi
+ com.sun.media.imageioimpl.plugins.pcx.PCXImageReaderSpi
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/services/javax.imageio.spi.ImageWriterSpi zzx2/src/share/services/javax.imageio.spi.ImageWriterSpi
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/services/javax.imageio.spi.ImageWriterSpi 2007-09-04 20:21:08.000000000 -0400
++++ zzx2/src/share/services/javax.imageio.spi.ImageWriterSpi 2009-11-11 13:32:59.627697630 -0500
+@@ -44,10 +44,6 @@
+ #
+ # --- JAI-Image I/O ImageWriter plug-ins ---
+ #
+-com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageWriterSpi
+-com.sun.media.imageioimpl.plugins.png.CLibPNGImageWriterSpi
+-com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriterSpi
+-com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriterCodecLibSpi
+ com.sun.media.imageioimpl.plugins.wbmp.WBMPImageWriterSpi
+ com.sun.media.imageioimpl.plugins.bmp.BMPImageWriterSpi
+ com.sun.media.imageioimpl.plugins.gif.GIFImageWriterSpi
diff --git a/SOURCES/jai-imageio-core-remove-jai-operations.patch b/SOURCES/jai-imageio-core-remove-jai-operations.patch
new file mode 100644
index 0000000..49cf268
--- /dev/null
+++ b/SOURCES/jai-imageio-core-remove-jai-operations.patch
@@ -0,0 +1,5904 @@
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/I18N.java zzx2/src/share/classes/com/sun/media/jai/imageioimpl/I18N.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/I18N.java 2005-02-11 00:01:54.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/jai/imageioimpl/I18N.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,53 +0,0 @@
+-/*
+- * $RCSfile: I18N.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:54 $
+- * $State: Exp $
+- */
+-package com.sun.media.jai.imageioimpl;
+-
+-import com.sun.media.imageioimpl.common.I18NImpl;
+-
+-final class I18N extends I18NImpl {
+- static String getString(String key) {
+- return getString("com.sun.media.jai.imageioimpl.I18N", key);
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/ImageIOCollectionImage.java zzx2/src/share/classes/com/sun/media/jai/imageioimpl/ImageIOCollectionImage.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/ImageIOCollectionImage.java 2005-02-11 00:01:54.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/jai/imageioimpl/ImageIOCollectionImage.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,74 +0,0 @@
+-/*
+- * $RCSfile: ImageIOCollectionImage.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:54 $
+- * $State: Exp $
+- */
+-package com.sun.media.jai.imageioimpl;
+-
+-import java.util.ArrayList;
+-import javax.media.jai.CollectionImage;
+-
+-/**
+- * A CollectionImage
to be used as the return value from
+- * ImageReadCIF.create()
and ImageWriteCIF.create()
.
+- * The imageCollection
instance variable is a List
.
+- */
+-class ImageIOCollectionImage extends CollectionImage {
+- /**
+- * Creates an ImageIOCollectionImage
with the specified
+- * capacity.
+- *
+- * @exception IllegalArgumentException if capacity
is
+- * not positive.
+- */
+- ImageIOCollectionImage(int capacity) {
+- super();
+-
+- if(capacity <= 0) {
+- // No message as this is not at the API level and it is
+- // the unique exception.
+- throw new IllegalArgumentException();
+- }
+-
+- imageCollection = new ArrayList(capacity);
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadCIF.java zzx2/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadCIF.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadCIF.java 2005-02-11 00:01:54.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadCIF.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,168 +0,0 @@
+-/*
+- * $RCSfile: ImageReadCIF.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:54 $
+- * $State: Exp $
+- */
+-package com.sun.media.jai.imageioimpl;
+-
+-import java.awt.Dimension;
+-import java.awt.RenderingHints;
+-import java.awt.image.renderable.ParameterBlock;
+-import java.util.ArrayList;
+-import java.util.List;
+-import javax.imageio.ImageReader;
+-import javax.media.jai.CollectionImage;
+-import javax.media.jai.CollectionImageFactory;
+-import javax.media.jai.CollectionOp;
+-import javax.media.jai.JAI;
+-import javax.media.jai.PlanarImage;
+-import com.sun.media.jai.operator.ImageReadDescriptor;
+-
+-public class ImageReadCIF implements CollectionImageFactory {
+-
+- static CollectionImage createStatic(ParameterBlock args,
+- RenderingHints hints) {
+-
+- // Clone the ParameterBlock as the ImageChoice will be overwritten.
+- ParameterBlock renderedPB = (ParameterBlock)args.clone();
+-
+- // Get the ImageChoice.
+- int[] imageIndices = (int[])args.getObjectParameter(1);
+-
+- // Variables to be set in the subsequent "if" block.
+- // XXX Could probably collapse the if block into a single code seq.
+- int numSources;
+- ImageIOCollectionImage imageList = null;
+-
+- if(imageIndices == null) {
+- // null-valued ImageChoice: load all images.
+-
+- // Load the first image.
+- renderedPB.set(0, 1);
+- PlanarImage image = JAI.create("ImageRead", renderedPB, hints);
+-
+- // Get the ImageReader property.
+- Object readerProperty =
+- image.getProperty(
+- ImageReadDescriptor.PROPERTY_NAME_IMAGE_READER);
+-
+- // Try to read the number of images.
+- if(readerProperty instanceof ImageReader) {
+- try {
+- // XXX Really should not allow search here. If search
+- // is disallowed and -1 is returned from getNumImages(),
+- // then "ImageRead" should just be called until an
+- // IndexOutOfBoundsException is caught.
+- numSources =
+- ((ImageReader)readerProperty).getNumImages(true);
+- } catch(Exception e) { // IOException
+- // Default to one source.
+- numSources = 1;
+- }
+- } else {
+- numSources = 1;
+- }
+-
+- // Allocate and fill index array.
+- imageIndices = new int[numSources];
+- for(int i = 0; i < numSources; i++) {
+- imageIndices[i] = i;
+- }
+-
+- // Allocate list and add first image.
+- imageList = new ImageIOCollectionImage(numSources);
+- imageList.add(image);
+- } else {
+- // Set the number of sources and create the list.
+- numSources = imageIndices.length;
+- imageList = new ImageIOCollectionImage(numSources);
+-
+- // Load the first image requested.
+- renderedPB.set(imageIndices[0], 1);
+- PlanarImage image = JAI.create("ImageRead", renderedPB, hints);
+-
+- // Add the first image to the list.
+- imageList.add(image);
+- }
+-
+- // Read subsequent images and add to the list.
+- for(int idx = 1; idx < numSources; idx++) {
+- renderedPB.set(imageIndices[idx], 1);
+- PlanarImage image = JAI.create("ImageRead", renderedPB, hints);
+- imageList.add(image);
+- }
+-
+- // Get the first image in the Collection.
+- PlanarImage firstImage = (PlanarImage)imageList.get(0);
+-
+- // Transfer properties to the Collection.
+- ImageReadCRIF.copyProperty(firstImage,
+- imageList,
+- ImageReadDescriptor.PROPERTY_NAME_IMAGE_READ_PARAM);
+- ImageReadCRIF.copyProperty(firstImage,
+- imageList,
+- ImageReadDescriptor.PROPERTY_NAME_IMAGE_READER);
+- ImageReadCRIF.copyProperty(firstImage,
+- imageList,
+- ImageReadDescriptor.PROPERTY_NAME_METADATA_STREAM);
+-
+- return imageList;
+- }
+-
+- /** Constructor. */
+- public ImageReadCIF() {}
+-
+- public CollectionImage create(ParameterBlock args,
+- RenderingHints hints) {
+- return createStatic(args, hints);
+- }
+-
+- // Forget it.
+- public CollectionImage update(ParameterBlock oldParamBlock,
+- RenderingHints oldHints,
+- ParameterBlock newParamBlock,
+- RenderingHints newHints,
+- CollectionImage oldRendering,
+- CollectionOp op) {
+- return null;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadCRIF.java zzx2/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadCRIF.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadCRIF.java 2005-11-30 19:39:04.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadCRIF.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,434 +0,0 @@
+-/*
+- * $RCSfile: ImageReadCRIF.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.2 $
+- * $Date: 2005/12/01 00:39:04 $
+- * $State: Exp $
+- */
+-package com.sun.media.jai.imageioimpl;
+-
+-import java.awt.Dimension;
+-import java.awt.RenderingHints;
+-import java.awt.geom.Rectangle2D;
+-import java.awt.image.RenderedImage;
+-import java.awt.image.renderable.ParameterBlock;
+-import java.awt.image.renderable.RenderableImage;
+-import java.awt.image.renderable.RenderContext;
+-import java.io.FileInputStream;
+-import java.io.InputStream;
+-import java.io.IOException;
+-import java.io.RandomAccessFile;
+-import java.net.Socket;
+-import java.net.URL;
+-import java.nio.channels.Channel;
+-import java.nio.channels.Channels;
+-import java.util.Collection;
+-import java.util.Comparator;
+-import java.util.EventListener;
+-import java.util.Iterator;
+-import java.util.Locale;
+-import java.util.TreeMap;
+-import java.util.Vector;
+-import javax.imageio.ImageIO;
+-import javax.imageio.ImageReader;
+-import javax.imageio.ImageReadParam;
+-import javax.imageio.event.IIOReadProgressListener;
+-import javax.imageio.event.IIOReadUpdateListener;
+-import javax.imageio.event.IIOReadWarningListener;
+-import javax.imageio.spi.ImageReaderSpi;
+-import javax.imageio.stream.ImageInputStream;
+-import javax.media.jai.CRIFImpl;
+-import javax.media.jai.ImageLayout;
+-import javax.media.jai.JAI;
+-import javax.media.jai.MultiResolutionRenderableImage;
+-import javax.media.jai.PropertySource;
+-import javax.media.jai.WritablePropertySource;
+-import com.sun.media.jai.operator.ImageReadDescriptor;
+-
+-public final class ImageReadCRIF extends CRIFImpl {
+- public ImageReadCRIF() {
+- super(); // Pass up the name?
+- }
+-
+- /**
+- * Attempt to create an {@link ImageInputStream} for the supplied
+- * input. The following sequence is effected:
+- *
+- *
+- *
+- * @param input An
+- *
input
is an ImageInputStream
it
+- * is cast and returned.input
is a String
it is converted
+- * to a read-only RandomAccessFile
.RandomAccessFile
fails, the
+- * String
input
is converted to an
+- * InputStream
by accessing it as a resource bundled
+- * in a JAR file.input
is a URL
it is converted
+- * to an InputStream
.input
is a Socket
it is converted
+- * to an InputStream
.ImageIO.createImageInputStream()
is invoked
+- * with parameter set to the (possibly converted) input and the
+- * value it returns (which could be null
) is returned
+- * to the caller.Object
to be used as the source,
+- * such as a String
, URL
, File
,
+- * readable RandomAccessFile
, InputStream
,
+- * readable Socket
, or readable Channel
.
+- *
+- * @return An ImageInputStream
or null
.
+- */
+- private static ImageInputStream getImageInputStream(Object input) {
+- // The value to be returned.
+- ImageInputStream stream = null;
+-
+- // If already an ImageInputStream cast and return.
+- if(input instanceof ImageInputStream) {
+- stream = (ImageInputStream)input;
+- } else {
+- // If the input is a String replace it with a RandomAccessFile.
+- if(input instanceof String) {
+- try {
+- // 'input' is conditionally checked for readability
+- // in the OperationDescriptor.
+- input = new RandomAccessFile((String)input, "r");
+- } catch(Exception e) {
+- // Try to get the file as an InputStream resource. This
+- // would happen when the application and image file are
+- // packaged in a JAR file
+- input = ImageReadCRIF.class.getClassLoader().getResourceAsStream((String)input);
+- if (input == null)
+- throw new RuntimeException
+- (I18N.getString("ImageReadCRIF0")+" "+input);
+- }
+- } else if(input instanceof URL) {
+- // If the input is a URL replace it with an InputStream.
+- try {
+- input = ((URL)input).openStream();
+- } catch(Exception e) {
+- throw new RuntimeException
+- (I18N.getString("ImageReadCRIF1")+" "+input);
+- }
+- } else if(input instanceof Socket) {
+- // If output is a Socket replace it with an InputStream.
+- try {
+- Socket socket = (Socket)input;
+- // XXX check binding, connection, closed, shutdown
+- // as these could have changed.
+- input = socket.getInputStream();
+- } catch(Exception e) {
+- throw new RuntimeException
+- (I18N.getString("ImageReadCRIF2")+" "+input);
+- }
+- }
+- }
+-
+- // Create the ImageInputStream.
+- try {
+- stream = ImageIO.createImageInputStream(input);
+- } catch(Exception e) {
+- throw new RuntimeException(e);
+- }
+-
+- return stream;
+- }
+-
+- /**
+- * Get the ImageReader
and set its input and metadata flag.
+- * The input set on the reader might not be the same object as the input
+- * passed in if the latter was replaced by getImageInputStream().
+- */
+- static ImageReader getImageReader(ParameterBlock pb) {
+- // Get the input.
+- Object input = pb.getObjectParameter(0);
+-
+- // Get the reader parameter.
+- ImageReader reader = (ImageReader)pb.getObjectParameter(8);
+-
+- // Attempt to create an ImageInputStream from the input.
+- ImageInputStream stream = getImageInputStream(input);
+-
+- // If no reader passed in, try to find one.
+- if(reader == null) {
+- // Get all compatible readers.
+- Iterator readers = ImageIO.getImageReaders(stream != null ?
+- stream : input);
+-
+- // If any readers, take the first one whose originating
+- // service provider indicates that it can decode the input.
+- if(readers != null && readers.hasNext()) {
+- do {
+- ImageReader tmpReader = (ImageReader)readers.next();
+- ImageReaderSpi readerSpi =
+- tmpReader.getOriginatingProvider();
+- try {
+- if(readerSpi.canDecodeInput(stream != null ?
+- stream : input)) {
+- reader = tmpReader;
+- }
+- } catch(IOException ioe) {
+- // XXX Ignore it?
+- }
+- } while(reader == null && readers.hasNext());
+- }
+- }
+-
+- // If reader found, set its input and metadata flag.
+- if(reader != null) {
+- // Get the locale parameter and set on the reader.
+- Locale locale = (Locale)pb.getObjectParameter(6);
+- if(locale != null) {
+- reader.setLocale(locale);
+- }
+-
+- // Get the listeners parameter and set on the reader.
+- EventListener[] listeners =
+- (EventListener[])pb.getObjectParameter(5);
+- if(listeners != null) {
+- for(int i = 0; i < listeners.length; i++) {
+- EventListener listener = listeners[i];
+- if(listener instanceof IIOReadProgressListener) {
+- reader.addIIOReadProgressListener(
+- (IIOReadProgressListener)listener);
+- }
+- if(listener instanceof IIOReadUpdateListener) {
+- reader.addIIOReadUpdateListener(
+- (IIOReadUpdateListener)listener);
+- }
+- if(listener instanceof IIOReadWarningListener) {
+- reader.addIIOReadWarningListener(
+- (IIOReadWarningListener)listener);
+- }
+- }
+- }
+-
+- // Get the metadata reading flag.
+- boolean readMetadata =
+- ((Boolean)pb.getObjectParameter(2)).booleanValue();
+-
+- // Set the input and indicate metadata reading state.
+- reader.setInput(stream != null ? stream : input,
+- false, // seekForwardOnly
+- !readMetadata); // ignoreMetadata
+- }
+-
+- return reader;
+- }
+-
+- static void copyProperty(PropertySource ps,
+- WritablePropertySource wps,
+- String propertyName) {
+- Object propertyValue = ps.getProperty(propertyName);
+-
+- if(propertyValue != null &&
+- !propertyValue.equals(java.awt.Image.UndefinedProperty)) {
+- wps.setProperty(propertyName, propertyValue);
+-
+- }
+- }
+-
+- public RenderedImage create(ParameterBlock pb,
+- RenderingHints rh) {
+-
+- // Value to be returned.
+- RenderedImage image = null;
+-
+- // Get the reader.
+- ImageReader reader = getImageReader(pb);
+-
+- // Proceed if a compatible reader was found.
+- if(reader != null) {
+- // Get the remaining parameters required.
+- int imageIndex = pb.getIntParameter(1);
+- ImageReadParam param =
+- (ImageReadParam)pb.getObjectParameter(7);
+- boolean readThumbnails =
+- ((Boolean)pb.getObjectParameter(3)).booleanValue();
+-
+- // Initialize the layout.
+- ImageLayout layout =
+- (rh != null && rh.containsKey(JAI.KEY_IMAGE_LAYOUT)) ?
+- (ImageLayout)rh.get(JAI.KEY_IMAGE_LAYOUT) :
+- new ImageLayout();
+-
+- try {
+- // Get the parameter input.
+- Object paramInput = pb.getObjectParameter(0);
+-
+- // Get the reader input.
+- Object readerInput = reader.getInput();
+-
+- // Set the stream to close when the OpImage is disposed.
+- ImageInputStream streamToClose = null;
+- if(readerInput != paramInput &&
+- readerInput instanceof ImageInputStream) {
+- streamToClose = (ImageInputStream)readerInput;
+- }
+-
+- // Create the rendering.
+- image = new ImageReadOpImage(layout,
+- rh,
+- param,
+- reader,
+- imageIndex,
+- readThumbnails,
+- streamToClose);
+- } catch(Exception e) {
+- throw new RuntimeException(e);
+- }
+- }
+-
+- return image;
+- }
+-
+- // XXX This implementation of renderable mode is incredibly lame
+- // but the architecture and implementation allow for nothing else.
+- // It would be better if the CRIFs had some kind of state that
+- // could be associated with them. As it standards getBounds2D()
+- // will create a new MultiResolutionRenderableImage and so will
+- // the second create() below. Actually what is needed is a
+- // RenderableImageFactory definition.
+- // XXX There is also a problem with multiple invocations of the
+- // rendered mode case. Without saving and seeking back to the
+- // same offset it appears to have problems. Should ImageReadOpImage
+- // save the initial position and always seek back to it?
+-
+- public RenderableImage createRenderable(ParameterBlock pb,
+- RenderingHints rh) {
+-
+- // Read the collection.
+- Collection sequence = ImageReadCIF.createStatic(pb, rh);
+-
+- // Create a SortedMap which sorts on the basis of inverse area.
+- // The keys will be Dimensions and the objects RenderedImages.
+- TreeMap sourceMap = new TreeMap(new Comparator() {
+- public int compare(Object o1, Object o2) {
+- Dimension d1 = (Dimension)o1;
+- Dimension d2 = (Dimension)o2;
+-
+- int area1 = d1.width*d1.height;
+- int area2 = d2.width*d2.height;
+-
+- double inverse1 = area1 == 0 ?
+- Double.MAX_VALUE : 1.0/area1;
+- double inverse2 = area2 == 0 ?
+- Double.MAX_VALUE : 1.0/area2;
+-
+- if(inverse1 < inverse2) {
+- return -1;
+- } else if(inverse1 > inverse2) {
+- return 1;
+- } else {
+- return 0;
+- }
+- }
+-
+- public boolean equals(Object o1, Object o2) {
+- return o1.equals(o2);
+- }
+- });
+-
+- Iterator images = sequence.iterator();
+- while(images.hasNext()) {
+- RenderedImage image = (RenderedImage)images.next();
+- sourceMap.put(new Dimension(image.getWidth(), image.getHeight()),
+- image);
+- }
+-
+- // Create the rendered source list sorted by inverse area.
+- Vector renderedSources = new Vector(sourceMap.size());
+- Iterator keys = sourceMap.keySet().iterator();
+- while(keys.hasNext()) {
+- renderedSources.add(sourceMap.get(keys.next()));
+- }
+-
+- // Create the RenderableImage from the sorted RenderedImages.
+- MultiResolutionRenderableImage renderableImage =
+- new MultiResolutionRenderableImage(renderedSources,
+- 0.0F, 0.0F, 1.0F);
+-
+- // Set properties from those of the first rendered source.
+- PropertySource firstSource = (PropertySource)renderedSources.get(0);
+- copyProperty(firstSource,
+- renderableImage,
+- ImageReadDescriptor.PROPERTY_NAME_IMAGE_READ_PARAM);
+- copyProperty(firstSource,
+- renderableImage,
+- ImageReadDescriptor.PROPERTY_NAME_IMAGE_READER);
+- copyProperty(firstSource,
+- renderableImage,
+- ImageReadDescriptor.PROPERTY_NAME_METADATA_STREAM);
+- copyProperty(firstSource,
+- renderableImage,
+- ImageReadDescriptor.PROPERTY_NAME_METADATA_IMAGE);
+-
+- // Return the RenderableImage.
+- return renderableImage;
+- }
+-
+- public RenderedImage create(RenderContext rc,
+- ParameterBlock pb) {
+-
+- RenderableImage renderableImage =
+- createRenderable(pb, rc.getRenderingHints());
+-
+- RenderedImage renderedImage = renderableImage.createRendering(rc);
+-
+- ((WritablePropertySource)renderedImage).setProperty(
+- ImageReadDescriptor.PROPERTY_NAME_RENDERABLE_INPUT,
+- (PropertySource)renderableImage);
+-
+- return renderedImage;
+- }
+-
+- public Rectangle2D getBounds2D(ParameterBlock pb) {
+- // XXX Should just get the aspect ratio of the first image and use it.
+- // Otherwise this will be very inefficient.
+- RenderableImage renderable = createRenderable(pb, null);
+-
+- return new Rectangle2D.Float(renderable.getMinX(),
+- renderable.getMinY(),
+- renderable.getWidth(),
+- renderable.getHeight());
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadOpImage.java zzx2/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadOpImage.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadOpImage.java 2006-07-14 17:43:57.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadOpImage.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,914 +0,0 @@
+-/*
+- * $RCSfile: ImageReadOpImage.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.2 $
+- * $Date: 2006/07/14 21:43:57 $
+- * $State: Exp $
+- */
+-package com.sun.media.jai.imageioimpl;
+-
+-import java.awt.Dimension;
+-import java.awt.Point;
+-import java.awt.Rectangle;
+-import java.awt.image.BufferedImage;
+-import java.awt.image.ColorModel;
+-import java.awt.image.Raster;
+-import java.awt.image.SampleModel;
+-import java.awt.image.WritableRaster;
+-import java.io.InputStream;
+-import java.io.IOException;
+-import java.util.Iterator;
+-import java.util.Map;
+-import javax.imageio.ImageReader;
+-import javax.imageio.ImageReadParam;
+-import javax.imageio.ImageTypeSpecifier;
+-import javax.imageio.metadata.IIOMetadata;
+-import javax.imageio.spi.ImageReaderSpi;
+-import javax.imageio.stream.ImageInputStream;
+-import javax.media.jai.ImageLayout;
+-import javax.media.jai.OpImage;
+-import com.sun.media.jai.operator.ImageReadDescriptor;
+-
+-/**
+- * Implementation of the OpImage
of the "ImageRead" operation.
+- */
+-final class ImageReadOpImage extends OpImage {
+-
+- /**
+- * XXX For testing only.
+- */
+- /* XXX
+- public static void main(String[] args) throws Throwable {
+- java.io.File file = new java.io.File(args[0]);
+- int imageIndex = args.length > 1 ?
+- Integer.valueOf(args[1]).intValue() : 0;
+- int tileSize = args.length > 2 ?
+- Integer.valueOf(args[2]).intValue() : 128;
+-
+- javax.imageio.stream.ImageInputStream stream =
+- new javax.imageio.stream.FileImageInputStream(file);
+-
+- Iterator iter = javax.imageio.ImageIO.getImageReaders(stream);
+- ImageReader imageReader = (ImageReader)iter.next();
+- imageReader.setInput(stream,
+- true, // seekForwardOnly
+- false); // ignoreMetadata
+-
+- ImageLayout layout = new ImageLayout();
+- layout.setTileWidth(tileSize).setTileHeight(tileSize);
+- //layout.setTileGridXOffset(42).setTileGridYOffset(7);
+-
+- ImageReadParam param = imageReader.getDefaultReadParam();
+- param.setSourceSubsampling(2, 2, 0, 0);
+- param.setSourceRegion(new Rectangle(128, 0, 256, 256));
+- param.setSourceBands(new int[] {2, 1, 0});
+- param.setDestinationBands(new int[] {0, 1, 2});
+-
+- OpImage image = new ImageReadOpImage(layout, // ImageLayout
+- null, // Map
+- param, // ImageReadParam
+- imageReader,
+- imageIndex,
+- true,
+- null); // streamToClose
+-
+- System.out.println(new ImageLayout(image));
+-
+- System.out.println("\nImage Properties:");
+- String[] propNames = image.getPropertyNames();
+- if(propNames != null) {
+- for(int i = 0; i < propNames.length; i++) {
+- System.out.println(i+" "+propNames[i]+" = "+
+- image.getProperty(propNames[i]));
+- }
+- }
+- System.out.println("");
+-
+- BufferedImage[] thumbnails = null;
+- Object thumbnailProp =
+- image.getProperty(ImageReadDescriptor.PROPERTY_NAME_THUMBNAILS);
+- if(thumbnailProp != java.awt.Image.UndefinedProperty) {
+- thumbnails = (BufferedImage[])thumbnailProp;
+- }
+-
+- java.awt.Frame frame =
+- new java.awt.Frame("ImageReadOpImage Test: "+file);
+- if(thumbnails != null) {
+- frame.setLayout(new java.awt.GridLayout(1, thumbnails.length+1));
+- }
+-
+- frame.add(new javax.media.jai.widget.ScrollingImagePanel(image,
+- image.getWidth(),
+- image.getHeight()));
+- if(thumbnails != null) {
+- for(int i= 0; i < thumbnails.length; i++) {
+- frame.add(new javax.media.jai.widget.ScrollingImagePanel(thumbnails[i],
+- thumbnails[i].getWidth(),
+- thumbnails[i].getHeight()));
+- }
+- }
+- frame.pack();
+- frame.show();
+- }
+- */
+-
+- /**
+- * The ImageReadParam
used in reading the image.
+- */
+- private ImageReadParam param;
+-
+- /**
+- * The ImageReader
used to read the image.
+- */
+- private ImageReader reader;
+-
+- /**
+- * The index of the image to be read.
+- */
+- private int imageIndex;
+-
+- /**
+- * Whether thumbnails are to be read.
+- */
+- private boolean readThumbnails;
+-
+- /**
+- * Whether stream metadata have been be read.
+- */
+- private boolean streamMetadataRead = false;
+-
+- /**
+- * Whether image metadata have been be read.
+- */
+- private boolean imageMetadataRead = false;
+-
+- /**
+- * A stream to be closed when the instance is disposed; may be null.
+- */
+- private ImageInputStream streamToClose;
+-
+- /**
+- * Destination to source X scale factor.
+- */
+- private int scaleX;
+-
+- /**
+- * Destination to source Y scale factor.
+- */
+- private int scaleY;
+-
+- /**
+- * Destination to source X translation factor.
+- */
+- private int transX;
+-
+- /**
+- * Destination to source Y translation factor.
+- */
+- private int transY;
+-
+- /**
+- * Derive the image layout based on the user-supplied layout,
+- * reading parameters, and image index.
+- */
+- private static ImageLayout layoutHelper(ImageLayout il,
+- ImageReadParam param,
+- ImageReader reader,
+- int imageIndex)
+- throws IOException {
+- ImageLayout layout = (il == null) ?
+- new ImageLayout() : (ImageLayout)il.clone();
+-
+- // --- Determine the image type. ---
+-
+- // If not provided in the original layout, set the SampleModel
+- // and ColorModel from the ImageReadParam, if supplied.
+- if(!layout.isValid(ImageLayout.SAMPLE_MODEL_MASK) &&
+- !layout.isValid(ImageLayout.COLOR_MODEL_MASK)) {
+- // If an ImageReadParam has been supplied and has its
+- // destinationType set then use it. Otherwise default to
+- // the raw image type.
+- ImageTypeSpecifier imageType =
+- (param != null && param.getDestinationType() != null) ?
+- param.getDestinationType() :
+- reader.getRawImageType(imageIndex);
+-
+- // XXX The following block of code should not be necessary
+- // but for J2SE 1.4.0 FCS ImageReader.getRawImageType(0)
+- // returns null for earth.jpg, Bas-noir.jpg, etc.
+- if(imageType == null) {
+- Iterator imageTypes = reader.getImageTypes(imageIndex);
+- while(imageType == null && imageTypes.hasNext()) {
+- imageType = (ImageTypeSpecifier)imageTypes.next();
+- }
+- }
+-
+- // XXX Should an exception be thrown if imageType is null?
+- if(imageType != null) {
+- // Set the SampleModel and ColorModel.
+- layout.setSampleModel(imageType.getSampleModel());
+- layout.setColorModel(imageType.getColorModel());
+- }
+- }
+-
+- // --- Set up the destination bounds. ---
+-
+- // Calculate the computable destination bounds.
+- Dimension sourceSize = getSourceSize(param, reader, imageIndex);
+- Rectangle srcRegion = new Rectangle();
+- Rectangle destRegion = new Rectangle();
+- computeRegions(param,
+- sourceSize.width,
+- sourceSize.height,
+- layout.getMinX(null), // valid value or 0
+- layout.getMinY(null), // valid value or 0
+- false,
+- srcRegion,
+- destRegion);
+-
+- if(!destRegion.isEmpty()) {
+- // Backup layout image bounds with computable bounds.
+- if(!layout.isValid(ImageLayout.WIDTH_MASK)) {
+- layout.setWidth(destRegion.width);
+- }
+- if(!layout.isValid(ImageLayout.HEIGHT_MASK)) {
+- layout.setHeight(destRegion.height);
+- }
+- if(!layout.isValid(ImageLayout.MIN_X_MASK)) {
+- layout.setMinX(destRegion.x);
+- }
+- if(!layout.isValid(ImageLayout.MIN_Y_MASK)) {
+- layout.setMinY(destRegion.y);
+- }
+-
+- // Ensure the layout bounds intersect computable bounds.
+- Rectangle destBounds = new Rectangle(layout.getMinX(null),
+- layout.getMinY(null),
+- layout.getWidth(null),
+- layout.getHeight(null));
+- if(destRegion.intersection(destBounds).isEmpty()) {
+- throw new IllegalArgumentException
+- (I18N.getString("ImageReadOpImage0"));
+- }
+- }
+-
+- // --- Set up the tile grid. ---
+-
+- if(!layout.isValid(ImageLayout.TILE_GRID_X_OFFSET_MASK)) {
+- layout.setTileGridXOffset(reader.getTileGridXOffset(imageIndex));
+- }
+- if(!layout.isValid(ImageLayout.TILE_GRID_Y_OFFSET_MASK)) {
+- layout.setTileGridYOffset(reader.getTileGridYOffset(imageIndex));
+- }
+- if(!layout.isValid(ImageLayout.TILE_WIDTH_MASK)) {
+- layout.setTileWidth(reader.getTileWidth(imageIndex));
+- }
+- if(!layout.isValid(ImageLayout.TILE_HEIGHT_MASK)) {
+- layout.setTileHeight(reader.getTileHeight(imageIndex));
+- }
+-
+- return layout;
+- }
+-
+- /**
+- * Returns whether an ImageTypeSpecifier
may be used
+- * to read in the image at a specified index.
+- *
+- * XXX
+- */
+- private static boolean isCompatibleType(ImageTypeSpecifier imageType,
+- ImageReader reader,
+- int imageIndex)
+- throws IOException {
+- Iterator imageTypes = reader.getImageTypes(imageIndex);
+-
+- boolean foundIt = false;
+- while (imageTypes.hasNext()) {
+- ImageTypeSpecifier type =
+- (ImageTypeSpecifier)imageTypes.next();
+- if (type.equals(imageType)) {
+- foundIt = true;
+- break;
+- }
+- }
+-
+- return foundIt;
+- }
+-
+- /**
+- * Returns the source region to be read. If the sourceRenderSize
+- * is being used it is returned; otherwise the raw source dimensions
+- * are returned.
+- *
+- * XXX
+- */
+- private static Dimension getSourceSize(ImageReadParam param,
+- ImageReader reader,
+- int imageIndex)
+- throws IOException {
+- Dimension sourceSize = null;
+- if(param != null && param.canSetSourceRenderSize()) {
+- sourceSize = param.getSourceRenderSize();
+- }
+- if(sourceSize == null) {
+- sourceSize = new Dimension(reader.getWidth(imageIndex),
+- reader.getHeight(imageIndex));
+- }
+- return sourceSize;
+- }
+-
+- /**
+- * XXX
+- */
+- // Code copied from ImageReader.java
+- private static Rectangle getSourceRegion(ImageReadParam param,
+- int srcWidth,
+- int srcHeight) {
+- Rectangle sourceRegion = new Rectangle(0, 0, srcWidth, srcHeight);
+- if (param != null) {
+- Rectangle region = param.getSourceRegion();
+- if (region != null) {
+- sourceRegion = sourceRegion.intersection(region);
+- }
+-
+- int subsampleXOffset = param.getSubsamplingXOffset();
+- int subsampleYOffset = param.getSubsamplingYOffset();
+- sourceRegion.x += subsampleXOffset;
+- sourceRegion.y += subsampleYOffset;
+- sourceRegion.width -= subsampleXOffset;
+- sourceRegion.height -= subsampleYOffset;
+- }
+-
+- return sourceRegion;
+- }
+-
+- /**
+- * XXX
+- */
+- // clipDestRegion: whether to clip destRegion to positive coordinates.
+- // Code based on method of same name in ImageReader.java
+- private static void computeRegions(ImageReadParam param,
+- int srcWidth,
+- int srcHeight,
+- int destMinX,
+- int destMinY,
+- boolean clipDestRegion,
+- Rectangle srcRegion,
+- Rectangle destRegion) {
+- if (srcRegion == null) {
+- throw new IllegalArgumentException("srcRegion == null");
+- }
+- if (destRegion == null) {
+- throw new IllegalArgumentException("destRegion == null");
+- }
+-
+- // Start with the entire source image
+- srcRegion.setBounds(0, 0, srcWidth, srcHeight);
+-
+- // Destination also starts with source image, as that is the
+- // maximum extent if there is no subsampling
+- destRegion.setBounds(destMinX, destMinY, srcWidth, srcHeight);
+-
+- // Clip that to the param region, if there is one
+- int periodX = 1;
+- int periodY = 1;
+- int gridX = 0;
+- int gridY = 0;
+- if (param != null) {
+- Rectangle paramSrcRegion = param.getSourceRegion();
+- if (paramSrcRegion != null) {
+- srcRegion.setBounds(srcRegion.intersection(paramSrcRegion));
+- }
+- periodX = param.getSourceXSubsampling();
+- periodY = param.getSourceYSubsampling();
+- gridX = param.getSubsamplingXOffset();
+- gridY = param.getSubsamplingYOffset();
+- srcRegion.translate(gridX, gridY);
+- srcRegion.width -= gridX;
+- srcRegion.height -= gridY;
+- Point destinationOffset = param.getDestinationOffset();
+- destRegion.translate(destinationOffset.x, destinationOffset.y);
+- }
+-
+- if(clipDestRegion) {
+- // Now clip any negative destination offsets, i.e. clip
+- // to the top and left of the destination image
+- if (destRegion.x < 0) {
+- int delta = -destRegion.x*periodX;
+- srcRegion.x += delta;
+- srcRegion.width -= delta;
+- destRegion.x = 0;
+- }
+- if (destRegion.y < 0) {
+- int delta = -destRegion.y*periodY;
+- srcRegion.y += delta;
+- srcRegion.height -= delta;
+- destRegion.y = 0;
+- }
+- }
+-
+- // Now clip the destination Region to the subsampled width and height
+- int subsampledWidth = (srcRegion.width + periodX - 1)/periodX;
+- int subsampledHeight = (srcRegion.height + periodY - 1)/periodY;
+- destRegion.width = subsampledWidth;
+- destRegion.height = subsampledHeight;
+-
+- if (srcRegion.isEmpty() || destRegion.isEmpty()) {
+- throw new IllegalArgumentException
+- (I18N.getString("ImageReadOpImage1"));
+- }
+- }
+-
+- /**
+- * XXX
+- * NB: This class may reset the following fields of the ImageReadParam
+- * destinationOffset
+- * destinationType
+- * sourceRegion
+- */
+- ImageReadOpImage(ImageLayout layout,
+- Map configuration,
+- ImageReadParam param,
+- ImageReader reader,
+- int imageIndex,
+- boolean readThumbnails,
+- ImageInputStream streamToClose) throws IOException {
+- super(null,
+- layoutHelper(layout, param, reader, imageIndex),
+- configuration,
+- false);
+-
+- // Revise parameter 'param' as needed.
+- if(param == null) {
+- // Get the ImageReadParam from the ImageReader.
+- param = reader.getDefaultReadParam();
+- } else if(param instanceof Cloneable) {
+- this.param = param;
+- } else if(param.getClass().getName().equals(
+- "javax.imageio.ImageReadParam")) {
+- // The ImageReadParam passed in is non-null. As the
+- // ImageReadParam class is not Cloneable, if the param
+- // class is simply ImageReadParam, then create a new
+- // ImageReadParam instance and set all its fields
+- // which were set in param. This will eliminate problems
+- // with concurrent modification of param for the cases
+- // in which there is not a special ImageReadparam used.
+-
+- // Create a new ImageReadParam instance.
+- ImageReadParam newParam = new ImageReadParam();
+-
+- // Set all fields which need to be set.
+-
+- // IIOParamController field.
+- if(param.hasController()) {
+- newParam.setController(param.getController());
+- }
+-
+- // Destination fields.
+- newParam.setDestination(param.getDestination());
+- if(param.getDestinationType() != null) {
+- // Set the destination type only if non-null as the
+- // setDestinationType() clears the destination field.
+- newParam.setDestinationType(param.getDestinationType());
+- }
+- newParam.setDestinationBands(param.getDestinationBands());
+- newParam.setDestinationOffset(param.getDestinationOffset());
+-
+- // Source fields.
+- newParam.setSourceBands(param.getSourceBands());
+- newParam.setSourceRegion(param.getSourceRegion());
+- if(param.getSourceMaxProgressivePass() != Integer.MAX_VALUE) {
+- newParam.setSourceProgressivePasses(
+- param.getSourceMinProgressivePass(),
+- param.getSourceNumProgressivePasses());
+- }
+- if(param.canSetSourceRenderSize()) {
+- newParam.setSourceRenderSize(param.getSourceRenderSize());
+- }
+- newParam.setSourceSubsampling(param.getSourceXSubsampling(),
+- param.getSourceYSubsampling(),
+- param.getSubsamplingXOffset(),
+- param.getSubsamplingYOffset());
+-
+- // Replace the local variable with the new ImageReadParam.
+- param = newParam;
+- }
+-
+- // Revise parameter 'readThumbnails' as needed.
+- if(readThumbnails && !reader.hasThumbnails(imageIndex)) {
+- // Unset thumbnail flag if not supported by ImageReader.
+- readThumbnails = false;
+- }
+-
+- // Set instance variables from (possibly revised) parameters.
+- this.param = param;
+- this.reader = reader;
+- this.imageIndex = imageIndex;
+- this.readThumbnails = readThumbnails;
+- this.streamToClose = streamToClose;
+-
+- // If an ImageTypeSpecifier is specified in the ImageReadParam
+- // but it is incompatible with the ImageReader, then attempt to
+- // replace it with a compatible one derived from this image.
+- if(param.getDestinationType() != null &&
+- !isCompatibleType(param.getDestinationType(), reader, imageIndex) &&
+- sampleModel != null && colorModel != null) {
+- ImageTypeSpecifier newImageType =
+- new ImageTypeSpecifier(colorModel, sampleModel);
+- if(isCompatibleType(newImageType, reader, imageIndex)) {
+- param.setDestinationType(newImageType);
+- }
+- }
+-
+- // --- Compute the destination to source mapping coefficients. ---
+-
+- Dimension sourceSize = getSourceSize(param, reader, imageIndex);
+-
+- Rectangle srcRegion = getSourceRegion(param,
+- sourceSize.width,
+- sourceSize.height);
+-
+- Point destinationOffset = this.param.getDestinationOffset();
+-
+- this.scaleX = this.param.getSourceXSubsampling();
+- this.scaleY = this.param.getSourceYSubsampling();
+- this.transX =
+- srcRegion.x + this.param.getSubsamplingXOffset() -
+- this.param.getSourceXSubsampling()*(minX + destinationOffset.x);
+- this.transY =
+- srcRegion.y + this.param.getSubsamplingYOffset() -
+- this.param.getSourceYSubsampling()*(minY + destinationOffset.y);
+-
+- // Replace the original destination offset with (0,0) as the
+- // destination-to-source mapping assimilates this value.
+- this.param.setDestinationOffset(new Point());
+- // XXX Need to unset other ImageReadParam settings either here
+- // or in computeTile(). Examine this issue taking into account
+- // synchronization.
+-
+- // Set the ImageReadParam property.
+- setProperty(ImageReadDescriptor.PROPERTY_NAME_IMAGE_READ_PARAM, param);
+-
+- // Set the ImageReader property.
+- setProperty(ImageReadDescriptor.PROPERTY_NAME_IMAGE_READER, reader);
+-
+- // If metadata are being read, set the value of the metadata
+- // properties to UndefinedProperty so that the property
+- // names will appear in the array of property names. The actual
+- // values will be retrieved when getProperty() is invoked.
+- if(!reader.isIgnoringMetadata()) {
+- // Get the service provider interface, if any.
+- ImageReaderSpi provider = reader.getOriginatingProvider();
+-
+- // Stream metadata.
+- if(provider == null ||
+- provider.isStandardStreamMetadataFormatSupported() ||
+- provider.getNativeStreamMetadataFormatName() != null) {
+- // Assume an ImageReader with a null provider supports
+- // stream metadata.
+- setProperty(ImageReadDescriptor.PROPERTY_NAME_METADATA_STREAM,
+- java.awt.Image.UndefinedProperty);
+- } else {
+- // Provider supports neither standard nor native stream
+- // metadata so set flag to suppress later reading attempt.
+- streamMetadataRead = true;
+- }
+-
+- // Image metadata.
+- if(provider == null ||
+- provider.isStandardImageMetadataFormatSupported() ||
+- provider.getNativeImageMetadataFormatName() != null) {
+- // Assume an ImageReader with a null provider supports
+- // image metadata.
+- setProperty(ImageReadDescriptor.PROPERTY_NAME_METADATA_IMAGE,
+- java.awt.Image.UndefinedProperty);
+- } else {
+- // Provider supports neither standard nor native image
+- // metadata so set flag to suppress later reading attempt.
+- imageMetadataRead = true;
+- }
+- }
+-
+- // If thumbnail read flag is set, set the value of the thumbnail
+- // property to UndefinedProperty so that the thumbnail property
+- // name will appear in the array of property names. The actual
+- // value will be retrieved when getProperty() is invoked.
+- if(readThumbnails && reader.readerSupportsThumbnails()) {
+- setProperty(ImageReadDescriptor.PROPERTY_NAME_THUMBNAILS,
+- java.awt.Image.UndefinedProperty);
+- }
+- }
+-
+- /**
+- * Returns false as ImageReaders might return Rasters
+- * via computeTile() tile that are internally cached.
+- */
+- public boolean computesUniqueTiles() {
+- return false;
+- }
+-
+- /**
+- * XXX
+- */
+- private Rectangle computeSourceRect(Rectangle destRect) {
+- Rectangle sourceRect = new Rectangle();
+-
+- sourceRect.x = scaleX*destRect.x + transX;
+- sourceRect.y = scaleY*destRect.y + transY;
+-
+- sourceRect.width =
+- scaleX*(destRect.x + destRect.width) + transX - sourceRect.x;
+- sourceRect.height =
+- scaleY*(destRect.y + destRect.height) + transY - sourceRect.y;
+-
+- return sourceRect;
+- }
+-
+- /**
+- * Computes a tile.
+- *
+- * @param tileX The X index of the tile.
+- * @param tileY The Y index of the tile.
+- */
+- public Raster computeTile(int tileX, int tileY) {
+- //XXX System.out.println("Tile ("+tileX+","+tileY+")");
+- // Create a new WritableRaster to represent this tile.
+- Point org = new Point(tileXToX(tileX), tileYToY(tileY));
+- //WritableRaster dest = Raster.createWritableRaster(sampleModel, org);
+- Rectangle rect = new Rectangle(org.x, org.y, tileWidth, tileHeight);
+-
+- // Clip output rectangle to image bounds.
+- // Not sure what will happen here with the bounds intersection.
+- Rectangle destRect = rect.intersection(getBounds());
+- // XXX Check for destRect.isEmpty()?
+-
+- /* XXX delete
+- java.awt.geom.AffineTransform transform =
+- new java.awt.geom.AffineTransform(scaleX, 0, 0, scaleY,
+- transX, transY);
+- */
+- Rectangle srcRect =
+- computeSourceRect(destRect);
+- /* XXX delete
+- transform.createTransformedShape(destRect).getBounds();
+- */
+-
+- WritableRaster readerTile = null;
+- try {
+- synchronized(reader) {
+- param.setSourceRegion(srcRect);
+- BufferedImage bi = reader.read(imageIndex, param);
+- WritableRaster ras = bi.getRaster();
+- readerTile = ras.createWritableChild(0, 0,
+- ras.getWidth(),
+- ras.getHeight(),
+- org.x, org.y,
+- null);
+- }
+- } catch(IOException e) {
+- throw new RuntimeException(e);
+- }
+-
+- WritableRaster tile = null;
+- if(sampleModel == readerTile.getSampleModel()) {
+- tile = readerTile;
+- } else {
+- // XXX As this method is synchronized, could a single
+- // destination be supplied to the reader instead of
+- // creating a new one?
+- tile = Raster.createWritableRaster(sampleModel, org);
+- tile.setRect(readerTile);
+- }
+-
+- return tile;
+- }
+-
+- /**
+- * Throws an IllegalArgumentException since the image has no image
+- * sources.
+- *
+- * @param sourceRect ignored.
+- * @param sourceIndex ignored.
+- *
+- * @throws IllegalArgumentException since the image has no sources.
+- */
+- public Rectangle mapSourceRect(Rectangle sourceRect,
+- int sourceIndex) {
+- throw new IllegalArgumentException
+- (I18N.getString("ImageReadOpImage2"));
+- }
+-
+- /**
+- * Throws an IllegalArgumentException since the image has no image
+- * sources.
+- *
+- * @param destRect ignored.
+- * @param sourceIndex ignored.
+- *
+- * @throws IllegalArgumentException since the image has no sources.
+- */
+- public Rectangle mapDestRect(Rectangle destRect,
+- int sourceIndex) {
+- throw new IllegalArgumentException
+- (I18N.getString("ImageReadOpImage2"));
+- }
+-
+- /**
+- * Gets a property from the property set of this image. If the
+- * property name is not recognized,
+- * java.awt.Image.UndefinedProperty
will be returned.
+- *
+- * String
.
+- *
+- * @return A reference to the property Object
, or the value
+- * java.awt.Image.UndefinedProperty
.
+- *
+- * @exception IllegalArgumentException if propertyName
+- * is null
.
+- */
+- public Object getProperty(String name) {
+- // Attempt to get property from superclass method.
+- Object property = super.getProperty(name);
+-
+- // If thumbnail property name with undefined value and thumbnails
+- // are being read and an attempt to read them has not already been
+- // made, then read the thumbnails and set the property.
+- if((property == null ||
+- property == java.awt.Image.UndefinedProperty)) {
+-
+- // Thumbnails
+- if(readThumbnails &&
+- name.equalsIgnoreCase(
+- ImageReadDescriptor.PROPERTY_NAME_THUMBNAILS)) {
+-
+- // Lock the class to avoid a race condition here
+- // and with computeTile().
+- synchronized(reader) {
+- // First re-check the flag in case another thread
+- // got here first.
+- if(readThumbnails) {
+- try {
+- // Get number of thumbnails.
+- int numThumbnails =
+- reader.getNumThumbnails(imageIndex);
+-
+- if(numThumbnails > 0) {
+- // Read all thumbnails.
+- BufferedImage[] thumbnails =
+- new BufferedImage[numThumbnails];
+- for(int i = 0; i < numThumbnails; i++) {
+- thumbnails[i] =
+- reader.readThumbnail(imageIndex, i);
+- }
+-
+- // Set thumbnail property.
+- setProperty(
+- ImageReadDescriptor.PROPERTY_NAME_THUMBNAILS,
+- thumbnails);
+-
+- // Update return value.
+- property = thumbnails;
+- }
+- } catch(IOException e) {
+- throw new RuntimeException(e);
+- } finally {
+- // If return value is somehow null set it
+- // to UndefinedProperty.
+- if(property == null) {
+- property = java.awt.Image.UndefinedProperty;
+- }
+-
+- // Unset thumbnail flag to avert subsequent
+- // reading attempts in case this one failed.
+- readThumbnails = false;
+- }
+- }
+- }
+- } else if(!reader.isIgnoringMetadata() &&
+- ((!streamMetadataRead &&
+- name.equalsIgnoreCase(
+- ImageReadDescriptor.PROPERTY_NAME_METADATA_STREAM)) ||
+- (!imageMetadataRead &&
+- name.equalsIgnoreCase(
+- ImageReadDescriptor.PROPERTY_NAME_METADATA_IMAGE)))) {
+-
+- // Lock the class to avoid a race condition here
+- // and with computeTile().
+- synchronized(reader) {
+-
+- // Set flag to indicate stream or image metadata.
+- boolean isStreamMetadata =
+- name.equalsIgnoreCase(
+- ImageReadDescriptor.PROPERTY_NAME_METADATA_STREAM);
+-
+- // Recheck the appropriate flag.
+- if(!(isStreamMetadata ?
+- streamMetadataRead : imageMetadataRead)) {
+-
+- // Set property name.
+- String propertyName = isStreamMetadata ?
+- ImageReadDescriptor.PROPERTY_NAME_METADATA_STREAM :
+- ImageReadDescriptor.PROPERTY_NAME_METADATA_IMAGE;
+-
+- IIOMetadata metadata = null;
+- try {
+- // Read metadata.
+- metadata = isStreamMetadata ?
+- reader.getStreamMetadata() :
+- reader.getImageMetadata(imageIndex);
+-
+- // Set metadata property.
+- if(metadata != null) {
+- setProperty(propertyName, metadata);
+- }
+-
+- // Update return value.
+- property = metadata;
+- } catch(IOException e) {
+- throw new RuntimeException(e);
+- } finally {
+- // If return value is somehow null set it
+- // to UndefinedProperty.
+- if(property == null) {
+- property = java.awt.Image.UndefinedProperty;
+- }
+-
+- // Set appropriate flag to avert subsequent
+- // reading attempts in case this one failed.
+- if(isStreamMetadata) {
+- streamMetadataRead = true;
+- } else {
+- imageMetadataRead = true;
+- }
+- }
+- }
+- }
+- }
+- }
+-
+- return property;
+- }
+-
+- /**
+- * Closes an ImageInputStream
passed in, if any.
+- */
+- public void dispose() {
+- if(streamToClose != null) {
+- try {
+- streamToClose.close();
+- } catch(IOException e) {
+- // Ignore it.
+- }
+- }
+-
+- super.dispose();
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadWriteSpi.java zzx2/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadWriteSpi.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadWriteSpi.java 2005-02-11 00:01:55.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/jai/imageioimpl/ImageReadWriteSpi.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,142 +0,0 @@
+-/*
+- * $RCSfile: ImageReadWriteSpi.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:55 $
+- * $State: Exp $
+- */
+-package com.sun.media.jai.imageioimpl;
+-
+-import java.awt.image.renderable.ContextualRenderedImageFactory;
+-import javax.media.jai.CollectionImageFactory;
+-import javax.media.jai.OperationDescriptor;
+-import javax.media.jai.OperationRegistry;
+-import javax.media.jai.OperationRegistrySpi;
+-import com.sun.media.jai.operator.ImageReadDescriptor;
+-import com.sun.media.jai.operator.ImageWriteDescriptor;
+-import javax.media.jai.registry.CollectionRegistryMode;
+-import javax.media.jai.registry.RenderableRegistryMode;
+-import javax.media.jai.registry.RenderedRegistryMode;
+-
+-/**
+- * {@link OperationRegistrySpi} implementation to register the "ImageRead"
+- * and "ImageWrite" operations and their associated image factories.
+- */
+-public class ImageReadWriteSpi implements OperationRegistrySpi {
+-
+- /** The name of the product to which these operations belong. */
+- private String productName = "com.sun.media.jai";
+-
+- /** Default constructor. */
+- public ImageReadWriteSpi() {}
+-
+- /**
+- * Registers the "ImageRead" and "ImageWrite" operations and their
+- * associated image factories across all supported operation modes.
+- * An {@link OperationDescriptor} is created for each operation and
+- * registered with the supplied {@link OperationRegistry}. An image
+- * factory is then created for each supported mode of each operation
+- * registered for that operation with the registry.
+- *
+- * @param registry The registry with which to register the operations
+- * and their factories.
+- */
+- public void updateRegistry(OperationRegistry registry) {
+- // Create the "ImageRead" descriptor instance.
+- OperationDescriptor readDescriptor = new ImageReadDescriptor();
+-
+- // Register the "ImageRead" descriptor.
+- registry.registerDescriptor(readDescriptor);
+-
+- // Create the "ImageRead" CRIF.
+- ContextualRenderedImageFactory readCRIF = new ImageReadCRIF();
+-
+- // Get the "ImageRead" operation name.
+- String imageReadName = readDescriptor.getName();
+-
+- // Register the "ImageRead" factory for rendered mode.
+- registry.registerFactory(RenderedRegistryMode.MODE_NAME,
+- imageReadName,
+- productName,
+- readCRIF);
+-
+- // Register the "ImageRead" factory for renderable mode.
+- registry.registerFactory(RenderableRegistryMode.MODE_NAME,
+- imageReadName,
+- productName,
+- readCRIF);
+-
+- // Create and register the "ImageRead" factory for collection mode.
+- registry.registerFactory(CollectionRegistryMode.MODE_NAME,
+- imageReadName,
+- productName,
+- new ImageReadCIF());
+-
+- // Create the "ImageWrite" descriptor instance.
+- OperationDescriptor writeDescriptor = new ImageWriteDescriptor();
+-
+- // Register the "ImageWrite" descriptor.
+- registry.registerDescriptor(writeDescriptor);
+-
+- // Create the "ImageWrite" CRIF.
+- ContextualRenderedImageFactory writeCRIF = new ImageWriteCRIF();
+-
+- // Get the "ImageWrite" operation name.
+- String imageWriteName = writeDescriptor.getName();
+-
+- // Register the "ImageWrite" factory for rendered mode.
+- registry.registerFactory(RenderedRegistryMode.MODE_NAME,
+- imageWriteName,
+- productName,
+- writeCRIF);
+-
+- // Register the "ImageWrite" factory for renderable mode.
+- registry.registerFactory(RenderableRegistryMode.MODE_NAME,
+- imageWriteName,
+- productName,
+- writeCRIF);
+-
+- // Create and register the "ImageWrite" factory for collection mode.
+- registry.registerFactory(CollectionRegistryMode.MODE_NAME,
+- imageWriteName,
+- productName,
+- new ImageWriteCIF());
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/ImageWriteCIF.java zzx2/src/share/classes/com/sun/media/jai/imageioimpl/ImageWriteCIF.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/ImageWriteCIF.java 2005-02-11 00:01:55.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/jai/imageioimpl/ImageWriteCIF.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,296 +0,0 @@
+-/*
+- * $RCSfile: ImageWriteCIF.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:55 $
+- * $State: Exp $
+- */
+-package com.sun.media.jai.imageioimpl;
+-
+-import java.awt.RenderingHints;
+-import java.awt.image.BufferedImage;
+-import java.awt.image.RenderedImage;
+-import java.awt.image.renderable.ParameterBlock;
+-import java.io.IOException;
+-import java.util.ArrayList;
+-import java.util.Collection;
+-import java.util.Iterator;
+-import javax.imageio.ImageIO;
+-import javax.imageio.ImageWriteParam;
+-import javax.imageio.ImageWriter;
+-import javax.imageio.metadata.IIOMetadata;
+-import javax.imageio.stream.ImageOutputStream;
+-import javax.media.jai.CollectionImage;
+-import javax.media.jai.CollectionImageFactory;
+-import javax.media.jai.CollectionOp;
+-import javax.media.jai.PropertySource;
+-import com.sun.media.jai.operator.ImageWriteDescriptor;
+-
+-public final class ImageWriteCIF implements CollectionImageFactory {
+- /** Constructor. */
+- public ImageWriteCIF() {}
+-
+- public CollectionImage create(ParameterBlock args,
+- RenderingHints hints) {
+-
+- // Get the writer.
+- ImageWriter writer = (ImageWriter)args.getObjectParameter(13);
+-
+- // Find a writer if null.
+- if(writer == null) {
+- // Get the format. Should be non-null from OperationDescriptor.
+- String format = (String)args.getObjectParameter(1);
+-
+- // Find a writer.
+- Iterator writers = ImageIO.getImageWritersByFormatName(format);
+-
+- // Get the writer.
+- if(writers != null) {
+- writer = (ImageWriter)writers.next();
+- } else {
+- throw new RuntimeException
+- (I18N.getString("ImageWriteCIF0")+" "+format);
+- }
+- }
+-
+- // Get the source Collection.
+- Collection collection = (Collection)args.getSource(0);
+-
+- // Determine the number of RenderedImages in the Collection.
+- int numRenderedImages = 0;
+- Iterator iter = collection.iterator();
+- while(iter.hasNext()) {
+- if(iter.next() instanceof RenderedImage) {
+- numRenderedImages++;
+- }
+- }
+-
+- // Set the sequence flag.
+- boolean writeToSequence = writer.canWriteSequence();
+-
+- // Check that the writer can write sequences.
+- if(numRenderedImages > 1 && !writeToSequence) {
+- throw new RuntimeException
+- (I18N.getString("ImageWriteCIF1"));
+- }
+-
+- // Get the stream metadata.
+- IIOMetadata streamMetadata =
+- (IIOMetadata)args.getObjectParameter(7);
+-
+- // Get the property use flag.
+- boolean useProperties =
+- ((Boolean)args.getObjectParameter(2)).booleanValue();
+-
+- // If null, get stream metadata from source properties if allowed.
+- if(streamMetadata == null &&
+- useProperties &&
+- collection instanceof PropertySource) {
+- Object streamMetadataProperty =
+- ((PropertySource)collection).getProperty(
+- ImageWriteDescriptor.PROPERTY_NAME_METADATA_STREAM);
+- if(streamMetadataProperty instanceof IIOMetadata) {
+- streamMetadata = (IIOMetadata)streamMetadataProperty;
+- }
+- }
+-
+- // Get the writer parameters.
+- ImageWriteParam param = (ImageWriteParam)args.getObjectParameter(12);
+-
+- // Transcode the stream metadata if requested.
+- if(streamMetadata != null) {
+- // Get the transcoding flag.
+- boolean transcode =
+- ((Boolean)args.getObjectParameter(3)).booleanValue();
+-
+- if(transcode) {
+- // Overwrite the stream metadata with transcoded metadata.
+- streamMetadata =
+- writer.convertStreamMetadata(streamMetadata,
+- param);
+- }
+- }
+-
+- if(writeToSequence) {
+- // Write the stream metadata to the sequence.
+- try {
+- // Get the output.
+- Object output = args.getObjectParameter(0);
+-
+- // Try to get an ImageOutputStream.
+- ImageOutputStream stream =
+- ImageWriteCRIF.getImageOutputStream(output);
+-
+- // Set the writer's output.
+- writer.setOutput(stream != null ? stream : output);
+-
+- // Prepare the sequence.
+- writer.prepareWriteSequence(streamMetadata);
+- } catch(IOException e) {
+- throw new RuntimeException(e);
+- }
+- }
+-
+- // Clone the ParameterBlock as the writer, image metadata, and
+- // thumbnail parameters will be replaced.
+- ParameterBlock imagePB = (ParameterBlock)args.clone();
+-
+- // Clear the stream metadata.
+- imagePB.set(null, 7);
+-
+- // Set the ImageWriter.
+- imagePB.set(writer, 13);
+-
+- // Get the image metadata array.
+- IIOMetadata[] imageMetadata =
+- (IIOMetadata[])args.getObjectParameter(8);
+-
+- // Get the thumbnail array.
+- BufferedImage[] thumbnails =
+- (BufferedImage[])args.getObjectParameter(9);
+-
+- // Create a new Iterator.
+- iter = collection.iterator();
+-
+- // Create an ImageIOCollectionImage to contain the result:
+- ImageIOCollectionImage imageList =
+- new ImageIOCollectionImage(collection.size());
+-
+- // Iterate over the collection.
+- int imageIndex = 0;
+- while(iter.hasNext()) {
+- // Get the next element.
+- Object nextElement = iter.next();
+-
+- // Process if a RenderedImage.
+- if(nextElement instanceof RenderedImage) {
+- // Replace source with current RenderedImage.
+- imagePB.setSource((RenderedImage)nextElement, 0);
+-
+- // Replace image metadata.
+- if(imageMetadata != null) {
+- imagePB.set(imageMetadata[imageIndex], 8);
+- }
+-
+- // Replace thumbnail array.
+- if(thumbnails != null) {
+- imagePB.set(thumbnails[imageIndex], 9);
+- }
+-
+- // Write the image to the sequence
+- RenderedImage nextImage =
+- ImageWriteCRIF.create(imageIndex,
+- writeToSequence,
+- imagePB, hints);
+-
+- // If the ImageWriteParam passed in was null, replace it
+- // with the first non-null ImageWriteParam property value
+- // and set the value in the local ParameterBlock.
+- if(param == null) {
+- Object paramPropertyValue =
+- nextImage.getProperty(
+- ImageWriteDescriptor.PROPERTY_NAME_IMAGE_WRITE_PARAM);
+-
+- if(paramPropertyValue instanceof ImageWriteParam) {
+- param = (ImageWriteParam)paramPropertyValue;
+-
+- // Replace the ImageWriteParam so the CRIF doesn't
+- // have to re-do the tile size initialization.
+- imagePB.set(param, 12);
+- }
+- }
+-
+- // Add the image to the collection to be returned.
+- imageList.add(nextImage);
+-
+- // Increment the index.
+- imageIndex++;
+- }
+- }
+-
+- // Get the pixel replacement parameter.
+- boolean allowPixelReplacement =
+- ((Boolean)args.getObjectParameter(5)).booleanValue();
+-
+- if(writeToSequence && !allowPixelReplacement) {
+- // Complete writing the sequence.
+- try {
+- // XXX What about pixel replacement? If this is invoked here
+- // it will not be possible. How can this be invoked such that
+- // pixel replacement can occur but the user is not obliged to
+- // call this method manually?
+- // Answer: document that the user must obtain the writer from
+- // the collection-level ImageWriter property and invoke
+- // endWriteSequence() on it.
+- writer.endWriteSequence();
+- } catch(IOException e) {
+- throw new RuntimeException(e);
+- }
+- }
+-
+- // Set collection-level properties.
+- if(param != null) {
+- imageList.setProperty(
+- ImageWriteDescriptor.PROPERTY_NAME_IMAGE_WRITE_PARAM,
+- param);
+- }
+- imageList.setProperty(
+- ImageWriteDescriptor.PROPERTY_NAME_IMAGE_WRITER,
+- writer);
+- if(streamMetadata != null) {
+- imageList.setProperty(
+- ImageWriteDescriptor.PROPERTY_NAME_METADATA_STREAM,
+- streamMetadata);
+- }
+-
+- // Return CollectionImage.
+- return imageList;
+- }
+-
+- // Forget it.
+- public CollectionImage update(ParameterBlock oldParamBlock,
+- RenderingHints oldHints,
+- ParameterBlock newParamBlock,
+- RenderingHints newHints,
+- CollectionImage oldRendering,
+- CollectionOp op) {
+- return null;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/ImageWriteCRIF.java zzx2/src/share/classes/com/sun/media/jai/imageioimpl/ImageWriteCRIF.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/ImageWriteCRIF.java 2005-02-11 00:01:55.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/jai/imageioimpl/ImageWriteCRIF.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,663 +0,0 @@
+-/*
+- * $RCSfile: ImageWriteCRIF.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:55 $
+- * $State: Exp $
+- */
+-package com.sun.media.jai.imageioimpl;
+-
+-import java.awt.Dimension;
+-import java.awt.RenderingHints;
+-import java.awt.image.BufferedImage;
+-import java.awt.image.RenderedImage;
+-import java.awt.image.renderable.ParameterBlock;
+-import java.awt.image.renderable.RenderableImage;
+-import java.awt.image.renderable.RenderContext;
+-import java.io.IOException;
+-import java.io.OutputStream;
+-import java.io.RandomAccessFile;
+-import java.net.Socket;
+-import java.util.Arrays;
+-import java.util.EventListener;
+-import java.util.Iterator;
+-import java.util.Locale;
+-import javax.imageio.IIOImage;
+-import javax.imageio.ImageIO;
+-import javax.imageio.ImageTypeSpecifier;
+-import javax.imageio.ImageWriter;
+-import javax.imageio.ImageWriteParam;
+-import javax.imageio.event.IIOWriteProgressListener;
+-import javax.imageio.event.IIOWriteWarningListener;
+-import javax.imageio.metadata.IIOMetadata;
+-import javax.imageio.stream.ImageOutputStream;
+-import javax.media.jai.CRIFImpl;
+-import javax.media.jai.PlanarImage;
+-import javax.media.jai.RenderedImageAdapter;
+-import javax.media.jai.WritablePropertySource;
+-import com.sun.media.jai.operator.ImageWriteDescriptor;
+-
+-public final class ImageWriteCRIF extends CRIFImpl {
+- public static void main(String[] args) throws Throwable {
+- java.io.File inFile = new java.io.File(args[0]);
+- java.io.File outFile = new java.io.File(args[1]);
+- String format = args.length > 2 ? args[2] : "png";
+- String mode = args.length > 3 ? args[3] : "rendered";
+-
+- int imageIndex = 0;
+-
+- javax.imageio.stream.ImageInputStream inStream =
+- javax.imageio.ImageIO.createImageInputStream(inFile);
+-
+- java.util.Iterator iter =
+- javax.imageio.ImageIO.getImageReaders(inStream);
+- javax.imageio.ImageReader reader =
+- (javax.imageio.ImageReader)iter.next();
+-
+- reader.setInput(inStream);
+-
+- RenderedImage image = reader.read(imageIndex);
+-
+- javax.imageio.metadata.IIOMetadata streamMetadata =
+- reader.getStreamMetadata();
+- javax.imageio.metadata.IIOMetadata imageMetadata =
+- reader.getImageMetadata(imageIndex);
+-
+- java.awt.image.BufferedImage[] thumbnails = null;
+- if(reader.hasThumbnails(imageIndex)) {
+- int numThumbnails = reader.getNumThumbnails(imageIndex);
+- thumbnails = new java.awt.image.BufferedImage[numThumbnails];
+- for(int i = 0; i < numThumbnails; i++) {
+- thumbnails[i] = reader.readThumbnail(imageIndex, i);
+- }
+- }
+-
+- ImageWriteCRIF crif = new ImageWriteCRIF();
+-
+- ParameterBlock pb = new ParameterBlock();
+-
+- if(mode.equalsIgnoreCase("rendered")) {
+- pb.addSource(image);
+- } else if(mode.equalsIgnoreCase("renderable")) {
+- ParameterBlock renderablePB = new ParameterBlock();
+- renderablePB.addSource(image);
+- RenderableImage renderable =
+- javax.media.jai.JAI.createRenderable("renderable",
+- renderablePB);
+- pb.addSource(renderable);
+- }
+-
+- pb.add(outFile); // Output
+- pb.add(format); // Format
+-
+- pb.add(Boolean.TRUE); // UseProperties
+- pb.add(Boolean.TRUE); // Transcode
+- pb.add(Boolean.TRUE); // VerifyOutput
+- pb.add(Boolean.TRUE); // AllowPixelReplacement
+-
+- pb.add(null); // TileSize
+-
+- pb.add(streamMetadata);
+- pb.add(imageMetadata);
+- pb.add(thumbnails);
+-
+- pb.add(null); // EventListener[]
+- pb.add(null); // Locale
+-
+- pb.add(null); // ImageWriteParam
+- pb.add(null); // ImageWriter
+-
+- if(mode.equalsIgnoreCase("rendered")) {
+- crif.create(pb, null);
+- } else if(mode.equalsIgnoreCase("renderable")) {
+- java.awt.geom.AffineTransform transform =
+- new java.awt.geom.AffineTransform(256, 0, 0, 512, 0, 0);
+- crif.create(new RenderContext(transform), pb);
+- }
+- }
+-
+- public ImageWriteCRIF() {
+- super();
+- }
+-
+- /**
+- * Attempt to create an {@link ImageOutputStream} for the supplied
+- * output. The following sequence is effected:
+- *
+- *
+- *
+- * @param output An
+- *
output
is an ImageOutputStream
it
+- * is cast and returned.output
is a String
it is converted
+- * to a read-write RandomAccessFile
.output
is a Socket
it is converted
+- * to an OutputStream
.ImageIO.createImageOutputStream()
is invoked
+- * with parameter set to the (possibly converted) output and the
+- * value it returns (which could be null
) is returned
+- * to the caller.Object
to be used as the destination,
+- * such as a String
, File
, writable
+- * RandomAccessFile
, OutputStream
, writable
+- * Socket
, or writable Channel
.
+- *
+- * @return An ImageOutputStream
or null
.
+- */
+- static ImageOutputStream getImageOutputStream(Object output) {
+- // The value to be returned.
+- ImageOutputStream stream = null;
+-
+- // If already an ImageOutputStream just cast.
+- if(output instanceof ImageOutputStream) {
+- stream = (ImageOutputStream)output;
+- } else {
+- if(output instanceof String) {
+- // If output is a String replace it with a RandomAccessFile.
+- try {
+- // 'output' is conditionally checked for writability
+- // in the OperationDescriptor.
+- output = new RandomAccessFile((String)output, "rw");
+- } catch(Exception e) {
+- throw new RuntimeException
+- (I18N.getString("ImageWriteCRIF0")+" "+output);
+- }
+- } else if(output instanceof Socket) {
+- // If output is a Socket replace it with an OutputStream.
+- try {
+- // XXX check binding, connection, closed, shutdown
+- // as these could have changed.
+- output = ((Socket)output).getOutputStream();
+- } catch(Exception e) {
+- throw new RuntimeException
+- (I18N.getString("ImageWriteCRIF1")+" "+output);
+- }
+- }
+-
+- // Create the ImageOutputStream.
+- try {
+- stream = ImageIO.createImageOutputStream(output);
+- } catch(IOException e) {
+- throw new RuntimeException(e);
+- }
+- }
+-
+- return stream;
+- }
+-
+- /**
+- * {@link RenderedImageFactory} implementation.
+- */
+- public RenderedImage create(ParameterBlock pb,
+- RenderingHints rh) {
+- return create(0, false, pb, rh);
+- }
+-
+- private static ImageWriteParam getWriteParam(ImageWriteParam param,
+- ImageWriter writer) {
+- // Set default to original ImageWriteParam.
+- ImageWriteParam newParam = param;
+-
+- if(param == null) {
+- newParam = writer.getDefaultWriteParam();
+- } else if(param.getClass().getName().equals(
+- "javax.imageio.ImageWriteParam")) {
+- // The ImageWriteParam passed in is non-null. As the
+- // ImageWriteParam class is not Cloneable, if the param
+- // class is simply ImageWriteParam, then create a new
+- // ImageWriteParam instance and set all its fields
+- // which were set in param. This will eliminate problems
+- // with concurrent modification of param for the cases
+- // in which there is not a special ImageWriteParam used.
+-
+- // Create a new ImageWriteParam instance.
+- newParam = writer.getDefaultWriteParam();
+-
+- // Set all fields which need to be set.
+-
+- // IIOParamController field.
+- if(param.hasController()) {
+- newParam.setController(param.getController());
+- }
+-
+- // Destination fields.
+- newParam.setDestinationOffset(param.getDestinationOffset());
+- newParam.setDestinationType(param.getDestinationType());
+-
+- // Source fields.
+- newParam.setSourceBands(param.getSourceBands());
+- newParam.setSourceRegion(param.getSourceRegion());
+- newParam.setSourceSubsampling(param.getSourceXSubsampling(),
+- param.getSourceYSubsampling(),
+- param.getSubsamplingXOffset(),
+- param.getSubsamplingYOffset());
+-
+- // Compression.
+- if(param.canWriteCompressed()) {
+- int compressionMode = param.getCompressionMode();
+- newParam.setCompressionMode(compressionMode);
+- if(compressionMode == ImageWriteParam.MODE_EXPLICIT) {
+- newParam.setCompressionQuality(param.getCompressionQuality());
+- newParam.setCompressionType(param.getCompressionType());
+- }
+- }
+-
+- // Progressive
+- if(param.canWriteProgressive()) {
+- newParam.setProgressiveMode(param.getProgressiveMode());
+- }
+-
+- // Tiling
+- if(param.canWriteTiles()) {
+- int tilingMode = param.getTilingMode();
+- newParam.setTilingMode(tilingMode);
+- if(tilingMode == ImageWriteParam.MODE_EXPLICIT) {
+- newParam.setTiling(param.getTileWidth(),
+- param.getTileHeight(),
+- param.getTileGridXOffset(),
+- param.getTileGridYOffset());
+- }
+- }
+- }
+-
+- return newParam;
+- }
+-
+- /**
+- * If tiling is supported, determine the appropriate tile size and
+- * set it on the returned param if necessary. The returned param
+- * will either be a new ImageWriteParam or the one passed in with
+- * its tiling settings possibly modified.
+- */
+- private static ImageWriteParam setTileSize(ImageWriteParam param,
+- ImageWriter writer,
+- Dimension tileSize,
+- RenderedImage source) {
+-
+- ImageWriteParam returnParam = getWriteParam(param, writer);
+-
+- // If tiling possible set tile size if needed.
+- if(returnParam.canWriteTiles()) {
+- if(tileSize != null) {
+- // Check tile size.
+- if(tileSize.width <= 0 || tileSize.height <= 0) {
+- throw new IllegalArgumentException
+- ("tileSize.width <= 0 || tileSize.height <= 0");
+- }
+-
+- // Use specified tile size.
+- returnParam.setTilingMode(ImageWriteParam.MODE_EXPLICIT);
+- returnParam.setTiling(tileSize.width,
+- tileSize.height,
+- 0, 0); // XXX set tile offsets?
+- } else if(param == null) {
+- if(source.getNumXTiles() > 1 || source.getNumYTiles() > 1) {
+- // Null tile size and param args: use source tile size.
+- returnParam.setTilingMode(ImageWriteParam.MODE_EXPLICIT);
+- returnParam.setTiling(source.getTileWidth(),
+- source.getTileHeight(),
+- 0, 0); // XXX set tile offsets?
+- }
+- } else if(returnParam.getTilingMode() ==
+- ImageWriteParam.MODE_EXPLICIT) {
+- // Param passed in has explicit mode set but the tile
+- // grid might not actually be set.
+- boolean setTileSize = false;
+-
+- // Save reference to preferred tile size array.
+- Dimension[] preferredTileSizes =
+- returnParam.getPreferredTileSizes();
+-
+- // Set the tile width.
+- int tileWidth = 0;
+- try {
+- // Try to get it from the param.
+- tileWidth = returnParam.getTileWidth();
+- } catch(IllegalStateException e) {
+- // Not set in the param.
+- setTileSize = true;
+-
+- if(preferredTileSizes != null &&
+- preferredTileSizes.length >= 2 &&
+- preferredTileSizes[0].width > 0 &&
+- preferredTileSizes[1].width > 0) {
+- // Use average of first two preferred tile widths.
+- tileWidth = (preferredTileSizes[0].width +
+- preferredTileSizes[1].width) / 2;
+- } else {
+- // Use source image tile width.
+- tileWidth = source.getTileWidth();
+- }
+- }
+-
+- // Set the tile height.
+- int tileHeight = 0;
+- try {
+- // Try to get it from the param.
+- tileHeight = returnParam.getTileHeight();
+- } catch(IllegalStateException e) {
+- // Not set in the param.
+- setTileSize = true;
+-
+- if(preferredTileSizes != null &&
+- preferredTileSizes.length >= 2 &&
+- preferredTileSizes[0].height > 0 &&
+- preferredTileSizes[1].height > 0) {
+- // Use average of first two preferred tile heights.
+- tileHeight = (preferredTileSizes[0].height +
+- preferredTileSizes[1].height) / 2;
+- } else {
+- // Use source image tile height.
+- tileHeight = source.getTileHeight();
+- }
+- }
+-
+- // Set the tile size if not previously set in the param.
+- if(setTileSize) {
+- returnParam.setTiling(tileWidth,
+- tileHeight,
+- 0, 0); // XXX set tile offsets?
+- }
+- }
+- }
+-
+- return returnParam;
+- }
+-
+- static RenderedImage create(int imageIndex,
+- boolean writeToSequence,
+- ParameterBlock pb,
+- RenderingHints rh) {
+-
+- // Value to be returned.
+- RenderedImage image = null;
+-
+- // Get the source image.
+- RenderedImage source = pb.getRenderedSource(0);
+-
+- // Get the writer parameters.
+- ImageWriteParam param = (ImageWriteParam)pb.getObjectParameter(12);
+-
+- // Set the target image type.
+- ImageTypeSpecifier destinationType = null;
+- if(param != null) {
+- destinationType = param.getDestinationType();
+- }
+- if(destinationType == null) {
+- destinationType = new ImageTypeSpecifier(source);
+- }
+-
+- // Get the writer.
+- ImageWriter writer = (ImageWriter)pb.getObjectParameter(13);
+-
+- if(writer == null) {
+- // Get the format. Should be non-null from OperationDescriptor.
+- String format = (String)pb.getObjectParameter(1);
+-
+- // Find a writer.
+- Iterator writers = ImageIO.getImageWriters(destinationType,
+- format);
+-
+- // Get the writer.
+- if(writers != null && writers.hasNext()) {
+- writer = (ImageWriter)writers.next();
+- }
+- }
+-
+- // XXX What if no writer? Exception?
+- if(writer != null) {
+- // XXX Replace ImageWriter parameter in ParameterBlock?
+-
+- ImageOutputStream streamToClose = null;
+-
+- // Set the output if not writing to a sequence (in which
+- // case the output should already be set.
+- if(!writeToSequence) {
+- // Get the output.
+- Object output = pb.getObjectParameter(0);
+-
+- // Try to get an ImageOutputStream.
+- ImageOutputStream stream = getImageOutputStream(output);
+-
+- // Set stream to close if not writing to a sequence.
+- streamToClose = stream != output ? stream : null;
+-
+- // Set the writer's output.
+- writer.setOutput(stream != null ? stream : output);
+- }
+-
+- // Get the property use flag.
+- boolean useProperties =
+- ((Boolean)pb.getObjectParameter(2)).booleanValue();
+-
+- // Get the transcoding flag.
+- boolean transcode =
+- ((Boolean)pb.getObjectParameter(3)).booleanValue();
+-
+- IIOMetadata streamMetadata = null;
+- if(!writeToSequence) {
+- // Get the stream metadata.
+- streamMetadata = (IIOMetadata)pb.getObjectParameter(7);
+-
+- // If null, get stream metadata from source properties
+- // if allowed.
+- if(streamMetadata == null && useProperties) {
+- Object streamMetadataProperty =
+- source.getProperty(
+- ImageWriteDescriptor.PROPERTY_NAME_METADATA_STREAM);
+- if(streamMetadataProperty instanceof IIOMetadata) {
+- streamMetadata = (IIOMetadata)streamMetadataProperty;
+- }
+- }
+-
+- // Transcode the stream metadata if requested.
+- if(streamMetadata != null && transcode) {
+- // Overwrite the stream metadata with transcoded metadata.
+- streamMetadata =
+- writer.convertStreamMetadata(streamMetadata,
+- param);
+- }
+- }
+-
+- // Get the image metadata.
+- IIOMetadata imageMetadata =
+- (IIOMetadata)pb.getObjectParameter(8);
+-
+- // If null, get image metadata from source properties if allowed.
+- if(imageMetadata == null && useProperties) {
+- Object imageMetadataProperty =
+- source.getProperty(
+- ImageWriteDescriptor.PROPERTY_NAME_METADATA_IMAGE);
+- if(imageMetadataProperty instanceof IIOMetadata) {
+- imageMetadata = (IIOMetadata)imageMetadataProperty;
+- }
+- }
+-
+- // Transcode the image metadata if requested.
+- if(imageMetadata != null && transcode) {
+- // Overwrite the image metadata with transcoded metadata.
+- imageMetadata = writer.convertImageMetadata(imageMetadata,
+- destinationType,
+- param);
+- }
+-
+- // Get the thumbnails if supported by the writer.
+- BufferedImage[] thumbnails = null;
+- if(writer.getNumThumbnailsSupported(destinationType,
+- param,
+- streamMetadata,
+- imageMetadata) > 0) {
+- thumbnails = (BufferedImage[])pb.getObjectParameter(9);
+-
+- // If null, get thumbnails from source properties if allowed.
+- if(thumbnails == null && useProperties) {
+- Object thumbnailsProperty =
+- source.getProperty(
+- ImageWriteDescriptor.PROPERTY_NAME_METADATA_IMAGE);
+- if(thumbnailsProperty instanceof BufferedImage[]) {
+- thumbnails = (BufferedImage[])thumbnailsProperty;
+- }
+- }
+- }
+-
+- // Get the locale parameter and set on the writer.
+- Locale locale = (Locale)pb.getObjectParameter(11);
+- if(locale != null) {
+- writer.setLocale(locale);
+- }
+-
+- // Get the listeners parameter and set on the writer.
+- EventListener[] listeners =
+- (EventListener[])pb.getObjectParameter(10);
+- if(listeners != null) {
+- for(int i = 0; i < listeners.length; i++) {
+- EventListener listener = listeners[i];
+- if(listener instanceof IIOWriteProgressListener) {
+- writer.addIIOWriteProgressListener(
+- (IIOWriteProgressListener)listener);
+- }
+- if(listener instanceof IIOWriteWarningListener) {
+- writer.addIIOWriteWarningListener(
+- (IIOWriteWarningListener)listener);
+- }
+- }
+- }
+-
+- // Set the tile size.
+- // XXX Replace ImageWriteParam parameter in ParameterBlock?
+- param = setTileSize(param, writer,
+- (Dimension)pb.getObjectParameter(6),
+- source);
+-
+- // Create the IIOImage container.
+- IIOImage iioImage = new IIOImage(source,
+- thumbnails != null ?
+- Arrays.asList(thumbnails) : null,
+- imageMetadata);
+-
+- try {
+- // Write the image.
+- if(writeToSequence) {
+- writer.writeToSequence(iioImage, param);
+- } else {
+- writer.write(streamMetadata, iioImage, param);
+- }
+-
+- // Get the pixel replacement parameter.
+- boolean allowPixelReplacement =
+- ((Boolean)pb.getObjectParameter(5)).booleanValue();
+-
+- // Set the return value.
+- if(allowPixelReplacement &&
+- source instanceof PlanarImage &&
+- writer.canReplacePixels(imageIndex)) {
+-
+- // Create an image which is a PropertyChangeListener of
+- // "invalidregion" events including RenderingChangeEvents.
+- image = new PixelReplacementImage(source,
+- rh,
+- param,
+- writer,
+- imageIndex,
+- streamToClose);
+-
+- // Register the image as a sink of its source so that
+- // it automatically receives events.
+- ((PlanarImage)source).addSink(image);
+- } else if(!writeToSequence) {
+- Object writerOutput = writer.getOutput();
+- if(writerOutput != pb.getObjectParameter(0) &&
+- writerOutput instanceof ImageOutputStream) {
+- // This block is executed if and only if pixel
+- // replacement is not occurring, a sequence is
+- // not being written, and an ImageOutputStream
+- // inaccessible to the application is set on the
+- // ImageWriter.
+- ((ImageOutputStream)writerOutput).flush();
+- }
+-
+- // Set the return value to the original image or
+- // a wrapped version thereof.
+- image = source instanceof WritablePropertySource ?
+- source : new RenderedImageAdapter(source);
+- }
+-
+- // Set required properties.
+- WritablePropertySource wps = (WritablePropertySource)image;
+-
+- // Set the ImageWriteParam property.
+- wps.setProperty(
+- ImageWriteDescriptor.PROPERTY_NAME_IMAGE_WRITE_PARAM,
+- param);
+-
+- // Set the ImageWriter property.
+- wps.setProperty(
+- ImageWriteDescriptor.PROPERTY_NAME_IMAGE_WRITER,
+- writer);
+-
+- // Set the stream metadata property.
+- if(streamMetadata != null) {
+- wps.setProperty(
+- ImageWriteDescriptor.PROPERTY_NAME_METADATA_STREAM,
+- streamMetadata);
+- }
+-
+- // Set the image metadata property.
+- if(imageMetadata != null) {
+- wps.setProperty(
+- ImageWriteDescriptor.PROPERTY_NAME_METADATA_IMAGE,
+- imageMetadata);
+- }
+-
+- // Set the thumbnail property.
+- if(thumbnails != null) {
+- wps.setProperty(
+- ImageWriteDescriptor.PROPERTY_NAME_THUMBNAILS,
+- thumbnails);
+- }
+- } catch(IOException e) {
+- throw new RuntimeException(e);
+- }
+- }
+-
+- return image;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/PixelReplacementImage.java zzx2/src/share/classes/com/sun/media/jai/imageioimpl/PixelReplacementImage.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/PixelReplacementImage.java 2005-02-11 00:01:55.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/jai/imageioimpl/PixelReplacementImage.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,293 +0,0 @@
+-/*
+- * $RCSfile: PixelReplacementImage.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:55 $
+- * $State: Exp $
+- */
+-package com.sun.media.jai.imageioimpl;
+-
+-import java.awt.Point;
+-import java.awt.Rectangle;
+-import java.awt.Shape;
+-import java.awt.image.Raster;
+-import java.awt.image.RenderedImage;
+-import java.beans.PropertyChangeEvent;
+-import java.beans.PropertyChangeListener;
+-import java.io.IOException;
+-import java.io.OutputStream;
+-import java.util.Map;
+-import java.util.Vector;
+-import javax.media.jai.ImageLayout;
+-import javax.media.jai.OpImage;
+-import javax.media.jai.PlanarImage;
+-import javax.media.jai.RenderedOp;
+-import javax.media.jai.PropertyChangeEventJAI;
+-import javax.media.jai.RenderingChangeEvent;
+-import javax.imageio.ImageWriter;
+-import javax.imageio.ImageWriteParam;
+-import javax.imageio.stream.ImageOutputStream;
+-
+-/**
+- * Implementation of PlanarImage
for the "ImageWrite" operation
+- * for the case of ImageWriter
s which can replace pixels. The
+- * sole purpose of this class is to respond to "invalidregion" events so
+- * as to update the written image.
+- */
+-final class PixelReplacementImage extends PlanarImage
+- implements PropertyChangeListener {
+-
+- /**
+- * The ImageWriteParam
used in writing the image.
+- */
+- private ImageWriteParam param;
+-
+- /**
+- * The ImageWriter
used to write the image.
+- */
+- private ImageWriter writer;
+-
+- /**
+- * The index of the image to be write.
+- */
+- private int imageIndex;
+-
+- /**
+- * A stream to be closed when the instance is disposed; may be null.
+- */
+- private ImageOutputStream streamToClose;
+-
+- /**
+- * Creates a Vector
containing a single element.
+- */
+- private static Vector createVector(Object element) {
+- Vector v = new Vector(1);
+- v.add(element);
+- return v;
+- }
+-
+- /**
+- * XXX
+- */
+- PixelReplacementImage(RenderedImage source,
+- Map configuration,
+- ImageWriteParam param,
+- ImageWriter writer,
+- int imageIndex,
+- ImageOutputStream streamToClose) throws IOException {
+- super(new ImageLayout(source), // Layout same as source.
+- createVector(source),
+- configuration);
+-
+- // Verify that the writer can replace pixels.
+- if(!writer.canReplacePixels(imageIndex)) {
+- throw new IllegalArgumentException
+- ("!writer.canReplacePixels(imageIndex)");
+- }
+-
+- // Set the instance variables from the parameters.
+- // XXX Should ImageWriteParam original settings be cached for
+- // testing later to see whether anything important has changed?
+- this.param = param;
+- this.writer = writer;
+- this.imageIndex = imageIndex;
+- this.streamToClose = streamToClose;
+- }
+-
+- /**
+- * Close an ImageOutputStream
passed in.
+- */
+- public void dispose() {
+- if(streamToClose != null) {
+- try {
+- streamToClose.close();
+- } catch(IOException e) {
+- // Ignore it.
+- }
+- }
+-
+- super.dispose();
+- }
+-
+- /**
+- * Gets a tile.
+- *
+- * @param tileX The X index of the tile.
+- * @param tileY The Y index of the tile.
+- */
+- public Raster getTile(int tileX, int tileY) {
+- return getSourceImage(0).getTile(tileX, tileY);
+- }
+-
+- // --- PropertyChangeListener implementation ---
+-
+- // XXX Doc
+- public void propertyChange(PropertyChangeEvent evt) {
+- PlanarImage source = getSourceImage(0);
+- Object eventSource = evt.getSource();
+-
+- //
+- // Process the event if the writer can replace pixels,
+- // the event source is the source of this OpImage,
+- // and the event name is "invalidregion".
+- //
+- if((evt instanceof PropertyChangeEventJAI &&
+- evt.getPropertyName().equalsIgnoreCase("invalidregion") &&
+- eventSource.equals(source)) ||
+- (evt instanceof RenderingChangeEvent &&
+- evt.getOldValue().equals(source) &&
+- eventSource instanceof RenderedOp &&
+- evt.getNewValue().equals(((RenderedOp)eventSource).getRendering()))) {
+-
+- // Get the invalid region information.
+- Shape srcInvalidRegion = null;
+-
+- if(evt instanceof RenderingChangeEvent) {
+- // RenderingChangeEvent presumably from a source RenderedOp.
+- RenderingChangeEvent rcEvent = (RenderingChangeEvent)evt;
+-
+- // Get the invalidated region of the source.
+- srcInvalidRegion = rcEvent.getInvalidRegion();
+-
+- // Reset this image's source.
+- source = (PlanarImage)evt.getNewValue();
+- setSource(source, 0);
+-
+- // If entire source is invalid replace with source bounds.
+- if(srcInvalidRegion == null) {
+- srcInvalidRegion =
+- ((PlanarImage)rcEvent.getOldValue()).getBounds();
+- }
+- } else {
+- // Get the invalidated region of the source.
+- Object evtNewValue = (Shape)evt.getNewValue();
+-
+- // Continue if the value class is correct.
+- if(evtNewValue instanceof Shape) {
+- srcInvalidRegion = (Shape)evtNewValue;
+-
+- // If entire source is invalid replace with source bounds.
+- if(srcInvalidRegion == null) {
+- srcInvalidRegion = source.getBounds();
+- }
+- }
+- }
+-
+- // Return if the invalid portion could not be determined.
+- if(srcInvalidRegion == null) {
+- return;
+- }
+-
+- // Return if the invalid region does not overlap the param region.
+- if(param != null) {
+- Rectangle sourceRegion = param.getSourceRegion();
+- if(sourceRegion != null &&
+- !srcInvalidRegion.intersects(sourceRegion)) {
+- return;
+- }
+- } else {
+- param = writer.getDefaultWriteParam();
+- }
+-
+- // Get indices of all tiles overlapping the invalid region.
+- Point[] tileIndices =
+- source.getTileIndices(srcInvalidRegion.getBounds());
+-
+- // Should not happen but return if tileIndices is null.
+- if(tileIndices == null) return;
+-
+- // Get subsampling values.
+- int gridX = minX + param.getSubsamplingXOffset();
+- int gridY = minY + param.getSubsamplingYOffset();
+- int stepX = param.getSourceXSubsampling();
+- int stepY = param.getSourceYSubsampling();
+- boolean isSubsampling =
+- stepX != 1 || stepY != 1 || gridX != minX || gridY != minY;
+-
+- // Loop over affected tiles.
+- int numTiles = tileIndices.length;
+- for(int i = 0; i < numTiles; i++) {
+- // Save the next tile index.
+- Point tileIndex = tileIndices[i];
+-
+- // Compute tile bounds.
+- Rectangle tileRect =
+- source.getTileRect(tileIndex.x, tileIndex.y);
+-
+- // Replace if bounds intersect invalid region.
+- if(srcInvalidRegion.intersects(tileRect)) {
+- // Get the source tile.
+- Raster raster = source.getTile(tileIndex.x, tileIndex.y);
+-
+- Rectangle destRect;
+- if(isSubsampling) {
+- int destMinX =
+- (tileRect.x - gridX + stepX - 1)/stepX;
+- int destMinY =
+- (tileRect.y - gridY + stepY - 1)/stepY;
+- int destMaxX =
+- (tileRect.x + tileRect.width -
+- gridX + stepX - 1)/stepX;
+- int destMaxY =
+- (tileRect.y + tileRect.height -
+- gridY + stepY - 1)/stepY;
+- destRect = new Rectangle(destMinX, destMinY,
+- destMaxX - destMinX,
+- destMaxY - destMinY);
+- } else {
+- destRect = tileRect;
+- }
+-
+- // Replace the pixels.
+- try {
+- synchronized(writer) {
+- writer.prepareReplacePixels(imageIndex, destRect);
+- param.setDestinationOffset(destRect.getLocation());
+- writer.replacePixels(raster, param);
+- writer.endReplacePixels();
+- }
+- } catch(IOException e) {
+- throw new RuntimeException(e);
+- }
+- }
+- }
+- }
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/properties zzx2/src/share/classes/com/sun/media/jai/imageioimpl/properties
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/imageioimpl/properties 2005-02-11 00:01:56.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/jai/imageioimpl/properties 1969-12-31 19:00:00.000000000 -0500
+@@ -1,26 +0,0 @@
+-#
+-# $RCSfile: properties,v $
+-#
+-# Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
+-#
+-# Use is subject to license terms.
+-#
+-# $Revision: 1.1 $
+-# $Date: 2005/02/11 05:01:56 $
+-# $State: Exp $
+-#
+-# Internationalization file for com.sun.media.jai.imageioimpl
+-
+-ImageReadCRIF0=Cannot create read-only RandomAccessFile for path
+-ImageReadCRIF1=Cannot create InputStream for URL
+-ImageReadCRIF2=Cannot create InputStream for Socket
+-
+-ImageReadOpImage0=Destination bounds do not intersect available destination data region.
+-ImageReadOpImage1=Source or destination region is empty.
+-ImageReadOpImage2=Cannot perform rectangle mapping between source and destination because the image has no sources.
+-
+-ImageWriteCIF0=Unable to find an ImageWriter for format
+-ImageWriteCIF1=Source Collection has more than one image and ImageWriter cannot write sequences.
+-
+-ImageWriteCRIF0=Cannot create read-write RandomAccessFile for path
+-ImageWriteCRIF1=Cannot create OutputStream for Socket
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/operator/I18N.java zzx2/src/share/classes/com/sun/media/jai/operator/I18N.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/operator/I18N.java 2005-02-11 00:01:56.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/jai/operator/I18N.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,54 +0,0 @@
+-/*
+- * $RCSfile: I18N.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:56 $
+- * $State: Exp $
+- */
+-package com.sun.media.jai.operator;
+-
+-import com.sun.media.imageioimpl.common.I18NImpl;
+-
+-final class I18N extends I18NImpl {
+- static String getString(String key) {
+- return getString("com.sun.media.jai.operator.I18N", key);
+- }
+-}
+-
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/operator/ImageReadDescriptor.java zzx2/src/share/classes/com/sun/media/jai/operator/ImageReadDescriptor.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/operator/ImageReadDescriptor.java 2005-11-30 19:40:32.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/jai/operator/ImageReadDescriptor.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,1100 +0,0 @@
+-/*
+- * $RCSfile: ImageReadDescriptor.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.2 $
+- * $Date: 2005/12/01 00:40:32 $
+- * $State: Exp $
+- */
+-package com.sun.media.jai.operator;
+-
+-import java.awt.RenderingHints;
+-import java.awt.image.RenderedImage;
+-import java.awt.image.renderable.ContextualRenderedImageFactory;
+-import java.awt.image.renderable.ParameterBlock;
+-import java.awt.image.renderable.RenderableImage;
+-import java.io.File;
+-import java.io.InputStream;
+-import java.net.Socket;
+-import java.util.Collection;
+-import java.util.EventListener;
+-import java.util.Locale;
+-import javax.imageio.ImageReadParam;
+-import javax.imageio.ImageReader;
+-import javax.imageio.stream.ImageInputStream;
+-import javax.media.jai.JAI;
+-import javax.media.jai.OperationDescriptorImpl;
+-import javax.media.jai.OperationRegistry;
+-import javax.media.jai.PropertyGenerator;
+-import javax.media.jai.RenderedOp;
+-import javax.media.jai.RenderableOp;
+-import javax.media.jai.registry.CollectionRegistryMode;
+-import javax.media.jai.registry.RenderableRegistryMode;
+-import javax.media.jai.registry.RenderedRegistryMode;
+-import com.sun.media.jai.util.PropertyGeneratorImpl;
+-
+-/**
+- * An OperationDescriptor
describing the "ImageRead" operation.
+- *
+- * String
or some other type
+- * compatible with a reader plug-in. The
+- * {@link javax.imageio.ImageIO} class should be used to specify the location
+- * and enable the use of cache files via its setCacheDirectory()
+- * and setUseCache()
methods, respectively. Note that this cache
+- * pertains to image stream caching and is unrelated to the JAI
+- * TileCache
.OpImage
constructor, an
+- * ImageLayout
hint may also be
+- * supplied. The settings of this ImageLayout
override any other
+- * possible derivation of its components. In particular, it is possible that
+- * the generated image(s) have a different tile layout than that present in
+- * the image read from the input source.
+- *
+- * Name Value
+- * GlobalName ImageRead
+- * LocalName ImageRead
+- * Vendor com.sun.media.jai
+- * Description Reads an image using the Java Image I/O Framework.
+- * DocURL http://java.sun.com/products/java-media/jai/forDevelopers/jai-imageio-1_0-rc-docs/com/sun/media/jai/operator/ImageReadDescriptor.html
+- * Version 1.0
+- * arg0Desc The input source.
+- * arg1Desc The index or indices of the image(s) to read.
+- * arg2Desc Whether metadata should be read if available.
+- * arg3Desc Whether thumbnails should be read if available.
+- * arg4Desc Whether to verify the validity of the input source.
+- * arg5Desc EventListeners to be registered with the ImageReader.
+- * arg6Desc The Locale for the ImageReader to use.
+- * arg7Desc Java Image I/O read parameter instance.
+- * arg8Desc Java Image I/O reader instance.
Name | Class Type | +- *Default Value |
---|---|---|
+- * Input | java.lang.Object.class | +- *NO_PARAMETER_DEFAULT | +- *
+- * ImageChoice | java.lang.Integer | +- *0 | +- *
+- * ReadMetadata | java.lang.Boolean | +- *TRUE | +- *
+- * ReadThumbnails | java.lang.Boolean | +- *TRUE | +- *
+- * VerifyInput | java.lang.Boolean | +- *TRUE | +- *
+- * Listeners | java.util.EventListener[] | +- *null | +- *
+- * Locale | java.util.Locale | +- *null | +- *
+- * ReadParam | javax.imageio.ImageReadParam | +- *null | +- *
+- * Reader | javax.imageio.ImageReader | +- *null | +- *
The rendered mode parameters are handled as follows: +- * +- *
The foregoing policy regarding modification of any supplied ImageReadParam +- * or ImageReader is necessary as neither of these classes is cloneable. Given +- * that as a starting point there are in effect three possibilities: (A) do not +- * accept them as parameters, (B) accept them via alternate parameters which do +- * not pose these problems (for example an ImageReaderSpi and a long list of +- * settings represented by the ImageReadParam), or (C) accept them explicitly. +- * Option C has been deemed preferable despite the potential race condition +- * issues.
+- * +- *In the Sun Microsystems implementation of this operation these potential +- * conflicts have been mitigated to a certain extent: +- * +- *
Any fields of the supplied ImageLayout which are not set will be set to +- * default values as follows. The ImageLayout will be cloned before it is +- * modified.
+- * +- *Each value defaults to the corresponding value of the destination +- * which would be derived on the basis of the source image dimensions +- * and the settings of the ImageReadParam, i.e., source region, +- * subsampling offsets and factors, and destination offset.
+- * +- *It should be noted that unlike in the Java Image I/O API itself, +- * negative coordinates are permitted and the image origin is not +- * required to be at (0,0) as for BufferedImages. Therefore it is +- * possible that a given image be loaded using the same ImageReadParam +- * by an ImageReader and by the "ImageRead" operation with different +- * results. Possible differences would be that the portion of the +- * image with negative coordinates is not clipped as it would be with +- * direct Image I/O access, and no empty extent between (0,0) and the +- * start of the data will be present.
+- * +- *For example, if the ImageReadParam had sourceRegion [0,0,w,h], +- * destinationOffset [-w/2,-h/2], and no subsampling, then the Java +- * Image I/O API would compute the effective source and destination +- * regions to be [w/2,h/2,w/2,h/2] and [0,0,w/2,h/2], respectively. +- * The JAI ImageRead operation would compute the effective source and +- * destination regions to be [0,0,w,h] and [-w/2,-h/2,w,h], respectively. +- * The Image I/O result would therefore be equal to the bottom right +- * quadrant of the JAI result.
+- * tileGridXOffset = ImageReader.getTileGridXOffset(imageIndex); +- * tileGridYOffset = ImageReader.getTileGridYOffset(imageIndex); +- * tileWidth = ImageReader.getTileWidth(imageIndex); +- * tileHeight = ImageReader.getTileHeight(imageIndex); +- *
+- * ImageReader.getRawImageType(imageIndex).getColorModel(); +- *
+- * ImageReader.getRawImageType(imageIndex).getSampleModel().createCompatibleSampleModel(tileWidth, tileHeight); +- *
Property Name | +- *Type | +- *Comment | +- *
---|---|---|
JAI.ImageReadParam | +- *ImageReadParam | +- *Set to ImageReadParam actually used which may differ from the one passed in. | +- *
JAI.ImageReader | +- *ImageReader | +- *Set to ImageReader actually used. | +- *
JAI.ImageMetadata | +- *IIOMetadata | +- *Set if and only if ReadMetadata parameter is TRUE and image metadata are available. | +- *
JAI.StreamMetadata | +- *IIOMetadata | +- *Set if and only if ReadMetadata parameter is TRUE and stream metadata are available. | +- *
JAI.Thumbnails | +- *BufferedImage[] | +- *Set if and only if ReadThumbnails parameter is TRUE and thumbnails are available. | +- *
If a given property is not set, this implies of course that the names of +- * absent properties will not appear in the array returned by getPropertyNames() +- * and getProperty() invoked to obtain absent properties will return +- * java.awt.Image.UndefinedProperty as usual.
+- * +- *The ImageReader and ImageReadParam may be used for subsequent invocations +- * of the operation (for example to obtain different images in a multi-page file) +- * or for informational purposes. Care should be taken in using these property +- * values with respect to the synchronization issues previously discussed.
+- * +- *In all cases image metadata properties will be set when the node is rendered, +- * i.e., metadata reading is not subject to the same deferred execution as is +- * image data reading. The thumbnail property value will not be set however until +- * its value is actually requested.
+- * +- *It should be noted that although they are discussed in the context of +- * rendered mode, the parameter synchronization +- * policy and ImageLayout handling methodology +- * apply to renderable mode as well.
+- * +- *Name | Class Type | +- *Default Value |
---|---|---|
ImageChoice | int[] | +- *int[] {0,...,NumImages-1} | +- *
In the Sun Microsystems renderable mode implementation of the "ImageRead" +- * operation, when createRendering() is invoked on the RenderableImage created +- * by the operation, a MultiResolutionRenderableImage is constructed from a +- * Vector of RenderedImages consisting of the images at the specified indices. +- * These images will be sorted into order of decreasing resolution (as +- * determined by the product of width and height for each image) and inserted +- * in this order in the Vector of images used to construct the +- * MultiResolutionRenderableImage. Metadata will be set on the component +- * RenderedImages as usual for rendered mode. Finally the +- * createRendering() invocation will be forwarded to the underlying +- * MultiResolutionRenderableImage and the resulting RenderedImage returned.
+- * +- *Note that using this approach the entire MultiResolutionRenderableImage +- * must be regenerated for each invocation of createRendering(). If multiple +- * renderings are to be created from the RenderableImage without changing +- * the operation parameters, then a more efficient approach would be to use the +- * "JAI.RenderableInput" property to be described.
+- * +- *Property Name | +- *Type | +- *Comment | +- *
---|---|---|
JAI.RenderableInput | +- *RenderableImage | +- *A RenderableImage derived from the input source according to the supplied set of parameters. | +- *
The RenderableImage which is the value of the foregoing property may have +- * set on it any of the properties previously described for rendered mode +- * contingent on parameter settings and data availability. The image metadata +- * and thumbnail properties would be copied from the highest resolution image +- * among those specified by the ImageChoice parameter.
+- * +- *If multiple renderings are to be created from the RenderableImage +- * without changing the operation parameters, then an efficient alternative +- * approach to multiple invocations of createRendering() on the RenderableImage +- * is to obtain the RenderableImage value of the "JAI.RenderableInput" property +- * and invoke createRendering() on this value.
+- * +- *Collection
of RenderedImage
s from the specified
+- * input source. This could be used for example to load an animated GIF
+- * image or a multi-page TIFF image.
+- *
+- * It should be noted that although they are discussed in the context of +- * rendered mode, the parameter synchronization +- * policy and ImageLayout handling methodology +- * apply to collection mode as well.
+- * +- *ParameterBlock
+- * and invokes {@link JAI#create(String,ParameterBlock,RenderingHints)}.
+- *
+- * @param input The input source.
+- * @param imageChoice The index of the image to read.
+- * @param readMetadata Whether metadata should be read if available.
+- * @param readThumbnails Whether thumbnails should be read if available.
+- * @param verifyInput Whether to verify the validity of the input source.
+- * @param listeners EventListeners to be registered with the ImageReader.
+- * @param locale The Locale for the ImageReader to use.
+- * @param readParam Java Image I/O read parameter instance.
+- * @param reader Java Image I/O reader instance.
+- * @param hints Hints possibly including an ImageLayout
.
+- * @return an image derived from the input source.
+- */
+- public static RenderedOp create(ImageInputStream input,
+- Integer imageChoice,
+- Boolean readMetadata,
+- Boolean readThumbnails,
+- Boolean verifyInput,
+- EventListener[] listeners,
+- Locale locale,
+- ImageReadParam readParam,
+- ImageReader reader,
+- RenderingHints hints) {
+-
+- ParameterBlock args = new ParameterBlock();
+-
+- args.add(input);
+- args.add(imageChoice);
+- args.add(readMetadata);
+- args.add(readThumbnails);
+- args.add(verifyInput);
+- args.add(listeners);
+- args.add(locale);
+- args.add(readParam);
+- args.add(reader);
+-
+- return JAI.create(OPERATION_NAME, args, hints);
+- }
+-
+- /**
+- * Type-safe convenience method for creating a {@link Collection}
+- * representing the "ImageRead" operation in collection mode. The
+- * method packs the parameters into a new ParameterBlock
+- * and invokes
+- * {@link JAI#createCollection(String,ParameterBlock, RenderingHints)}.
+- *
+- * @param input The input source.
+- * @param imageChoice The indices of the images to read.
+- * @param readMetadata Whether metadata should be read if available.
+- * @param readThumbnails Whether thumbnails should be read if available.
+- * @param verifyInput Whether to verify the validity of the input source.
+- * @param listeners EventListeners to be registered with the ImageReader.
+- * @param locale The Locale for the ImageReader to use.
+- * @param readParam Java Image I/O read parameter instance.
+- * @param reader Java Image I/O reader instance.
+- * @param hints Hints possibly including an ImageLayout
.
+- * @return a collection of images derived from the input source.
+- */
+- public static Collection createCollection(ImageInputStream input,
+- int[] imageChoice,
+- Boolean readMetadata,
+- Boolean readThumbnails,
+- Boolean verifyInput,
+- EventListener[] listeners,
+- Locale locale,
+- ImageReadParam readParam,
+- ImageReader reader,
+- RenderingHints hints) {
+-
+- ParameterBlock args = new ParameterBlock();
+-
+- args.add(input);
+- args.add(imageChoice);
+- args.add(readMetadata);
+- args.add(readThumbnails);
+- args.add(verifyInput);
+- args.add(listeners);
+- args.add(locale);
+- args.add(readParam);
+- args.add(reader);
+-
+- return JAI.createCollection(OPERATION_NAME, args, hints);
+- }
+-
+- /**
+- * Type-safe convenience method for creating a {@link RenderableOp}
+- * representing the "ImageRead" operation in renderable mode. The
+- * method packs the parameters into a new ParameterBlock
+- * and invokes
+- * {@link JAI#createRenderable(String,ParameterBlock,RenderingHints)}.
+- *
+- * @param input The input source.
+- * @param imageChoice The indices of the images to read.
+- * @param readMetadata Whether metadata should be read if available.
+- * @param readThumbnails Whether thumbnails should be read if available.
+- * @param verifyInput Whether to verify the validity of the input source.
+- * @param listeners EventListeners to be registered with the ImageReader.
+- * @param locale The Locale for the ImageReader to use.
+- * @param readParam Java Image I/O read parameter instance.
+- * @param reader Java Image I/O reader instance.
+- * @param hints Hints possibly including an ImageLayout
.
+- * @return an image capable of rendering an image from those in the
+- * input source.
+- */
+- public static RenderableOp createRenderable(ImageInputStream input,
+- int[] imageChoice,
+- Boolean readMetadata,
+- Boolean readThumbnails,
+- Boolean verifyInput,
+- EventListener[] listeners,
+- Locale locale,
+- ImageReadParam readParam,
+- ImageReader reader,
+- RenderingHints hints) {
+-
+- ParameterBlock args = new ParameterBlock();
+-
+- args.add(input);
+- args.add(imageChoice);
+- args.add(readMetadata);
+- args.add(readThumbnails);
+- args.add(verifyInput);
+- args.add(listeners);
+- args.add(locale);
+- args.add(readParam);
+- args.add(reader);
+-
+- return JAI.createRenderable(OPERATION_NAME, args, hints);
+- }
+-
+- /**
+- * Returns the array of {@link PropertyGenerator}s for the specified
+- * mode of this operation.
+- *
+- * For renderable mode returns an array containing a single
+- * PropertyGenerator
which defines a
+- * {@link RenderableImage}-valued property named "JAI.RenderableInput".
+- * For all other modes null
is returned.
PropertyGenerator
+- * if modeName
is "renderable" (case-insensitive) or
+- * null
otherwise.
+- */
+- public PropertyGenerator[] getPropertyGenerators(String modeName) {
+- return modeName.equalsIgnoreCase(RenderableRegistryMode.MODE_NAME) ?
+- new PropertyGenerator[] { new ImageReadPropertyGenerator() } :
+- null;
+- }
+-
+- /**
+- * Validates the parameters in the supplied ParameterBlock
.
+- *
+- * In addition to the standard validation performed by the +- * corresponding superclass method, this method verifies the following: +- *
TRUE
and Input
+- * is a File
or String
, whether the
+- * corresponding physical file exists and is readable; andTRUE
and Input
+- * is a String
, converting which to a
+- * corresponding physical file failed, whether it can be converted
+- * to an InputStream accessed as a resource from a JAR file; andTRUE
and Input
+- * is a Socket
, whether it is bound, connected, open,
+- * and the read-half is not shut down.msg
and
+- * false
will be returned; otherwise true
will
+- * be returned.
+- *
+- * The file existence and readability verification may be suppressed
+- * by setting the VerifyInput parameter to FALSE
.
+- * This might be desirable for example if the operation is being
+- * created for remote rendering and Input is a file which is at
+- * a location visible on the remote peer but not on the host on which
+- * the operation is created.
OperationDescriptor
describing the "ImageWrite" operation.
+- *
+- * The "ImageWrite" operation uses the +- * Java +- * Image I/O Framework to write images to an output destination. Which +- * formats may be written depends on which {@link javax.imageio.ImageWriter} +- * plug-ins are registered with the Image I/O Framework when the operation is +- * invoked.
+- * +- *The output destination will usually be an
+- * {@link javax.imageio.stream.ImageOutputStream}, but may be a
+- * {@link java.io.File}, {@link java.io.RandomAccessFile},
+- * {@link java.io.OutputStream}, {@link java.net.Socket},
+- * {@link java.nio.channels.WritableByteChannel}, file path represented as a
+- * String
or some other type compatible with a writer plug-in. The
+- * {@link javax.imageio.ImageIO} class should be used to specify the location
+- * and enable the use of cache files via its setCacheDirectory()
+- * and setUseCache()
methods, respectively. Note that this cache
+- * pertains to image stream caching and is unrelated to the JAI
+- * TileCache
. If an {@link javax.imageio.stream.ImageOutputStream}
+- * is created internally by the operation, for example from a
+- * {@link java.io.File}-valued Output parameter,
+- * then it will be flushed automatically if and only if the operation is not
+- * in collection mode and pixel replacement is
+- * not occurring.
The "ImageWrite" operation supports rendered,
+- * renderable, and
+- * collection modes and requires a single
+- * source. The operation is "immediate" for all modes as specified by
+- * OperationDescriptor.isImmediate()
so that
+- * {@link #isImmediate()} returns true
. The operation will
+- * therefore be rendered when created via either JAI.create[NS]()
+- * or JAI.createCollection[NS]()
.
+- * A {@link java.awt.RenderingHints} object supplied when the
+- * operation is created will have no effect except with respect to the
+- * mapping of JAI.KEY_INTERPOLATION
and then only in renderable
+- * mode.
Image properties are used to pass metadata and other information to the +- * writer plug-in and to make available metadata as actually written to the +- * output destination. Property handling is mode-specific.
+- * +- *Name | Value |
---|---|
GlobalName | ImageWrite |
LocalName | ImageWrite |
Vendor | com.sun.media.jai |
Description | Writes an image using the Java Image I/O Framework. |
DocURL | http://java.sun.com/products/java-media/jai/forDevelopers/jai-imageio-1_0-rc-docs/com/sun/media/jai/operator/ImageWriteDescriptor.html |
Version | 1.0 |
arg0Desc | The output destination. |
arg1Desc | The format name of the output. |
arg2Desc | Whether to use image metadata properties as fallbacks. |
arg3Desc | Whether to transcode metadata before writing. |
arg4Desc | Whether to verify the validity of the output destination. |
arg5Desc | Whether to allow pixel replacement in the output image. |
arg6Desc | The tile size of the output image. |
arg7Desc | Stream metadata to write to the output. |
arg8Desc | Image metadata to write to the output. |
arg9Desc | Thumbnails to write to the output. |
arg10Desc | EventListeners to be registered with the ImageWriter. |
arg11Desc | The Locale for the ImageWriter to use. |
arg12Desc | Java Image I/O write parameter instance. |
arg13Desc | Java Image I/O writer instance. |
Name | Class Type | +- *Default Value |
---|---|---|
+- * Output | java.lang.Object.class | +- *NO_PARAMETER_DEFAULT | +- *
+- * Format | java.lang.String | +- *null | +- *
+- * UseProperties | java.lang.Boolean | +- *TRUE | +- *
+- * Transcode | java.lang.Boolean | +- *TRUE | +- *
+- * VerifyOutput | java.lang.Boolean | +- *TRUE | +- *
+- * AllowPixelReplacement | java.lang.Boolean | +- *FALSE | +- *
+- * TileSize | java.awt.Dimension | +- *null | +- *
+- * StreamMetadata | javax.imageio.metadata.IIOMetadata | +- *null | +- *
+- * ImageMetadata | javax.imageio.metadata.IIOMetadata | +- *null | +- *
+- * Thumbnails | java.awt.BufferedImage[] | +- *null | +- *
+- * Listeners | java.util.EventListener[] | +- *null | +- *
+- * Locale | java.util.Locale | +- *null | +- *
+- * WriteParam | javax.imageio.ImageWriteParam | +- *null | +- *
+- * Writer | javax.imageio.ImageWriter | +- *null | +- *
The rendered mode parameters are handled as follows: +- * +- *
In the Sun Microsystems implementation of this operation these potential +- * conflicts have been mitigated to a certain extent: +- * +- *
+- * if ImageWriter cannot write tiles +- * output is untiled +- * else +- * if TileSize parameter is non-null +- * set tile size to TileSize +- * else +- * if WriteParam is null +- * set tile size to source tile size +- * else +- * if tilingMode is ImageWriteParam.MODE_EXPLICIT +- * if tile dimension is set in WriteParam +- * set tile size to tile dimension from WriteParam +- * else +- * if preferred tile dimension is set in WriteParam +- * set tile size to average of first two preferred dimensions +- * else +- * set tile size to source tile size +- * else // tilingMode is not ImageWriteParam.MODE_EXPLICIT +- * the plug-in decides the tile size +- *+- * +- * There is no mechanism to set the tile grid offsets of the output. +- * +- *
Note that this behavior differs from what would happen if the RenderedOp +- * created by the operation received a RenderingChangeEvent: in this case a +- * new rendering of the node would be created using the ParameterBlock and +- * RenderingHints currently in effect. This would cause the entire image to be +- * rewritten at the current position of the output. This will also happen +- * when AllowPixelReplacement is FALSE. In effect in both of these cases the +- * behavior in response to a RenderingChangeEvent is unspecified and the result +- * will likely be unexpected.
+- * +- *To avoid any inadvertent overwriting of the destination as a result of +- * events received by the RenderedOp, the following usage is recommended when +- * the objective is automatic pixel replacement: +- * +- *
+- * // Sources, parameters, and hints. +- * ParameterBlock args; +- * RenderingHints hints; +- * +- * // Create the OperationNode. +- * RenderedOp imageWriteNode = JAI.create("ImageWrite", args, hints); +- * +- * // Get the rendering which already exists due to "immediate" status. +- * RenderedImage imageWriteRendering = imageWriteNode.getRendering(); +- * +- * // Unhook the OperationNode as a sink of its source OperationNode. +- * imageWriteNode.getSourceImage(0).removeSink(imageWriteNode); +- * +- * // Add the rendering as a sink of the source OperationNode. +- * imageWriteNode.getSourceImage(0).addSink(imageWriteRendering); +- * +- * // Free the OperationNode for garbage collection. +- * imageWriteNode = null; +- *+- * +- * At this point a reference to imageWriteRendering must be held as long as the +- * data of the source of the operation may change. Then provided the events are +- * correctly propagated to imageWriteRendering, the data in the output file +- * will be automatically updated to match the source data. +- * +- *
If pixel replacement is not the objective and inadvertent overwriting is +- * to be avoided then the safest approach would be the following: +- * +- *
+- * // Create the OperationNode. +- * RenderedOp imageWriteNode = JAI.create("ImageWrite", args, hints); +- * +- * // Unhook the OperationNode as a sink of its source +- * imageWriteNode.getSourceImage(0).removeSink(imageWriteNode); +- *+- * +- * The image is written by the first statement and no reference to the +- * rendering need be retained as before. +- * +- *
Property Name | +- *Type | +- *Comment | +- *
---|---|---|
JAI.ImageWriteParam | +- *ImageWriteParam | +- *Set to ImageWriteParam actually used which may differ from the one passed in. | +- *
JAI.ImageWriter | +- *ImageWriter | +- *Set to ImageWriter actually used. | +- *
JAI.ImageMetadata | +- *IIOMetadata | +- *Set if and only if image metadata are available; may be transcoded. | +- *
JAI.StreamMetadata | +- *IIOMetadata | +- *Set if and only if stream metadata are available; may be transcoded. | +- *
JAI.Thumbnails | +- *BufferedImage[] | +- *Set if and only thumbnails are provided and the writer supportes writing them. | +- *
If a given property is not set, this implies of course that the names of +- * absent properties will not appear in the array returned by getPropertyNames() +- * and getProperty() invoked to obtain absent properties will return +- * java.awt.Image.UndefinedProperty as usual.
+- * +- *The ImageWriter and ImageWriteParam may be used for subsequent invocations +- * of the operation or for informational purposes. Care should be taken in using +- * these property values with respect to the synchronization issues previously +- * discussed.
+- * +- *Metadata properties will be set to those actually written to the output. They +- * may be derived either from input parameters or source properties depending on +- * the values of the StreamMetadata, ImageMetadata, and UseProperties parameters. +- * They will be transcoded data if Transcode is TRUE and the ImageWriter supports +- * transcoding.
+- * +- *All properties will be set when the node is rendered.
+- * +- *JAI.KEY_INTERPOLATION
is supplied via a
+- * RenderingHints
passed to the operation, then the interpolation
+- * type it specifies will be used to create the rendering if interpolation is
+- * required.
+- *
+- * The Collection is treated as a sequence of images which will be +- * extracted from the Collection in the order returned by a new Iterator. +- * Elements in the Collection which are not RenderedImages will be ignored. +- * The derived sequence of images will then be written to the output.
+- * +- *If there is only one RenderedImage in the source Collection, this image +- * will be written as done in rendered mode operation. If there is more than +- * one RenderedImage, the sequence of RenderedImages will be written as an +- * image sequence. In the latter case the ImageWriter must be able to write +- * sequences.
+- * +- *Name | Class Type | +- *Default Value |
---|---|---|
ImageMetadata | javax.imageio.metadataIIOMetadata[] | +- *null | +- *
Thumbnails | java.awt.image.BufferedImage[][] | +- *null | +- *
+- * The change to the ImageMetadata and Thumbnails parameters is that there can +- * now be a distinct image metadata object and thumbnail array for each image +- * in the Collection. The components of these respective arrays will be indexed +- * using the sequence of RenderedImages extracted from the source Collection by +- * the Iterator. It is the responsibility of the caller to ensure that this +- * sequencing is correct. In this context it is advisable to use a source +- * Collection which maintains the order of its elements such as a List. +- *
+- * +- *+- * To ensure proper termination of the image sequence and avoid any inadvertent +- * overwriting of the destination as a result of events received by the +- * CollectionOp, the following usage is recommended when the objective is +- * automatic pixel replacement: +- * +- *
+- * // Sources, parameters, and hints. +- * ParameterBlock args; +- * RenderingHints hints; +- * +- * // Create the Collection. +- * CollectionImage imageWriteCollection = +- * (CollectionImage)JAI.createCollection("ImageWrite", args, hints); +- * +- * // Unhook the Collection node from the source to avoid +- * // re-renderings caused by CollectionChangeEvents. +- * if(args.getSource(0) instanceof CollectionImage) { +- * CollectionImage sourceCollection = +- * (CollectionImage)args.getSource(0); +- * sourceCollection.removeSink(imageWriteCollection); +- * } +- * +- * // !!! Pixel replacement activity happens here ... !!! +- * +- * // Get the ImageWriter. +- * ImageWriter writer = +- * (ImageWriter)imageWriteCollection.getProperty("JAI.ImageWriter"); +- * +- * // End the sequence if necessary. +- * if(writer.canWriteSequence()) { +- * writer.endWriteSequence(); +- * } +- *+- * +- * +- *
+- * Using the foregoing construct, all pixels in all images written to the output +- * sequence will remain current with the in-memory data of their respective +- * source provided all events are propagated as expected. Note that it is not +- * necessary to end the sequence manually if pixel replacement is not allowed or +- * is not supported. Also the sequence must be manually ended if and only if the +- * writer is capable of writing sequences. This permits pixel replacement to +- * work in the case where the source collection contains only a single image +- * and the writer supports pixel replacement but cannot write sequences. +- *
+- * +- *+- * If pixel replacement is not the objective, i.e., AllowPixelReplacement is +- * FALSE, and inadvertent overwriting is to be avoided then the safest approach +- * would be the following: +- * +- *
+- * // Create the Collection. +- * Collection imageWriteCollection = +- * JAI.create("ImageWrite", args, hints); +- * +- * // Unhook the Collection node from the source to avoid +- * // re-renderings caused by CollectionChangeEvents. +- * if(args.getSource(0) instanceof CollectionImage) { +- * CollectionImage sourceCollection = +- * (CollectionImage)args.getSource(0); +- * sourceCollection.removeSink(imageWriteCollection); +- * } +- *+- * +- * The image is written by the first statement and no reference to the +- * rendering need be retained. +- * +- *
ParameterBlock
and invokes
+- * {@link JAI#create(String,ParameterBlock,RenderingHints)}.
+- *
+- * @param source The image to be written.
+- * @param output The output destination.
+- * @param format The format name of the output.
+- * @param useProperties Whether to use image metadata properties as
+- * fallbacks.
+- * @param transcode Whether to transcode metadata before writing.
+- * @param verifyOutput Whether to verify the validity of the output
+- * destination.
+- * @param allowPixelReplacement Whether to allow pixel replacement
+- * in the output image.
+- * @param tileSize The tile size of the output image.
+- * @param streamMetadata Stream metadata to write to the output.
+- * @param imageMetadata Image metadata to write to the output.
+- * @param thumbnails Thumbnails to write to the output.
+- * @param listeners EventListeners to be registered with the ImageWriter.
+- * @param locale The Locale for the ImageWriter to use.
+- * @param writeParam Java Image I/O write parameter instance.
+- * @param writer Java Image I/O writer instance.
+- * @param hints Operation hints.
+- * @return a reference to the operation source.
+- */
+- public static RenderedOp create(RenderedImage source,
+- ImageOutputStream output,
+- String format,
+- Boolean useProperties,
+- Boolean transcode,
+- Boolean verifyOutput,
+- Boolean allowPixelReplacement,
+- Dimension tileSize,
+- IIOMetadata streamMetadata,
+- IIOMetadata imageMetadata,
+- BufferedImage[] thumbnails,
+- EventListener[] listeners,
+- Locale locale,
+- ImageWriteParam writeParam,
+- ImageWriter writer,
+- RenderingHints hints) {
+-
+- ParameterBlock args = new ParameterBlock();
+-
+- args.addSource(source);
+-
+- args.add(output);
+- args.add(format);
+- args.add(useProperties);
+- args.add(transcode);
+- args.add(verifyOutput);
+- args.add(allowPixelReplacement);
+- args.add(tileSize);
+- args.add(streamMetadata);
+- args.add(imageMetadata);
+- args.add(thumbnails);
+- args.add(listeners);
+- args.add(locale);
+- args.add(writeParam);
+- args.add(writer);
+-
+- return JAI.create(OPERATION_NAME, args, hints);
+- }
+-
+- /**
+- * Type-safe convenience method for creating a {@link Collection}
+- * representing the "ImageWrite" operation in collection mode. The
+- * method packs the source and parameters into a new
+- * ParameterBlock
and invokes
+- * {@link JAI#createCollection(String,ParameterBlock,RenderingHints)}.
+- *
+- * @param source The collection to be written.
+- * @param output The output destination.
+- * @param format The format name of the output.
+- * @param useProperties Whether to use image metadata properties as
+- * fallbacks.
+- * @param transcode Whether to transcode metadata before writing.
+- * @param verifyOutput Whether to verify the validity of the output
+- * destination.
+- * @param allowPixelReplacement Whether to allow pixel replacement
+- * in the output image.
+- * @param tileSize The tile size of the output image.
+- * @param streamMetadata Stream metadata to write to the output.
+- * @param imageMetadata Image metadata to write to the output.
+- * @param thumbnails Thumbnails to write to the output.
+- * @param listeners EventListeners to be registered with the ImageWriter.
+- * @param locale The Locale for the ImageWriter to use.
+- * @param writeParam Java Image I/O write parameter instance.
+- * @param writer Java Image I/O writer instance.
+- * @param hints Operation hints.
+- * @return a reference to the operation source.
+- */
+- public static Collection createCollection(Collection source,
+- ImageOutputStream output,
+- String format,
+- Boolean useProperties,
+- Boolean transcode,
+- Boolean verifyOutput,
+- Boolean allowPixelReplacement,
+- Dimension tileSize,
+- IIOMetadata streamMetadata,
+- IIOMetadata[] imageMetadata,
+- BufferedImage[][] thumbnails,
+- EventListener[] listeners,
+- Locale locale,
+- ImageWriteParam writeParam,
+- ImageWriter writer,
+- RenderingHints hints) {
+-
+- ParameterBlock args = new ParameterBlock();
+-
+- args.addSource(source);
+-
+- args.add(output);
+- args.add(format);
+- args.add(useProperties);
+- args.add(transcode);
+- args.add(verifyOutput);
+- args.add(allowPixelReplacement);
+- args.add(tileSize);
+- args.add(streamMetadata);
+- args.add(imageMetadata);
+- args.add(thumbnails);
+- args.add(listeners);
+- args.add(locale);
+- args.add(writeParam);
+- args.add(writer);
+-
+- return JAI.createCollection(OPERATION_NAME, args, hints);
+- }
+-
+- /**
+- * Type-safe convenience method for creating a {@link RenderableOp}
+- * representing the "ImageWrite" operation in renderable mode. The
+- * method packs the source and parameters into a new
+- * ParameterBlock
and invokes
+- * {@link JAI#createRenderable(String,ParameterBlock,RenderingHints)}.
+- *
+- * @param source The renderable source to be written.
+- * @param output The output destination.
+- * @param format The format name of the output.
+- * @param useProperties Whether to use image metadata properties as
+- * fallbacks.
+- * @param transcode Whether to transcode metadata before writing.
+- * @param verifyOutput Whether to verify the validity of the output
+- * destination.
+- * @param allowPixelReplacement Whether to allow pixel replacement
+- * in the output image.
+- * @param tileSize The tile size of the output image.
+- * @param streamMetadata Stream metadata to write to the output.
+- * @param imageMetadata Image metadata to write to the output.
+- * @param thumbnails Thumbnails to write to the output.
+- * @param listeners EventListeners to be registered with the ImageWriter.
+- * @param locale The Locale for the ImageWriter to use.
+- * @param writeParam Java Image I/O write parameter instance.
+- * @param writer Java Image I/O writer instance.
+- * @param hints Operation hints.
+- * @return a reference to the operation source.
+- */
+- public static RenderableOp createRenderable(RenderableImage source,
+- ImageOutputStream output,
+- String format,
+- Boolean useProperties,
+- Boolean transcode,
+- Boolean verifyOutput,
+- Boolean allowPixelReplacement,
+- Dimension tileSize,
+- IIOMetadata streamMetadata,
+- IIOMetadata imageMetadata,
+- BufferedImage[] thumbnails,
+- EventListener[] listeners,
+- Locale locale,
+- ImageWriteParam writeParam,
+- ImageWriter writer,
+- RenderingHints hints) {
+- ParameterBlock args = new ParameterBlock();
+-
+- args.addSource(source);
+-
+- args.add(output);
+- args.add(format);
+- args.add(useProperties);
+- args.add(transcode);
+- args.add(verifyOutput);
+- args.add(allowPixelReplacement);
+- args.add(tileSize);
+- args.add(streamMetadata);
+- args.add(imageMetadata);
+- args.add(thumbnails);
+- args.add(listeners);
+- args.add(locale);
+- args.add(writeParam);
+- args.add(writer);
+-
+- return JAI.createRenderable(OPERATION_NAME, args, hints);
+- }
+-
+- /**
+- * Returns true indicating that the operation should be rendered
+- * immediately during a call to JAI.create[]()
or
+- * JAI.createCollection[NS]()
.
+- *
+- * @see javax.media.jai.OperationDescriptor
+- */
+- public boolean isImmediate() {
+- return true;
+- }
+-
+- /**
+- * Validates the parameters in the supplied ParameterBlock
.
+- *
+- * In addition to the standard validation performed by the +- * corresponding superclass method, this method verifies the following: +- *
TRUE
and Output
+- * is a File
or String
, whether the
+- * corresponding physical file is writable, i.e., exists and may
+- * be overwritten or does not exist and may be created; andTRUE
and Output
+- * is a Socket
, whether it is bound, connected, open,
+- * and the write-half is not shut down; andmodeName
equals
+- * {@link CollectionRegistryMode#MODE_NAME}), the source is not a
+- * {@link CollectionOp}, and the size of the source
+- * {@link Collection} is greater than unity, whether the
+- * {@link ImageWriter} cannot write sequences.msg
and
+- * false
will be returned; otherwise true
will
+- * be returned.
+- *
+- * @param modeName The operation mode.
+- * @param args The source and parameters of the operation.
+- * @param msg A container for any error messages.
+- *
+- * @return Whether the supplied parameters are valid.
+- */
+- protected boolean validateParameters(String modeName,
+- ParameterBlock args,
+- StringBuffer msg) {
+- if (!super.validateParameters(modeName, args, msg)) {
+- return false;
+- }
+-
+- // Get the Output parameter.
+- Object output = args.getObjectParameter(0);
+-
+- // Check the output if so requested by "VerifyOutput".
+- Boolean verifyOutput = (Boolean)args.getObjectParameter(4);
+- if (verifyOutput.booleanValue()){
+- if(output instanceof File || output instanceof String) {
+- // Set file and path variables.
+- File file = null;
+- String path = null;
+- if(output instanceof File) {
+- file = (File)output;
+- path = file.getPath();
+- } else if(output instanceof String) {
+- path = (String)output;
+- file = new File(path);
+- }
+-
+- // Perform non-destructive test that the file
+- // may be created and written.
+- try {
+- if (file.exists()) {
+- if (!file.canWrite()) {
+- // Cannot write to existing file.
+- msg.append(file.getPath() + " " +
+- I18N.getString("ImageWriteDescriptor15"));
+- return false;
+- }
+- } else {
+- if (!file.createNewFile()) {
+- // Cannot create file.
+- msg.append(file.getPath() + " " +
+- I18N.getString("ImageWriteDescriptor16"));
+- return false;
+- }
+- file.delete();
+- }
+- } catch (IOException ioe) {
+- // I/O exception during createNewFile().
+- msg.append(file.getPath() + " " +
+- I18N.getString("ImageWriteDescriptor17") + " " +
+- ioe.getMessage());
+- return false;
+- } catch (SecurityException se) {
+- // Security exception during exists(), canWrite(),
+- // createNewFile(), or delete().
+- msg.append(file.getPath() + " " +
+- I18N.getString("ImageWriteDescriptor18") + " " +
+- se.getMessage());
+- return false;
+- }
+- } else if(output instanceof Socket) {
+- Socket socket = (Socket)output;
+-
+- if(socket.isOutputShutdown()) {
+- msg.append("\"" + socket + "\": " +
+- I18N.getString("ImageWriteDescriptor19"));
+- return false;
+- } else if(socket.isClosed()) {
+- msg.append("\"" + socket + "\": " +
+- I18N.getString("ImageWriteDescriptor20"));
+- return false;
+- } else if(!socket.isBound()) {
+- msg.append("\"" + socket + "\": " +
+- I18N.getString("ImageWriteDescriptor21"));
+- return false;
+- } else if(!socket.isConnected()) {
+- msg.append("\"" + socket + "\": " +
+- I18N.getString("ImageWriteDescriptor22"));
+- return false;
+- }
+- }
+- }
+-
+- // Get the Format parameter.
+- String format = (String)args.getObjectParameter(1);
+-
+- // Get the ImageWriter parameter.
+- ImageWriter writer = (ImageWriter)args.getObjectParameter(13);
+-
+- if(format == null) {
+- // Attempt to get the format from the ImageWriter provider.
+- if(writer != null) {
+-
+- // Get the SPI.
+- ImageWriterSpi spi = writer.getOriginatingProvider();
+-
+- // Set from the SPI.
+- if(spi != null) {
+- format = spi.getFormatNames()[0];
+- }
+- }
+-
+- // Attempt to deduce the format from the file suffix.
+- if(format == null &&
+- (output instanceof File || output instanceof String)) {
+-
+- // Set the file name string.
+- String name = output instanceof File ?
+- ((File)output).getName() : (String)output;
+-
+- // Extract the suffix.
+- String suffix = name.substring(name.lastIndexOf(".") + 1);
+-
+- // Get the writers of that suffix.
+- Iterator writers = ImageIO.getImageWritersBySuffix(suffix);
+-
+- if(writers != null) {
+- // Get the first writer.
+- writer = (ImageWriter)writers.next();
+-
+- if(writer != null) {
+- // Get the SPI.
+- ImageWriterSpi spi = writer.getOriginatingProvider();
+-
+- // Set from the SPI.
+- if(spi != null) {
+- format = spi.getFormatNames()[0];
+- }
+- }
+- }
+- }
+-
+- // Default to the most versatile core Java Image I/O writer.
+- if(format == null) {
+- format = "PNG";
+- }
+-
+- // Replace the format setting.
+- if(format != null) {
+- args.set(format, 1);
+- }
+- }
+-
+- // Check the tile size parameter if present.
+- Dimension tileSize = (Dimension)args.getObjectParameter(6);
+- if(tileSize != null && (tileSize.width <= 0 || tileSize.height <= 0)) {
+- msg.append(I18N.getString("ImageWriteDescriptor23"));
+- return false;
+- }
+-
+- // For collection mode, verify that the source collection contains
+- // at least one RenderedImage and that the writer can handle sequences
+- // if there is more than one RenderedImage in the source collection.
+- if(modeName.equalsIgnoreCase(CollectionRegistryMode.MODE_NAME)) {
+- // Get the source collection.
+- Collection source = (Collection)args.getSource(0);
+-
+- // If the source collection is a CollectionOp do not perform this
+- // check as invoking source.size() will render the node.
+- if(!(source instanceof CollectionOp)) {
+-
+- // Determine the number of RenderedImages in the Collection.
+- int numRenderedImages = 0;
+- Iterator iter = source.iterator();
+- while(iter.hasNext()) {
+- if(iter.next() instanceof RenderedImage) {
+- numRenderedImages++;
+- }
+- }
+-
+- if(numRenderedImages == 0) {
+- msg.append(I18N.getString("ImageWriteDescriptor24"));
+- return false;
+- } else if(numRenderedImages > 1) {
+- // Get the writer parameter.
+- writer = (ImageWriter)args.getObjectParameter(13);
+-
+- // If the parameter writer is null, get one based on the
+- // format.
+- if(writer == null && format != null) {
+- // Get the writers of that format.
+- Iterator writers =
+- ImageIO.getImageWritersByFormatName(format);
+-
+- if(writers != null) {
+- // Get the first writer.
+- writer = (ImageWriter)writers.next();
+- }
+- }
+-
+- if(writer != null) {
+- // Check that the writer can write sequences.
+- if(!writer.canWriteSequence()) {
+- msg.append(I18N.getString("ImageWriteDescriptor25"));
+- return false;
+- }
+- }
+- }
+- }
+- }
+-
+- return true;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/operator/package.html zzx2/src/share/classes/com/sun/media/jai/operator/package.html
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/operator/package.html 2005-02-11 00:01:57.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/jai/operator/package.html 1969-12-31 19:00:00.000000000 -0500
+@@ -1,52 +0,0 @@
+-
+-
+-
+-Provides JAI operations which read and write images using the Java Image
+-I/O Framework. These operations are plug-ins which are automatically loaded
+-using the javax.media.jai.OperationRegistrySpi
mechanism of JAI.
+-
+-@since 1.0
+-
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/operator/PrintProps.java zzx2/src/share/classes/com/sun/media/jai/operator/PrintProps.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/operator/PrintProps.java 2005-02-11 00:01:57.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/jai/operator/PrintProps.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,85 +0,0 @@
+-/*
+- * $RCSfile: PrintProps.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:57 $
+- * $State: Exp $
+- */
+-package com.sun.media.jai.operator;
+-
+-import java.util.Collection;
+-import java.util.Iterator;
+-import javax.media.jai.PropertySource;
+-
+-final class PrintProps {
+- static final void print(PropertySource ps) {
+- String[] propNames = ps.getPropertyNames();
+- if(propNames != null) {
+- System.out.println("\nPROPERTIES OF "+
+- ps.getClass().getName()+"@"+
+- ps.hashCode()+":\n");
+- for(int j = 0; j < propNames.length; j++) {
+- Object propVal = ps.getProperty(propNames[j]);
+- if(propVal == null) {
+- System.out.println(propNames[j]+" is NULL.");
+- } else if(propVal == java.awt.Image.UndefinedProperty) {
+- System.out.println(propNames[j]+" is UNDEFINED.");
+- } else {
+- System.out.println(propNames[j]+" = "+
+- propVal.getClass().getName()+"@"+
+- propVal.hashCode());
+- }
+- }
+- } else {
+- System.out.println("\n"+ps+" has no properties.");
+- }
+- System.out.println("\n");
+-
+- if(ps instanceof Collection) {
+- Iterator iter = ((Collection)ps).iterator();
+- while(iter.hasNext()) {
+- Object nextElement = iter.next();
+- if(nextElement instanceof PropertySource) {
+- print((PropertySource)nextElement);
+- }
+- }
+- }
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/operator/properties zzx2/src/share/classes/com/sun/media/jai/operator/properties
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/jai/operator/properties 2005-02-11 00:01:57.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/jai/operator/properties 1969-12-31 19:00:00.000000000 -0500
+@@ -1,60 +0,0 @@
+-#
+-# $RCSfile: properties,v $
+-#
+-# Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
+-#
+-# Use is subject to license terms.
+-#
+-# $Revision: 1.1 $
+-# $Date: 2005/02/11 05:01:57 $
+-# $State: Exp $
+-#
+-# Internationalization file for com.sun.media.jai.operator
+-
+-DescriptorVersion=1.0
+-
+-ImageReadDescriptor0=Reads an image using the Java Image I/O Framework.
+-ImageReadDescriptor1=The input source.
+-ImageReadDescriptor2=The index or indices of the image(s) to read.
+-ImageReadDescriptor3=Whether metadata should be read if available.
+-ImageReadDescriptor4=Whether thumbnails should be read if available.
+-ImageReadDescriptor5=Whether to verify the validity of the input source.
+-ImageReadDescriptor6=EventListeners to be registered with the ImageReader.
+-ImageReadDescriptor7=The Locale for the ImageReader to use.
+-ImageReadDescriptor8=Java Image I/O read parameter instance.
+-ImageReadDescriptor9=Java Image I/O reader instance.
+-ImageReadDescriptor10=Image index parameter must be non-negative.
+-ImageReadDescriptor11=does not exist.
+-ImageReadDescriptor12=is not readable.
+-ImageReadDescriptor13=has its read-half shut down.
+-ImageReadDescriptor14=is closed.
+-ImageReadDescriptor15=is not bound to an address.
+-ImageReadDescriptor16=is not connected.
+-
+-ImageWriteDescriptor0=Writes an image using the Java Image I/O Framework.
+-ImageWriteDescriptor1=The output destination.
+-ImageWriteDescriptor2=The format name of the output.
+-ImageWriteDescriptor3=Whether to use image metadata properties as fallbacks.
+-ImageWriteDescriptor4=Whether to transcode metadata before writing.
+-ImageWriteDescriptor5=Whether to verify the validity of the output destination.
+-ImageWriteDescriptor6=Whether to allow pixel replacement in the output image.
+-ImageWriteDescriptor7=The tile size of the output image.
+-ImageWriteDescriptor8=Stream metadata to write to the output.
+-ImageWriteDescriptor9=Image metadata to write to the output.
+-ImageWriteDescriptor10=Thumbnails to write to the output.
+-ImageWriteDescriptor11=EventListeners to be registered with the ImageWriter.
+-ImageWriteDescriptor12=The Locale for the ImageWriter to use.
+-ImageWriteDescriptor13=Java Image I/O write parameter instance.
+-ImageWriteDescriptor14=Java Image I/O writer instance.
+-ImageWriteDescriptor15=exists but is not writable.
+-ImageWriteDescriptor16=does not exist and cannot be created.
+-ImageWriteDescriptor17=encountered IOException during createNewFile:
+-ImageWriteDescriptor18=access denied by security manager:
+-ImageWriteDescriptor19=has its write-half shut down.
+-ImageWriteDescriptor20=is closed.
+-ImageWriteDescriptor21=is not bound to an address.
+-ImageWriteDescriptor22=is not connected.
+-ImageWriteDescriptor23=Non-positive tile dimension specified.
+-ImageWriteDescriptor24=No RenderedImages in the source Collection.
+-ImageWriteDescriptor25=There is more than one RenderedImage in the source \
+-Collection and the supplied ImageWriter cannot write sequences.
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/services/javax.imageio.spi.ImageReaderSpi zzx2/src/share/services/javax.imageio.spi.ImageReaderSpi
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/services/javax.media.jai.OperationRegistrySpi 2005-02-11 00:02:44.000000000 -0500
++++ zzx2/src/share/services/javax.media.jai.OperationRegistrySpi 1969-12-31 19:00:00.000000000 -0500
+@@ -1,47 +0,0 @@
+-#
+-# $RCSfile: javax.media.jai.OperationRegistrySpi,v $
+-#
+-#
+-# Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+-#
+-# Redistribution and use in source and binary forms, with or without
+-# modification, are permitted provided that the following conditions
+-# are met:
+-#
+-# - Redistribution of source code must retain the above copyright
+-# notice, this list of conditions and the following disclaimer.
+-#
+-# - Redistribution in binary form must reproduce the above copyright
+-# notice, this list of conditions and the following disclaimer in
+-# the documentation and/or other materials provided with the
+-# distribution.
+-#
+-# Neither the name of Sun Microsystems, Inc. or the names of
+-# contributors may be used to endorse or promote products derived
+-# from this software without specific prior written permission.
+-#
+-# This software is provided "AS IS," without a warranty of any
+-# kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+-# WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+-# FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+-# EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+-# NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+-# USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+-# DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+-# ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+-# CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+-# REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+-# INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+-# POSSIBILITY OF SUCH DAMAGES.
+-#
+-# You acknowledge that this software is not designed or intended for
+-# use in the design, construction, operation or maintenance of any
+-# nuclear facility.
+-#
+-# $Revision: 1.1 $
+-# $Date: 2005/02/11 05:02:44 $
+-# $State: Exp $
+-#
+-# --- JAI-Image I/O operations registration ---
+-#
+-com.sun.media.jai.imageioimpl.ImageReadWriteSpi
diff --git a/SOURCES/jai-imageio-core-remove-jpeg2000-plugin.patch b/SOURCES/jai-imageio-core-remove-jpeg2000-plugin.patch
new file mode 100644
index 0000000..b0ee40c
--- /dev/null
+++ b/SOURCES/jai-imageio-core-remove-jpeg2000-plugin.patch
@@ -0,0 +1,15731 @@
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/J2KImageReadParam.java zzx2/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/J2KImageReadParam.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/J2KImageReadParam.java 2006-09-29 15:25:32.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/J2KImageReadParam.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,147 +0,0 @@
+-/*
+- * $RCSfile: J2KImageReadParam.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.3 $
+- * $Date: 2006/09/29 19:25:32 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageio.plugins.jpeg2000;
+-
+-import javax.imageio.ImageReadParam;
+-
+-/**
+- * A subclass of ImageReadParam
for reading images in
+- * the JPEG 2000 format.
+- *
+- * The decoding parameters for JPEG 2000 are listed below: +- * +- *
Parameter Name | Description |
---|---|
decodingRate | +- *Specifies the decoding rate in bits per pixel (bpp) where the
+- * number of pixels is related to the image's original size (Note:
+- * this parameter is not affected by resolution ).
+- * The default is Double.MAX_VALUE .
+- * It means decoding with the encoding rate.
+- * |
+- *
resolution | +- *Specifies the resolution level wanted for the decoded image
+- * (0 means the lowest available resolution, the resolution
+- * level gives an image with the original dimension). If the given index
+- * is greater than the number of available resolution levels of the
+- * compressed image, the decoded image has the lowest available
+- * resolution (among all tile-components). This parameter affects only
+- * the inverse wavelet transform and not the number of bytes read by the
+- * codestream parser, which depends only on decodingRate .
+- * The default value, -1, means to use the resolution level at encoding.
+- * |
+- *
resolution
).
+- */
+- private double decodingRate = Double.MAX_VALUE;
+-
+- /** Specifies the resolution level wanted for the decoded image
+- * (0 means the lowest available resolution, the resolution
+- * level gives an image with the original dimension). If the given index
+- * is greater than the number of available resolution levels of the
+- * compressed image, the decoded image has the lowest available
+- * resolution (among all tile-components). This parameter
+- * affects only the inverse wavelet transform but not the number
+- * of bytes read by the codestream parser, which
+- * depends only on decodingRate
.
+- */
+- private int resolution = -1;
+-
+- /** Constructs a default instance of J2KImageReadParam
. */
+- public J2KImageReadParam() {
+- super();
+- }
+-
+- /**
+- * Sets decodingRate
.
+- *
+- * @param rate the decoding rate in bits per pixel.
+- * @see #getDecodingRate()
+- */
+- public void setDecodingRate(double rate) {
+- this.decodingRate = rate;
+- }
+-
+- /**
+- * Gets decodingRate
.
+- *
+- * @return the decoding rate in bits per pixel.
+- * @see #setDecodingRate(double)
+- */
+- public double getDecodingRate() {
+- return decodingRate;
+- }
+-
+- /**
+- * Sets resolution
.
+- *
+- * @param resolution the resolution level with 0 being
+- * the lowest available.
+- * @see #getResolution()
+- */
+- public void setResolution(int resolution) {
+- this.resolution = Math.max(resolution, -1);
+- }
+-
+- /**
+- * Gets resolution
.
+- *
+- * @return the resolution level with 0 being
+- * the lowest available.
+- * @see #setResolution(int)
+- */
+- public int getResolution() {
+- return resolution;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/J2KImageWriteParam.java zzx2/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/J2KImageWriteParam.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/J2KImageWriteParam.java 2006-09-20 19:23:30.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/J2KImageWriteParam.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,462 +0,0 @@
+-/*
+- * $RCSfile: J2KImageWriteParam.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.2 $
+- * $Date: 2006/09/20 23:23:30 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageio.plugins.jpeg2000;
+-
+-import java.awt.Rectangle;
+-import java.awt.image.Raster;
+-import java.awt.image.RenderedImage;
+-import java.util.Collections;
+-import java.util.Locale;
+-import java.util.Iterator;
+-import javax.imageio.ImageWriteParam;
+-
+-/**
+- * A subclass of ImageWriteParam
for writing images in
+- * the JPEG 2000 format.
+- *
+- * JPEG 2000 plugin supports to losslessly or lossy compress gray-scale, +- * RGB, and RGBA images with byte, unsigned short or short data type. It also +- * supports losslessly compress bilevel, and 8-bit color indexed images. The +- * result data is in the of JP2 format -- JPEG 2000 Part 1 or baseline format. +- * +- *
The parameters for encoding JPEG 2000 are listed in the following table: +- * +- *
Parameter Name | Description |
---|---|
numDecompositionLevels | +- * The number of decomposition levels to generate. This value must
+- * be in the range
+- * 0 ≤ numDecompositionLevels ≤ 32
+- * . The default value is 5 . Note that the number
+- * of resolution levels is
+- * numDecompositionLevels + 1 .
+- * The number of decomposition levels is constant across
+- * all components and all tiles.
+- * |
+- *
encodingRate | +- * The bitrate in bits-per-pixel for encoding. Should be set when
+- * lossy compression scheme is used. With the default value
+- * Double.MAX_VALUE , a lossless compression will be done.
+- * |
+- *
lossless | +- * Indicates using the lossless scheme or not. It is equivalent to
+- * use reversible quantization and 5x3 integer wavelet filters. The
+- * default is true .
+- * |
+- *
componentTransformation | +- *Specifies to utilize the component transformation on some tiles. +- * If the wavelet transform is reversible (w5x3 filter), the Reversible +- * Component Transformation (RCT) is applied. If not reversible +- * (w9x7 filter), the Irreversible Component Transformation (ICT) is used. +- * | +- *
filters | +- *Specifies which wavelet filters to use for the specified +- * tile-components. JPEG 2000 part I only supports w5x3 and w9x7 filters. +- * | +- *
codeBlockSize | +- *Specifies the maximum code-block size to use for tile-component. +- * The maximum width and height is 1024, however the block size +- * (i.e. width x height) must not exceed 4096. The minimum width and +- * height is 4. The default values are (64, 64). +- * | +- *
progressionType | +- * Specifies which type of progression should be used when generating
+- * the codestream.
+- * The format is ont of the progression types defined below: +- * +- * res : Resolution-Layer-Component-Position +- * layer: Layer-Resolution-Component-Position +- * res-pos: Resolution-Position-Component-Layer +- * pos-comp: Position-Component-Resolution-Layer +- * comp-pos: Component-Position-Resolution-Layer +- * |
+- *
SOP | +- *Specifies whether start of packet (SOP) markers should be used. +- * true enables, false disables it. The default value is false. +- * | +- *
EPH | +- *Specifies whether end of packet header (EPH) markers should be used. +- * true enables, false disables it. The default value is false. +- * | +- *
writeCodeStreamOnly | +- *Specifies whether write only the jpeg2000 code stream, i.e, no any +- * box is written. The default value is false. +- * | +- *
Double.MAX_VALUE
.
+- */
+- private double encodingRate = Double.MAX_VALUE;
+-
+- /**
+- * Indicates using the lossless scheme or not. It is equivalent to
+- * use reversible quantization and 5x3 integer wavelet filters.
+- */
+- private boolean lossless = true;
+-
+- /** Specifies to utilize the component transformation with some tiles.
+- * If the wavelet transform is reversible (w5x3 filter), the
+- * Reversible Component Transformation (RCT) is applied. If not reversible
+- * (w9x7 filter), the Irreversible Component Transformation (ICT)
+- * is used.
+- */
+- private boolean componentTransformation = true;
+-
+- /** Specifies which filters to use for the specified tile-components.
+- * JPEG 2000 part I only supports w5x3 and w9x7 filters.
+- */
+- private String filter = FILTER_53;
+-
+- /** Specifies the maximum code-block size to use for tile-component.
+- * The maximum width and height is 1024, however the image area
+- * (i.e. width x height) must not exceed 4096. The minimum
+- * width and height is 4. Default: 64 64.
+- */
+- private int[] codeBlockSize = new int[]{64, 64};
+-
+- /** See above.
+- */
+- private String progressionType = "layer";
+-
+- /** Specifies whether end of packet header (EPH) markers should be used.
+- * true enables, false disables it. Default: false.
+- */
+- private boolean EPH = false;
+-
+- /** Specifies whether start of packet (SOP) markers should be used.
+- * true enables, false disables it. Default: false.
+- */
+- private boolean SOP = false;
+-
+- /** Specifies whether write only the jpeg2000 code stream, i.e, no any
+- * box is written. The default value is false.
+- */
+- private boolean writeCodeStreamOnly = false;
+-
+- /**
+- * Constructor which sets the Locale
.
+- *
+- * @param locale a Locale
to be used to localize
+- * compression type names and quality descriptions, or
+- * null
.
+- */
+- public J2KImageWriteParam(Locale locale) {
+- super(locale);
+- setDefaults();
+- }
+-
+- /**
+- * Constructs a J2KImageWriteParam
object with default
+- * values for all parameters.
+- */
+- public J2KImageWriteParam() {
+- super();
+- setDefaults();
+- }
+-
+- /** Set source */
+- private void setDefaults() {
+- // override the params in the super class
+- canOffsetTiles = true;
+- canWriteTiles = true;
+- canOffsetTiles = true;
+- compressionTypes = new String[] {"JPEG2000"};
+- canWriteCompressed = true;
+- tilingMode = MODE_EXPLICIT;
+- }
+-
+- /**
+- * Sets numDecompositionLevels
.
+- *
+- * @param numDecompositionLevels the number of decomposition levels.
+- * @throws IllegalArgumentException if numDecompositionLevels
+- * is negative or greater than 32.
+- * @see #getNumDecompositionLevels
+- */
+- public void setNumDecompositionLevels(int numDecompositionLevels) {
+- if(numDecompositionLevels < 0 || numDecompositionLevels > 32) {
+- throw new IllegalArgumentException
+- ("numDecompositionLevels < 0 || numDecompositionLevels > 32");
+- }
+- this.numDecompositionLevels = numDecompositionLevels;
+- }
+-
+- /**
+- * Gets numDecompositionLevels
.
+- *
+- * @return the number of decomposition levels.
+- * @see #setNumDecompositionLevels
+- */
+- public int getNumDecompositionLevels() {
+- return numDecompositionLevels;
+- }
+-
+- /**
+- * Sets encodingRate
.
+- *
+- * @param rate the encoding rate in bits-per-pixel.
+- * @see #getEncodingRate()
+- */
+- public void setEncodingRate(double rate) {
+- this.encodingRate = rate;
+- if (encodingRate != Double.MAX_VALUE) {
+- lossless = false;
+- filter = FILTER_97;
+- } else {
+- lossless = true;
+- filter = FILTER_53;
+- }
+- }
+-
+- /**
+- * Gets encodingRate
.
+- *
+- * @return the encoding rate in bits-per-pixel.
+- * @see #setEncodingRate(double)
+- */
+- public double getEncodingRate() {
+- return encodingRate;
+- }
+-
+- /**
+- * Sets lossless
.
+- *
+- * @param lossless whether the compression scheme is lossless.
+- * @see #getLossless()
+- */
+- public void setLossless(boolean lossless) {
+- this.lossless = lossless;
+- }
+-
+- /**
+- * Gets lossless
.
+- *
+- * @return whether the compression scheme is lossless.
+- * @see #setLossless(boolean)
+- */
+- public boolean getLossless() {
+- return lossless;
+- }
+-
+- /**
+- * Sets filter
.
+- *
+- * @param value which wavelet filters to use for the specified
+- * tile-components.
+- * @see #getFilter()
+- */
+- public void setFilter(String value) {
+- filter = value;
+- }
+-
+- /**
+- * Gets filters
.
+- *
+- * @return which wavelet filters to use for the specified
+- * tile-components.
+- * @see #setFilter(String)
+- */
+- public String getFilter() {
+- return filter;
+- }
+-
+- /**
+- * Sets componentTransformation
.
+- *
+- * @param value whether to utilize the component transformation.
+- * @see #getComponentTransformation()
+- */
+- public void setComponentTransformation(boolean value) {
+- componentTransformation = value;
+- }
+-
+- /**
+- * Gets componentTransformation
.
+- *
+- * @return whether to utilize the component transformation.
+- * @see #setComponentTransformation(boolean)
+- */
+- public boolean getComponentTransformation() {
+- return componentTransformation;
+- }
+-
+- /**
+- * Sets codeBlockSize
.
+- *
+- * @param value the maximum code-block size to use per tile-component.
+- * @see #getCodeBlockSize()
+- */
+- public void setCodeBlockSize(int[] value) {
+- codeBlockSize = value;
+- }
+-
+- /**
+- * Gets codeBlockSize
.
+- *
+- * @return the maximum code-block size to use per tile-component.
+- * @see #setCodeBlockSize(int[])
+- */
+- public int[] getCodeBlockSize() {
+- return codeBlockSize;
+- }
+-
+- /**
+- * Sets SOP
.
+- *
+- * @param value whether start of packet (SOP) markers should be used.
+- * @see #getSOP()
+- */
+- public void setSOP(boolean value) {
+- SOP = value;
+- }
+-
+- /**
+- * Gets SOP
.
+- *
+- * @return whether start of packet (SOP) markers should be used.
+- * @see #setSOP(boolean)
+- */
+- public boolean getSOP() {
+- return SOP;
+- }
+-
+- /**
+- * Sets EPH
.
+- *
+- * @param value whether end of packet header (EPH) markers should be used.
+- * @see #getEPH()
+- */
+- public void setEPH(boolean value) {
+- EPH = value;
+- }
+-
+- /**
+- * Gets EPH
.
+- *
+- * @return whether end of packet header (EPH) markers should be used.
+- * @see #setEPH(boolean)
+- */
+- public boolean getEPH() {
+- return EPH;
+- }
+-
+- /**
+- * Sets progressionType
.
+- *
+- * @param value which type of progression should be used when generating
+- * the codestream.
+- * @see #getProgressionType()
+- */
+- public void setProgressionType(String value) {
+- progressionType = value;
+- }
+-
+- /**
+- * Gets progressionType
.
+- *
+- * @return which type of progression should be used when generating
+- * the codestream.
+- * @see #setProgressionType(String)
+- */
+- public String getProgressionType() {
+- return progressionType;
+- }
+-
+- /** Sets writeCodeStreamOnly
.
+- *
+- * @param value Whether the jpeg2000 code stream only or the jp2 format
+- * will be written into the output.
+- * @see #getWriteCodeStreamOnly()
+- */
+- public void setWriteCodeStreamOnly(boolean value) {
+- writeCodeStreamOnly = value;
+- }
+-
+- /** Gets writeCodeStreamOnly
.
+- *
+- * @return whether the jpeg2000 code stream only or the jp2 format
+- * will be written into the output.
+- * @see #setWriteCodeStreamOnly(boolean)
+- */
+- public boolean getWriteCodeStreamOnly() {
+- return writeCodeStreamOnly;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/package.html zzx2/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/package.html
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/package.html 2005-02-11 00:01:16.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/package.html 1969-12-31 19:00:00.000000000 -0500
+@@ -1,768 +0,0 @@
+-
+-
+-Package containing the public classes used by the Sun JPEG 2000 plug-in for
+-the Image I/O Framework.
+-
+-+-
+-<!DOCTYPE "com_sun_media_imageio_plugins_jpeg2000_image_1.0" [ +- +- <!ELEMENT com_sun_media_imageio_plugins_jpeg2000_image_1.0 (JPEG2000SignatureBox, +- JPEG2000FileTypeBox, +- OtherBoxes) > +- +- <!-- JPEG2000HeaderSuperBox should be before JPEG2000CodeStreamBox; This +- is the only constraint for the sequence of these boxes --> +- <!ELEMENT OtherBoxes (JPEG2000HeaderSuperBox, +- JPEG2000CodeStreamBox, +- JPEG2000IntellectualPropertyRightsBox*, +- JPEG2000XMLBox*, +- JPEG2000UUIDBox*, +- JPEG2000UUIDInfoBox*)> +- +- <!-- JPEG 2000 Signature box --> +- <!ELEMENT JPEG2000SignatureBox EMPTY> +- <!ATTLIST JPEG2000SignatureBox +- Length CDATA #FIXED "12" +- Type CDATA #FIXED "jP " +- Signature CDATA #FIXED "0x0D0A870A"> +- +- <!-- JPEG 2000 File type box --> +- <!ELEMENT JPEG2000FileTypeBox (Brand, MinorVersion, CompatibilityList) > +- <!ELEMENT Brand (#PCDATA)> +- <!ELEMENT MinorVersion (#PCDATA)> +- <!ELEMENT CompatibilityList (#PCDATA)> +- <!ATTLIST JPEG2000FileTypeBox +- Length CDATA #FIXED "12" +- Type CDATA #FIXED "jP " +- ExtraLength CDATA #IMPLIED> +- +- <!-- JPEG 2000 header super box--> +- <!ELEMENT JPEG2000HeaderSuperBox (JPEG2000HeaderBox, OptionalBoxes) > +- <!ELEMENT OptionalBoxes (JPEG2000BitsPerComponentBox, +- JPEG2000ColorSpecificationBox, +- JPEG2000PaletteBox?, +- JPEG2000ComponentMappingBox?, +- JPEG2000ChannelDefinitionBox?, +- JPEG2000ResolutionBox?)> +- <!ATTLIST JPEG2000HeaderSuperBox +- Length CDATA #REQUIRED +- Type CDATA #FIXED "jp2h" +- ExtraLength CDATA #IMPLIED> +- +- <!-- JPEG 2000 image header box --> +- <!ELEMENT JPEG2000HeaderBox (Width, Height, NumComponents, BitDepth, +- CompressionType, UnknownColorspace, +- IntellectualProperty)> +- <!ELEMENT Width (#PCDATA)> +- <!ELEMENT Height (#PCDATA)> +- <!ELEMENT NumComponents (#PCDATA)> +- <!ELEMENT BitDepth (#PCDATA)> +- <!ELEMENT CompressionType (#PCDATA)> +- <!ELEMENT UnknownColorspace (#PCDATA)> +- <!ELEMENT IntellectualProperty (#PCDATA)> +- <!ATTLIST JPEG2000HeaderBox +- Length CDATA #FIXED "22" +- Type CDATA #FIXED "ihdr"> +- +- <!-- JPEG 2000 bits per component box --> +- <!ELEMENT JPEG2000BitsPerComponentBox (BitDepth)> +- <!ATTLIST JPEG2000BitsPerComponentBox +- Length CDATA #REQUIRED +- Type CDATA #FIXED "bpcc" +- ExtraLength CDATA #IMPLIED> +- +- <!-- JPEG 2000 color specification box --> +- <!ELEMENT JPEG2000ColorSpecificationBox (Method, Precedence, +- ApproximationAccuracy, +- EnumeratedColorSpace, +- ICCProfile)> +- <!ELEMENT Method (#PCDATA)> +- <!ELEMENT Precedence (#PCDATA)> +- <!ELEMENT ApproximationAccuracy (#PCDATA)> +- <!ELEMENT EnumeratedColorSpace (#PCDATA)> +- <!ELEMENT ICCProfile (#PCDATA)> +- <!ATTLIST JPEG2000ColorSpecificationBox +- Length CDATA #REQUIRED +- Type CDATA #FIXED "colr" +- ExtraLength CDATA #IMPLIED> +- +- <!-- JPEG 2000 palette box --> +- <!ELEMENT JPEG2000PaletteBox (NumberEntries, NumberColors, +- BitDepth, +- LUT)> +- <!ELEMENT NumberEntries (#PCDATA)> +- <!ELEMENT NumberColors (#PCDATA)> +- <!ELEMENT LUT (LUTRow*)> +- <!ELEMENT LUTRow (#PCDATA)> +- <!ATTLIST JPEG2000PaletteBox +- Length CDATA #REQUIRED +- Type CDATA #FIXED "pclr" +- ExtraLength CDATA #IMPLIED> +- +- <!-- JPEG 2000 component mapping box--> +- <!ELEMENT JPEG2000ComponentMappingBox (Component, ComponentType, +- ComponentAssociation)> +- <!ELEMENT Component (#PCDATA)> +- <!ELEMENT ComponentType (#PCDATA)> +- <!ELEMENT ComponentAssociation (#PCDATA)> +- <!ATTLIST JPEG2000ComponentMappingBox +- Length CDATA #REQUIRED +- Type CDATA #FIXED "cmap" +- ExtraLength CDATA #IMPLIED> +- +- <!-- JPEG 2000 channel definition box--> +- <!ELEMENT JPEG2000ChannelDefinitionBox (NumberOfDefinition, Definitions)> +- <!ELEMENT NumberOfDefinition (#PCDATA)> +- <!ELEMENT Definitions (ChannelNumber, ChannelType)*> +- <!ELEMENT ChannelNumber (#PCDATA)> +- <!ELEMENT ChannelType (#PCDATA)> +- <!ELEMENT ChannelAssociation (#PCDATA)> +- <!ATTLIST JPEG2000ChannelDefinitionBox +- Length CDATA #REQUIRED +- Type CDATA #FIXED "cdef" +- ExtraLength CDATA #IMPLIED> +- +- <!-- JPEG 2000 resolution box--> +- <!ELEMENT JPEG2000ResolutionBox (JPEG2000CaptureResolutionBox, +- JPEG2000DefaultDisplayResolutionBox)> +- <!ATTLIST JPEG2000ResolutionBox +- Length CDATA #REQUIRED +- Type CDATA #FIXED "res " +- ExtraLength CDATA #IMPLIED> +- +- <!-- JPEG 2000 capture resolution box--> +- <!ELEMENT JPEG2000CaptureResolutionBox (VerticalResolutionNumerator, +- VerticalResolutionDenominator, +- HorizontalResolutionNumerator, +- HorizontalResolutionDenominator, +- VerticalResolutionExponent, +- HorizontalResolutionExponent)> +- <!ELEMENT VerticalResolutionNumerator (#PCDATA)> +- <!ELEMENT VerticalResolutionDenominator (#PCDATA)> +- <!ELEMENT HorizontalResolutionNumerator (#PCDATA)> +- <!ELEMENT HorizontalResolutionDenominator (#PCDATA)> +- <!ELEMENT VerticalResolutionExponent (#PCDATA)> +- <!ELEMENT HorizontalResolutionExponent (#PCDATA)> +- <!ATTLIST JPEG2000CaptureResolutionBox +- Length CDATA #REQUIRED +- Type CDATA #FIXED "resc" +- ExtraLength CDATA #IMPLIED> +- +- <!-- JPEG 2000 default display resolution box--> +- <!ELEMENT JPEG2000DefaultDisplayResolutionBox (VerticalResolutionNumerator, +- VerticalResolutionDenominator, +- HorizontalResolutionNumerator, +- HorizontalResolutionDenominator, +- VerticalResolutionExponent, +- HorizontalResolutionExponent)> +- <!ATTLIST JPEG2000DefaultDisplayResolutionBox +- Length CDATA #REQUIRED +- Type CDATA #FIXED "resd" +- ExtraLength CDATA #IMPLIED> +- +- <!-- JPEG 2000 code stream box--> +- <!ELEMENT JPEG2000CodeStreamBox (CodeStream)> +- <!ELEMENT CodeStream (#PCDATA)> +- <!ATTLIST JPEG2000CodeStreamBox +- Length CDATA #REQUIRED +- Type CDATA #FIXED "jp2c" +- ExtraLength CDATA #IMPLIED> +- +- <!-- JPEG 2000 intellectual property rights box--> +- <!ELEMENT JPEG2000IntellectualPropertyRightsBox (Content)> +- <!ELEMENT Content (#PCDATA)> +- <!ATTLIST JPEG2000IntellectualPropertyRightsBox +- Length CDATA #REQUIRED +- Type CDATA #FIXED "jp2i" +- ExtraLength CDATA #IMPLIED> +- +- <!-- JPEG 2000 XML box--> +- <!ELEMENT JPEG2000XMLBox (Content)> +- <!ATTLIST JPEG2000XMLBox +- Length CDATA #REQUIRED +- Type CDATA #FIXED "xml " +- ExtraLength CDATA #IMPLIED> +- +- <!-- JPEG 2000 UUID box--> +- <!ELEMENT JPEG2000UUIDBox (UUID, Data)> +- <!ELEMENT UUID (#PCDATA)> +- <!ELEMENT Data (#PCDATA)> +- <!ATTLIST JPEG2000UUIDBox +- Length CDATA #REQUIRED +- Type CDATA #FIXED "uuid" +- ExtraLength CDATA #IMPLIED> +- +- <!-- JPEG 2000 UUID info box--> +- <!ELEMENT JPEG2000UUIDInfoBox (JPEG2000UUIDListBox, JPEG2000DataEntryURLBox)> +- <!ATTLIST JPEG2000UUIDInfoBox +- Length CDATA #REQUIRED +- Type CDATA #FIXED "uinf" +- ExtraLength CDATA #IMPLIED> +- +- <!-- JPEG 2000 UUID list box--> +- <!ELEMENT JPEG2000UUIDListBox (NumberUUID, UUID*)> +- <!ELEMENT NumberUUID (#PCDATA)> +- <!ATTLIST JPEG2000UUIDListBox +- Length CDATA #REQUIRED +- Type CDATA #FIXED "ulst" +- ExtraLength CDATA #IMPLIED> +- +- <!-- JPEG 2000 Data Entry URL box--> +- <!ELEMENT JPEG2000DataEntryURLBox (Version, Flags, Location)> +- <!ELEMENT Version (#PCDATA)> +- <!ELEMENT Flags (#PCDATA)> +- <!ELEMENT URL (#PCDATA)> +- <!ATTLIST JPEG2000DataEntryURLBox +- Length CDATA #REQUIRED +- Type CDATA #FIXED "url " +- ExtraLength CDATA #IMPLIED> ] +-+- +- +-
+- +-<?xml version="1.0" ?> +-<!--Schema for JPEG 2000 image format --> +- +-<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" +- xmlns="http://com.sun.media.imageio" +- targetNamespace="http://com.sun.media.imageio"> +- +- <!-- JPEG 2000 Image File--> +- <xsd:element name="com_sun_media_imageio_plugins_jpeg2000_image_1.0"> +- <xsd:complexType> +- <xsd:sequence> +- <xsd:element ref="JPEG2000SignatureBox" /> +- <xsd:element ref="JPEG2000FileTypeBox" /> +- <!-- JPEG2000HeaderSuperBox should be before JPEG2000CodeStreamBox; +- This is the only constraint for the sequence of these boxes --> +- <xsd:element name="OtherBoxes"> +- <xsd:complexType> +- <xsd:all> +- <xsd:element ref="JPEG2000HeaderSuperBox" /> +- <xsd:element ref="JPEG2000CodeStreamBox" /> +- +- <xsd:element ref="JPEG2000IntellectualPropertyRightsBox" minOccurs="0" maxOccurs="unbounded" /> +- <xsd:element ref="JPEG2000XMLBox" minOccurs="0" maxOccurs="unbounded" /> +- <xsd:element ref="JPEG2000UUIDBox" minOccurs="0" maxOccurs="unbounded" /> +- <xsd:element ref="JPEG2000UUIDInfoBox" minOccurs="0" maxOccurs="unbounded" /> +- </xsd:all> +- </xsd:complexType> +- </xsd:element> +- </xsd:sequence> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 Signature box --> +- <xsd:element name="JPEG2000SignatureBox"> +- <xsd:complexType> +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" fixed="12" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="jP " /> +- <xsd:attribute name="Signature" type="xsd:hexBinary" use="required" fixed="0D0A870A" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 File type box --> +- <xsd:element name="JPEG2000FileTypeBox"> +- <xsd:complexType> +- <xsd:sequence> +- <xsd:element name="Brand" type = "xsd:unsignedInt" /> +- +- <xsd:element name="MinorVersion" minOccurs="0"> +- <xsd:simpleType> +- <xsd:restriction base="xsd:unsignedInt"> +- <xsd:enumeration value="0" /> +- </xsd:restriction> +- </xsd:simpleType> +- </xsd:element> +- +- <xsd:element name="CompatibilityList" type="IntegerList" /> +- </xsd:sequence> +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="ftyp" /> +- <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 header super box--> +- <xsd:element name="JPEG2000HeaderSuperBox"> +- <xsd:complexType> +- <xsd:sequence> +- <xsd:element ref="JPEG2000HeaderBox" /> +- <xsd:element name="OptionalBoxes" minOccurs="0" > +- <xsd:complexType> +- <xsd:all> +- <xsd:element ref="JPEG2000BitsPerComponentBox" /> +- <xsd:element ref="JPEG2000ColorSpecificationBox" /> +- <xsd:element ref="JPEG2000PaletteBox" minOccurs="0" /> +- <xsd:element ref="JPEG2000ComponentMappingBox" minOccurs="0" /> +- <xsd:element ref="JPEG2000ChannelDefinitionBox" minOccurs="0" /> +- <xsd:element ref="JPEG2000ResolutionBox" minOccurs="0" /> +- </xsd:all> +- </xsd:complexType> +- </xsd:element> +- </xsd:sequence> +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="jp2h" /> +- <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 image header box --> +- <xsd:element name="JPEG2000HeaderBox"> +- <xsd:complexType> +- <xsd:sequence> +- <xsd:element name="Width" type="xsd:unsignedInt" /> +- <xsd:element name="Height" type="xsd:unsignedInt" /> +- <xsd:element name="NumComponents" type="xsd:unsignedShort" /> +- <xsd:element name="BitDepth" type="xsd:byte" /> +- <xsd:element name="CompressionType" type="xsd:unsignedByte" /> +- <xsd:element name="UnknownColorspace" type="xsd:unsignedByte" /> +- <xsd:element name="IntellectualProperty"> +- <xsd:simpleType> +- <xsd:restriction base="xsd:unsignedByte"> +- <xsd:enumeration value="0" /> +- <xsd:enumeration value="1" /> +- </xsd:restriction> +- </xsd:simpleType> +- </xsd:element> +- +- </xsd:sequence> +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" fixed="22" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="ihdr" /> +- <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 bits per component box --> +- <xsd:element name="JPEG2000BitsPerComponentBox"> +- <xsd:complexType> +- <xsd:sequence> +- <xsd:element name="BitDepth" type="ByteList" /> +- </xsd:sequence> +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="bpcc" /> +- <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 color specification box --> +- <xsd:element name="JPEG2000ColorSpecificationBox"> +- <xsd:complexType> +- <xsd:sequence> +- +- <xsd:element name="Method"> +- <xsd:simpleType> +- <xsd:restriction base="xsd:unsignedByte"> +- <xsd:enumeration value="1" /> +- <xsd:enumeration value="2" /> +- </xsd:restriction> +- </xsd:simpleType> +- </xsd:element> +- +- <xsd:element name="Precedence" type="xsd:byte" /> +- <xsd:element name="ApproximationAccuracy" type="xsd:byte" /> +- <xsd:element name="EnumeratedColorSpace" type="xsd:unsignedInt" /> +- <xsd:element name="ICCProfile" type="xsd:anyType" /> +- +- </xsd:sequence> +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="colr" /> +- <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 palette box --> +- <xsd:element name="JPEG2000PaletteBox"> +- <xsd:complexType> +- <xsd:sequence> +- +- <xsd:element name="NumberEntries"> +- <xsd:simpleType> +- <xsd:restriction base="xsd:unsignedShort"> +- <xsd:minInclusive value="1" /> +- <xsd:maxInclusive value="1024" /> +- </xsd:restriction> +- </xsd:simpleType> +- </xsd:element> +- +- <xsd:element name="NumberColors"> +- <xsd:simpleType> +- <xsd:restriction base="xsd:unsignedShort"> +- <xsd:minInclusive value="1" /> +- <xsd:maxInclusive value="255" /> +- </xsd:restriction> +- </xsd:simpleType> +- </xsd:element> +- +- <xsd:element name="BitDepth" type="ByteList" /> +- +- <xsd:element name="LUT"> +- <xsd:complexType> +- <xsd:sequence> +- <xsd:element name="LUTRow" maxOccurs="unbounded" type="ByteList" /> +- </xsd:sequence> +- </xsd:complexType> +- </xsd:element> +- +- </xsd:sequence> +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="pclr" /> +- <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 component mapping box--> +- <xsd:element name="JPEG2000ComponentMappingBox"> +- <xsd:complexType> +- <xsd:sequence maxOccurs="unbounded"> +- <xsd:element name="Component" type="xsd:unsignedShort" /> +- <xsd:element name="ComponentType" type="xsd:unsignedByte" /> +- <xsd:element name="ComponentAssociation" type="xsd:unsignedByte" /> +- </xsd:sequence> +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="cmap" /> +- <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 channel definition box--> +- <xsd:element name="JPEG2000ChannelDefinitionBox"> +- <xsd:complexType> +- <xsd:sequence> +- <xsd:element name="NumberOfDefinition" type="xsd:unsignedShort" /> +- <xsd:element name="Definitions"> +- <xsd:complexType> +- <xsd:sequence maxOccurs="unbounded"> +- <xsd:element name="ChannelNumber" type="xsd:unsignedShort" /> +- <xsd:element name="ChannelType"> +- <xsd:simpleType> +- <xsd:restriction base="xsd:unsignedShort"> +- <xsd:enumeration value="0" /> +- <xsd:enumeration value="1" /> +- <xsd:enumeration value="2" /> +- <xsd:enumeration value="65535" /> +- </xsd:restriction> +- </xsd:simpleType> +- </xsd:element> +- <xsd:element name="ChannelAssociation" type="xsd:unsignedShort" /> +- </xsd:sequence> +- </xsd:complexType> +- </xsd:element> +- </xsd:sequence> +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="cdef" /> +- <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 resolution box--> +- <xsd:element name="JPEG2000ResolutionBox"> +- <xsd:complexType> +- <xsd:sequence> +- <xsd:element ref="JPEG2000CaptureResolutionBox" minOccurs="0" /> +- <xsd:element ref="JPEG2000DefaultDisplayResolutionBox" minOccurs="0" /> +- </xsd:sequence> +- +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="res " /> +- <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 capture resolution box--> +- <xsd:element name="JPEG2000CaptureResolutionBox"> +- <xsd:complexType> +- +- <xsd:sequence> +- <xsd:element name="VerticalResolutionNumerator" type="xsd:unsignedShort" /> +- <xsd:element name="VerticalResolutionDenominator" type="xsd:unsignedShort" /> +- <xsd:element name="HorizontalResolutionNumerator" type="xsd:unsignedShort" /> +- <xsd:element name="HorizontalResolutionDenominator" type="xsd:unsignedShort" /> +- <xsd:element name="VerticalResolutionExponent" type="xsd:byte" /> +- <xsd:element name="HorizontalResolutionExponent" type="xsd:byte" /> +- </xsd:sequence> +- +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" fixed ="18" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="resc" /> +- <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 default display resolution box--> +- <xsd:element name="JPEG2000DefaultDisplayResolutionBox"> +- <xsd:complexType> +- +- <xsd:sequence> +- <xsd:element name="VerticalResolutionNumerator" type="xsd:unsignedShort" /> +- <xsd:element name="VerticalResolutionDenominator" type="xsd:unsignedShort" /> +- <xsd:element name="HorizontalResolutionNumerator" type="xsd:unsignedShort" /> +- <xsd:element name="HorizontalResolutionDenominator" type="xsd:unsignedShort" /> +- <xsd:element name="VerticalResolutionExponent" type="xsd:byte" /> +- <xsd:element name="HorizontalResolutionExponent" type="xsd:byte" /> +- </xsd:sequence> +- +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" fixed ="18" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="resd" /> +- <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 code stream box--> +- <xsd:element name="JPEG2000CodeStreamBox" > +- <xsd:complexType> +- <xsd:sequence> +- <xsd:element name="CodeStream" type="xsd:anyType" /> +- </xsd:sequence> +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="jp2c" /> +- <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 intellectual property rights box--> +- <xsd:element name="JPEG2000IntellectualPropertyRightsBox" > +- <xsd:complexType> +- <xsd:sequence> +- <!-- The structure of this box is defined in Part 2 so keep it +- general --> +- <xsd:element name="Content" type="xsd:anyType" /> +- </xsd:sequence> +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="jp2i" /> +- <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 XML box--> +- <xsd:element name="JPEG2000XMLBox"> +- <xsd:complexType> +- <xsd:sequence> +- <xsd:element name="Content" type="xsd:string" /> +- </xsd:sequence> +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="xml " /> +- <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 UUID box--> +- <xsd:element name="JPEG2000UUIDBox"> +- <xsd:complexType> +- <xsd:sequence> +- <xsd:element name="UUID"> +- <xsd:simpleType> +- <xsd:restriction base="ByteList"> +- <xsd:length value="16" /> +- </xsd:restriction> +- </xsd:simpleType> +- </xsd:element> +- <xsd:element name="Data" type="xsd:anyType" /> +- </xsd:sequence> +- +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="uuid" /> +- <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 UUID info box--> +- <xsd:element name="JPEG2000UUIDInfoBox"> +- <xsd:complexType> +- <xsd:sequence> +- <xsd:element ref="JPEG2000UUIDListBox" /> +- <xsd:element ref="JPEG2000DataEntryURLBox" /> +- </xsd:sequence> +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="uinf" /> +- <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 UUID list box--> +- <xsd:element name="JPEG2000UUIDListBox"> +- <xsd:complexType> +- <xsd:sequence> +- <xsd:element name="NumberUUID" type="xsd:unsignedShort" /> +- <xsd:element name="UUID" maxOccurs="unbounded"> +- <xsd:simpleType> +- <xsd:restriction base="ByteList"> +- <xsd:length value="16" /> +- </xsd:restriction> +- </xsd:simpleType> +- </xsd:element> +- </xsd:sequence> +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="ulst" /> +- <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- JPEG 2000 Data Entry URL box--> +- <xsd:element name="JPEG2000DataEntryURLBox"> +- <xsd:complexType> +- <xsd:sequence> +- <xsd:element name="Version" type="xsd:unsignedByte" /> +- <xsd:element name="Flags"> +- <xsd:simpleType> +- <xsd:restriction base="ByteList"> +- <xsd:length value="3" /> +- </xsd:restriction> +- </xsd:simpleType> +- </xsd:element> +- <xsd:element name="URL" type="xsd:anyURI" /> +- </xsd:sequence> +- <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" /> +- <xsd:attribute name="Type" type="xsd:string" use="required" fixed="url " /> +- <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" /> +- </xsd:complexType> +- </xsd:element> +- +- <!-- The basic types defined and used in JPEG 2000 schema --> +- <xsd:simpleType name="IntegerList"> +- <xsd:list itemType="xsd:unsignedInt" /> +- </xsd:simpleType> +- +- <xsd:simpleType name="ByteList"> +- <xsd:list itemType="xsd:byte" /> +- </xsd:simpleType> +- +- <xsd:simpleType name="LongNoLessThan16"> +- <xsd:restriction base="xsd:long"> +- <xsd:minInclusive value="16" /> +- </xsd:restriction> +- </xsd:simpleType> +- +-</xsd:schema> +-+- +-
+-Standard Metadata Attribute JP2 Box Element +---------------------------- --------------- +-/Chroma +- /ColorSpaceType +- @name if UnknownColorSpace in header box is 0 +- then if EnumeratedColorSpace in +- color specification box is 16 --> RGB +- if EnumeratedColorSpace in +- color specification box is 17 -->GRAY +- /NumChannels +- @value if palette box exists +- the component number in palette box +- else +- the component number in header box +- /Palette if palette box exits +- /PaletteEntry +- @index +- @red lut[index][0] +- @green lut[index][1] +- @blue lut[index][2] +- @alpha lut[index][3] if the component number is 4 +- +-/Compression +- @value "JPEG2000" +- +-/Data +- /SampleFormat +- @value if the palette box exists, -->"Index" +- else if bit depth in header box or +- bits per component box has the sign bit +- --> "SignedIntegral" +- else --> "UnsignedIntegral" +- /BitsPerSample +- @value derive from the bit depth of header box +- or bits per component box +- /PlanarConfiguration +- @value --> "TileInterleaved" +- +-/Dimension +- /PixelAspectRatio +- @value the ratio of the horizontal and vertical +- resolution in the capture resolution box +- /HorizontalPhysicalPixelSpacing +- @value derived from the horizontal resolution +- (in pixel-per-meter) in the capture +- resolution box +- /VerticalPhysicalPixelSpacing +- @value derived from the vertical resolution +- (in pixel-per-meter) in the capture i +- resolution box +-/Transparency +- /Alpha +- @value --> "none" if no channel definition box or +- no alpha channel is defined in channel +- definition box +- --> "nonpremultiplied" if no premultiplied +- channel is defined in the channel +- definition box +- --> "premultiplied" if any premultiplied +- channel(s) defined in the channel +- definition box +-/Text +- /TextEntry +- @value The content of any XML box; each XML box +- defines a TextEntry +-+- +-@since 1.0 +- +- +diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/BitsPerComponentBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/BitsPerComponentBox.java +--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/BitsPerComponentBox.java 2005-02-11 00:01:31.000000000 -0500 ++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/BitsPerComponentBox.java 1969-12-31 19:00:00.000000000 -0500 +@@ -1,91 +0,0 @@ +-/* +- * $RCSfile: BitsPerComponentBox.java,v $ +- * +- * +- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. +- * +- * Redistribution and use in source and binary forms, with or without +- * modification, are permitted provided that the following conditions +- * are met: +- * +- * - Redistribution of source code must retain the above copyright +- * notice, this list of conditions and the following disclaimer. +- * +- * - Redistribution in binary form must reproduce the above copyright +- * notice, this list of conditions and the following disclaimer in +- * the documentation and/or other materials provided with the +- * distribution. +- * +- * Neither the name of Sun Microsystems, Inc. or the names of +- * contributors may be used to endorse or promote products derived +- * from this software without specific prior written permission. +- * +- * This software is provided "AS IS," without a warranty of any +- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND +- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, +- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY +- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL +- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF +- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS +- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR +- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, +- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND +- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR +- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE +- * POSSIBILITY OF SUCH DAMAGES. +- * +- * You acknowledge that this software is not designed or intended for +- * use in the design, construction, operation or maintenance of any +- * nuclear facility. +- * +- * $Revision: 1.1 $ +- * $Date: 2005/02/11 05:01:31 $ +- * $State: Exp $ +- */ +- +-package com.sun.media.imageioimpl.plugins.jpeg2000; +- +-import javax.imageio.metadata.IIOInvalidTreeException; +-import javax.imageio.metadata.IIOMetadataNode; +-import org.w3c.dom.Node; +-import org.w3c.dom.NodeList; +- +-/** This class is defined to represent a Bits Per Component Box of JPEG +- * JP2 file format. A Bits Per Component box has a length, and a fixed +- * type of "bpcc". Its content is a byte array containing the bit +- * depths of the color components. +- * +- * This box is necessary only when the bit depth are not identical for all +- * the components. +- */ +-public class BitsPerComponentBox extends Box { +- /** Counstructs a
BitsPerComponentBox
from the provided
+- * byte array containing the bit depths of each color component.
+- */
+- public BitsPerComponentBox(byte[] bitDepth) {
+- super(8 + bitDepth.length, 0x62706363, null);
+- data = bitDepth;
+- }
+-
+- /** Constructs a BitsPerComponentBox
based on the provide
+- * org.w3c.dom.Node
.
+- */
+- public BitsPerComponentBox(Node node) throws IIOInvalidTreeException {
+- super(node);
+- NodeList children = node.getChildNodes();
+-
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+- String name = child.getNodeName();
+-
+- if ("BitDepth".equals(name)) {
+- data = Box.getByteArrayElementValue(child);
+- }
+- }
+- }
+-
+- /** Returns the bit depths for all the image components. */
+- public byte[] getBitDepth() {
+- return data;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/Box.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/Box.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/Box.java 2007-09-05 16:03:20.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/Box.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,643 +0,0 @@
+-/*
+- * $RCSfile: Box.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.6 $
+- * $Date: 2007/09/05 20:03:20 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.lang.reflect.Constructor;
+-import java.lang.reflect.Method;
+-import java.lang.reflect.InvocationTargetException;
+-import javax.imageio.metadata.IIOInvalidTreeException;
+-import javax.imageio.metadata.IIOMetadataNode;
+-
+-import java.io.EOFException;
+-import java.io.IOException;
+-import java.util.Enumeration;
+-import java.util.Hashtable;
+-import java.util.StringTokenizer;
+-
+-import org.w3c.dom.NamedNodeMap;
+-import org.w3c.dom.Node;
+-import org.w3c.dom.NodeList;
+-
+-import javax.imageio.IIOException;
+-import javax.imageio.stream.ImageOutputStream;
+-import javax.imageio.stream.ImageInputStream;
+-
+-import com.sun.media.imageioimpl.common.ImageUtil;
+-
+-/**
+- * This class is defined to create the box of JP2 file format. A box has
+- * a length, a type, an optional extra length and its content. The subclasses
+- * should explain the content information.
+- */
+-public class Box {
+- /** The table to link tag names for all the JP2 boxes. */
+- private static Hashtable names = new Hashtable();
+-
+- // Initializes the hash table "names".
+- static {
+- //children for the root
+- names.put(new Integer(0x6A502020), "JPEG2000SignatureBox");
+- names.put(new Integer(0x66747970), "JPEG2000FileTypeBox");
+-
+- // children for the boxes other than
+- //JPEG2000SignatureBox/JPEG2000FileTypeBox
+- names.put(new Integer(0x6A703269),
+- "JPEG2000IntellectualPropertyRightsBox");
+- names.put(new Integer(0x786D6C20), "JPEG2000XMLBox");
+- names.put(new Integer(0x75756964), "JPEG2000UUIDBox");
+- names.put(new Integer(0x75696E66), "JPEG2000UUIDInfoBox");
+-
+- // Children of HeadCStream
+- names.put(new Integer(0x6a703268), "JPEG2000HeaderSuperBox");
+- names.put(new Integer(0x6a703263), "JPEG2000CodeStreamBox");
+-
+- // Children of JPEG2000HeaderSuperBox
+- names.put(new Integer(0x69686472), "JPEG2000HeaderBox");
+-
+- // Optional boxes in JPEG2000HeaderSuperBox
+- names.put(new Integer(0x62706363), "JPEG2000BitsPerComponentBox");
+- names.put(new Integer(0x636f6c72), "JPEG2000ColorSpecificationBox");
+- names.put(new Integer(0x70636c72), "JPEG2000PaletteBox");
+- names.put(new Integer(0x636d6170), "JPEG2000ComponentMappingBox");
+- names.put(new Integer(0x63646566), "JPEG2000ChannelDefinitionBox");
+- names.put(new Integer(0x72657320), "JPEG2000ResolutionBox");
+-
+- // Children of JPEG2000ResolutionBox
+- names.put(new Integer(0x72657363), "JPEG2000CaptureResolutionBox");
+- names.put(new Integer(0x72657364),
+- "JPEG2000DefaultDisplayResolutionBox");
+-
+- // Children of JPEG2000UUIDInfoBox
+- names.put(new Integer(0x756c7374), "JPEG2000UUIDListBox");
+- names.put(new Integer(0x75726c20), "JPEG2000DataEntryURLBox");
+- }
+-
+- /** A Hashtable contains the class names for each type of the boxes.
+- * This table will be used to construct a Box object from a Node object
+- * by using reflection.
+- */
+- private static Hashtable boxClasses = new Hashtable();
+-
+- // Initializes the hash table "boxClasses".
+- static {
+- //children for the root
+- boxClasses.put(new Integer(0x6A502020), SignatureBox.class);
+- boxClasses.put(new Integer(0x66747970), FileTypeBox.class);
+-
+- // children for the boxes other than
+- //JPEG2000SignatureBox/JPEG2000FileTypeBox
+- boxClasses.put(new Integer(0x6A703269), Box.class);
+- boxClasses.put(new Integer(0x786D6C20), XMLBox.class);
+- boxClasses.put(new Integer(0x75756964), UUIDBox.class);
+-
+- // Children of JPEG2000HeaderSuperBox
+- boxClasses.put(new Integer(0x69686472), HeaderBox.class);
+-
+- // Optional boxes in JPEG2000HeaderSuperBox
+- boxClasses.put(new Integer(0x62706363), BitsPerComponentBox.class);
+- boxClasses.put(new Integer(0x636f6c72), ColorSpecificationBox.class);
+- boxClasses.put(new Integer(0x70636c72), PaletteBox.class);
+- boxClasses.put(new Integer(0x636d6170), ComponentMappingBox.class);
+- boxClasses.put(new Integer(0x63646566), ChannelDefinitionBox.class);
+- boxClasses.put(new Integer(0x72657320), ResolutionBox.class);
+-
+- // Children of JPEG2000ResolutionBox
+- boxClasses.put(new Integer(0x72657363), ResolutionBox.class);
+- boxClasses.put(new Integer(0x72657364), ResolutionBox.class);
+-
+- // Children of JPEG2000UUIDInfoBox
+- boxClasses.put(new Integer(0x756c7374), UUIDListBox.class);
+- boxClasses.put(new Integer(0x75726c20), DataEntryURLBox.class);
+- }
+-
+- /** Returns the XML tag name defined in JP2 XML xsd/dtd for the box
+- * with the provided type
. If the type
is
+- * not known, the string "unknown"
is returned.
+- */
+- public static String getName(int type) {
+- String name = (String)names.get(new Integer(type));
+- return name == null ? "unknown" : name;
+- }
+-
+- /** Returns the Box class for the box with the provided type
.
+- */
+- public static Class getBoxClass(int type) {
+- if (type == 0x6a703268 || type == 0x72657320)
+- return null;
+- return (Class)boxClasses.get(new Integer(type));
+- }
+-
+- /** Returns the type String based on the provided name. */
+- public static String getTypeByName(String name) {
+- Enumeration keys = names.keys();
+- while (keys.hasMoreElements()) {
+- Integer i = (Integer)keys.nextElement();
+- if (name.equals(names.get(i)))
+- return getTypeString(i.intValue());
+- }
+- return null;
+- }
+-
+- /** Creates a Box
object with the provided type
+- * based on the provided Node object based on reflection.
+- */
+- public static Box createBox(int type,
+- Node node) throws IIOInvalidTreeException {
+- Class boxClass = (Class)boxClasses.get(new Integer(type));
+-
+- try {
+- // gets the constructor with Node
Box instance.
+- e.printStackTrace();
+- return new Box(node);
+- } catch(InvocationTargetException e) {
+- e.printStackTrace();
+- return new Box(node);
+- } catch (IllegalAccessException e) {
+- e.printStackTrace();
+- return new Box(node);
+- } catch (InstantiationException e) {
+- e.printStackTrace();
+- return new Box(node);
+- }
+-
+- return null;
+- }
+-
+- /** Extracts the value of the attribute from name. */
+- public static Object getAttribute(Node node, String name) {
+- NamedNodeMap map = node.getAttributes();
+- node = map.getNamedItem(name);
+- return (node != null) ? node.getNodeValue() : null;
+- }
+-
+- /** Parses the byte array expressed by a string. */
+- public static byte[] parseByteArray(String value) {
+- if (value == null)
+- return null;
+-
+- StringTokenizer token = new StringTokenizer(value);
+- int count = token.countTokens();
+-
+- byte[] buf = new byte[count];
+- int i = 0;
+- while(token.hasMoreElements()) {
+- buf[i++] = new Byte(token.nextToken()).byteValue();
+- }
+- return buf;
+- }
+-
+- /** Parses the integer array expressed a string. */
+- protected static int[] parseIntArray(String value) {
+- if (value == null)
+- return null;
+-
+- StringTokenizer token = new StringTokenizer(value);
+- int count = token.countTokens();
+-
+- int[] buf = new int[count];
+- int i = 0;
+- while(token.hasMoreElements()) {
+- buf[i++] = new Integer(token.nextToken()).intValue();
+- }
+- return buf;
+- }
+-
+- /** Gets its String
value from an IIOMetadataNode
.
+- */
+- protected static String getStringElementValue(Node node) {
+-
+- if (node instanceof IIOMetadataNode) {
+- Object obj = ((IIOMetadataNode)node).getUserObject();
+- if (obj instanceof String)
+- return (String)obj;
+- }
+-
+- return node.getNodeValue();
+- }
+-
+- /** Gets its byte value from an IIOMetadataNode
. */
+- protected static byte getByteElementValue(Node node) {
+- if (node instanceof IIOMetadataNode) {
+- Object obj = ((IIOMetadataNode)node).getUserObject();
+- if (obj instanceof Byte)
+- return ((Byte)obj).byteValue();
+- }
+-
+- String value = node.getNodeValue();
+- if (value != null)
+- return new Byte(value).byteValue();
+- return (byte)0;
+- }
+-
+- /** Gets its integer value from an IIOMetadataNode
. */
+- protected static int getIntElementValue(Node node) {
+- if (node instanceof IIOMetadataNode) {
+- Object obj = ((IIOMetadataNode)node).getUserObject();
+- if (obj instanceof Integer)
+- return ((Integer)obj).intValue();
+- }
+-
+- String value = node.getNodeValue();
+- if (value != null)
+- return new Integer(value).intValue();
+- return 0;
+- }
+-
+- /** Gets its short value from an IIOMetadataNode
. */
+- protected static short getShortElementValue(Node node) {
+- if (node instanceof IIOMetadataNode) {
+- Object obj = ((IIOMetadataNode)node).getUserObject();
+- if (obj instanceof Short)
+- return ((Short)obj).shortValue();
+- }
+- String value = node.getNodeValue();
+- if (value != null)
+- return new Short(value).shortValue();
+- return (short)0;
+- }
+-
+- /** Gets the byte array from an IIOMetadataNode
. */
+- protected static byte[] getByteArrayElementValue(Node node) {
+- if (node instanceof IIOMetadataNode) {
+- Object obj = ((IIOMetadataNode)node).getUserObject();
+- if (obj instanceof byte[])
+- return (byte[])obj;
+- }
+-
+- return parseByteArray(node.getNodeValue());
+- }
+-
+- /** Gets the integer array from an IIOMetadataNode
. */
+- protected static int[] getIntArrayElementValue(Node node) {
+- if (node instanceof IIOMetadataNode) {
+- Object obj = ((IIOMetadataNode)node).getUserObject();
+- if (obj instanceof int[])
+- return (int[])obj;
+- }
+-
+- return parseIntArray(node.getNodeValue());
+- }
+-
+- /** Copies that four bytes of an integer into the byte array. Necessary
+- * for the subclasses to compose the content array from the data elements
+- */
+- public static void copyInt(byte[] data, int pos, int value) {
+- data[pos++] = (byte)(value >> 24);
+- data[pos++] = (byte)(value >> 16);
+- data[pos++] = (byte)(value >> 8);
+- data[pos++] = (byte)(value & 0xFF);
+- }
+-
+- /** Converts the box type from integer to string. This is necessary because
+- * type is defined as String in xsd/dtd and integer in the box classes.
+- */
+- public static String getTypeString(int type) {
+- byte[] buf = new byte[4];
+- for (int i = 3; i >= 0; i--) {
+- buf[i] = (byte)(type & 0xFF);
+- type >>>= 8;
+- }
+-
+- return new String(buf);
+- }
+-
+- /**
+- * Converts the box type from integer to string. This is necessary because
+- * type is defined as String in xsd/dtd and integer in the box classes.
+- */
+- public static int getTypeInt(String s) {
+- byte[] buf = s.getBytes();
+- int t = buf[0];
+- for (int i = 1; i < 4; i++) {
+- t = (t <<8) | buf[i];
+- }
+-
+- return t;
+- }
+-
+- /** Box length, extra length, type and content data array */
+- protected int length;
+- protected long extraLength;
+- protected int type;
+- protected byte[] data;
+-
+- /** Constructs a Box
instance using the provided
+- * the box type and the box content in byte array format.
+- *
+- * @param length The provided box length.
+- * @param type The provided box type.
+- * @param data The provided box content in a byte array.
+- *
+- * @throws IllegalArgumentException If the length of the content byte array
+- * is not length - 8.
+- */
+- public Box(int length, int type, byte[] data) {
+- this.type = type;
+- setLength(length);
+- setContent(data);
+- }
+-
+- /** Constructs a Box
instance using the provided
+- * the box type, the box extra length, and the box content in byte
+- * array format. In this case, the length of the box is set to 1,
+- * which indicates the extra length is meaningful.
+- *
+- * @param length The provided box length.
+- * @param type The provided box type.
+- * @param extraLength The provided box extra length.
+- * @param data The provided box content in a byte array.
+- *
+- * @throws IllegalArgumentException If the length of the content byte array
+- * is not extra length - 16.
+- */
+- public Box(int length, int type, long extraLength, byte[] data) {
+- this.type = type;
+- setLength(length);
+- if (length == 1)
+- setExtraLength(extraLength);
+- setContent(data);
+- }
+-
+- /** Constructs a Box
instance from the provided
+- * ImageInputStream
at the specified position.
+- *
+- * @param iis The ImageInputStream
contains the box.
+- * @param pos The position from where to read the box.
+- * @throws IOException If any IOException is thrown in the called read
+- * methods.
+- */
+- public Box(ImageInputStream iis, int pos) throws IOException {
+- read(iis, pos);
+- }
+-
+- /**
+- * Constructs a Box from an "unknown" Node. This node has at
+- * least the attribute "Type", and may have the attribute "Length",
+- * "ExtraLength" and a child "Content". The child node content is a
+- * IIOMetaDataNode with a byte[] user object.
+- */
+- public Box(Node node) throws IIOInvalidTreeException {
+- NodeList children = node.getChildNodes();
+-
+- String value = (String)Box.getAttribute(node, "Type");
+- type = getTypeInt(value);
+- if (value == null || names.get(new Integer(type)) == null)
+- throw new IIOInvalidTreeException("Type is not defined", node);
+-
+- value = (String)Box.getAttribute(node, "Length");
+- if (value != null)
+- length = new Integer(value).intValue();
+-
+- value = (String)Box.getAttribute(node, "ExtraLength");
+- if (value != null)
+- extraLength = new Long(value).longValue();
+-
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+- if ("Content".equals(child.getNodeName())) {
+- if (child instanceof IIOMetadataNode) {
+- IIOMetadataNode cnode = (IIOMetadataNode)child;
+- try {
+- data = (byte[])cnode.getUserObject();
+- } catch (Exception e) {
+- }
+- }else {
+- data = getByteArrayElementValue(child);
+- }
+-
+- if (data == null) {
+- value = node.getNodeValue();
+- if (value != null)
+- data = value.getBytes();
+- }
+- }
+- }
+- }
+-
+- /** Creates an IIOMetadataNode
from this
+- * box. The format of this node is defined in the XML dtd and xsd
+- * for the JP2 image file.
+- */
+- public IIOMetadataNode getNativeNode() {
+- String name = Box.getName(getType());
+- if (name == null)
+- name = "unknown";
+-
+- IIOMetadataNode node = new IIOMetadataNode(name);
+- setDefaultAttributes(node);
+- IIOMetadataNode child = new IIOMetadataNode("Content");
+- child.setUserObject(data);
+- child.setNodeValue(ImageUtil.convertObjectToString(data));
+- node.appendChild(child);
+-
+- return node;
+- }
+-
+- /** Creates an IIOMetadataNode
from this
+- * box. The format of this node is defined in the XML dtd and xsd
+- * for the JP2 image file.
+- *
+- * This method is designed for the types of boxes whose XML tree
+- * only has 2 levels.
+- */
+- protected IIOMetadataNode getNativeNodeForSimpleBox() {
+- try {
+- Method m = this.getClass().getMethod("getElementNames",
+- (Class[])null);
+- String[] elementNames = (String[])m.invoke(null, (Object[])null);
+-
+- IIOMetadataNode node = new IIOMetadataNode(Box.getName(getType()));
+- setDefaultAttributes(node);
+- for (int i = 0; i < elementNames.length; i++) {
+- IIOMetadataNode child = new IIOMetadataNode(elementNames[i]);
+- m = this.getClass().getMethod("get" + elementNames[i],
+- (Class[])null);
+- Object obj = m.invoke(this, (Object[])null);
+- child.setUserObject(obj);
+- child.setNodeValue(ImageUtil.convertObjectToString(obj));
+- node.appendChild(child);
+- }
+- return node;
+- } catch (Exception e) {
+- throw new IllegalArgumentException(I18N.getString("Box0"));
+- }
+- }
+-
+- /** Sets the default attributes, "Length", "Type", and "ExtraLength", to
+- * the provided IIOMetadataNode
.
+- */
+- protected void setDefaultAttributes(IIOMetadataNode node) {
+- node.setAttribute("Length", Integer.toString(length));
+- node.setAttribute("Type", getTypeString(type));
+-
+- if (length == 1) {
+- node.setAttribute("ExtraLength", Long.toString(extraLength));
+- }
+- }
+-
+- /** Returns the box length. */
+- public int getLength() {
+- return length;
+- }
+-
+- /** Returns the box type. */
+- public int getType() {
+- return type;
+- }
+-
+- /** Returns the box extra length. */
+- public long getExtraLength() {
+- return extraLength;
+- }
+-
+- /** Returns the box content in byte array. */
+- public byte[] getContent() {
+- if (data == null)
+- compose();
+- return data;
+- }
+-
+- /** Sets the box length to the provided value. */
+- public void setLength(int length) {
+- this.length = length;
+- }
+-
+- /** Sets the box extra length length to the provided value. */
+- public void setExtraLength(long extraLength) {
+- if (length != 1)
+- throw new IllegalArgumentException(I18N.getString("Box1"));
+- this.extraLength = extraLength;
+- }
+-
+- /** Sets the box content. If the content length is not length -8 or
+- * extra length - 16, IllegalArgumentException will be thrown.
+- */
+- public void setContent(byte[] data) {
+- if (data != null &&
+- ((length ==1 && (extraLength - 16 != data.length)) ||
+- (length != 1 && length - 8 != data.length)))
+- throw new IllegalArgumentException(I18N.getString("Box2"));
+- this.data = data;
+- if (data != null)
+- parse(data);
+- }
+-
+- /** Writes this box instance into a ImageOutputStream
. */
+- public void write(ImageOutputStream ios) throws IOException {
+- ios.writeInt(length);
+- ios.writeInt(type);
+- if (length == 1) {
+- ios.writeLong(extraLength);
+- ios.write(data, 0, (int)extraLength);
+- } else if (data != null)
+- ios.write(data, 0, length);
+- }
+-
+- /** Reads a box from the ImageInputStream= 8 && length < (1 << 32)) {
+- // Length given by L parameter.
+- dataLength = length - 8;
+- } else {
+- // Illegal value for L parameter.
+- throw new IIOException("Illegal value "+length+
+- " for box length parameter.");
+- }
+- data = new byte[dataLength];
+- iis.readFully(data);
+- iis.reset();
+- }
+-
+- /** Parses the data elements from the byte array. The subclasses should
+- * override this method.
+- */
+- protected void parse(byte[] data) {
+- }
+-
+- /** Composes the content byte array from the data elements.
+- */
+- protected void compose() {
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ChannelDefinitionBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ChannelDefinitionBox.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ChannelDefinitionBox.java 2005-02-11 00:01:31.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ChannelDefinitionBox.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,272 +0,0 @@
+-/*
+- * $RCSfile: ChannelDefinitionBox.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:31 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.awt.image.ColorModel;
+-import javax.imageio.metadata.IIOInvalidTreeException;
+-import javax.imageio.metadata.IIOMetadataNode;
+-import org.w3c.dom.Node;
+-import org.w3c.dom.NodeList;
+-
+-/** This class is designed to represent a Channel Definition Box of
+- * JPEG JP2 file format. A Channel Definition Box has a length, and
+- * a fixed type of "cdef". Its content defines the type of the image
+- * channels: color channel, alpha channel or premultiplied alpha channel.
+- */
+-public class ChannelDefinitionBox extends Box {
+- /** The cached data elements. */
+- private short num;
+- private short[] channels;
+- private short[] types;
+- private short[] associations;
+-
+- /** Computes the length of this box from the provided
+- * ColorModel
.
+- */
+- private static int computeLength(ColorModel colorModel) {
+- int length = colorModel.getComponentSize().length - 1;
+- return 10 +
+- (colorModel.isAlphaPremultiplied() ? length * 18 : length * 12);
+- }
+-
+- /** Fills the channel definitions into the arrays based on the number
+- * of components and isPremultiplied.
+- */
+- public static void fillBasedOnBands(int numComps,
+- boolean isPremultiplied,
+- short[] c,
+- short[] t,
+- short[] a) {
+- int num = numComps * (isPremultiplied ? 3 : 2);
+- if (isPremultiplied) {
+- for (int i = numComps * 2; i < num; i++) {
+- c[i] = (short)(i - numComps * 2);
+- t[i] = 2; // 2 -- premultiplied
+- a[i] = (short)(i + 1 - numComps * 2);
+- }
+- }
+-
+- for (int i = 0; i < numComps; i++) {
+- int j = i + numComps;
+- c[i] = (short)i;
+- t[i] = 0; // The original channel
+- a[j] = a[i] = (short)(i + 1);
+-
+- c[j] = (short)numComps;
+- t[j] = 1; // 1 -- transparency
+- }
+- }
+-
+- /** Constructs a ChannelDefinitionBox
based on the provided
+- * ColorModel
.
+- */
+- public ChannelDefinitionBox(ColorModel colorModel) {
+- super(computeLength(colorModel), 0x63646566, null);
+-
+- // creates the buffers for the channel definitions.
+- short length = (short)(colorModel.getComponentSize().length - 1);
+- num = (short)(length * (colorModel.isAlphaPremultiplied() ? 3 : 2));
+- channels = new short[num];
+- types = new short[num];
+- associations = new short[num];
+-
+- // fills the arrays.
+- fillBasedOnBands(length,
+- colorModel.isAlphaPremultiplied(),
+- channels,
+- types,
+- associations);
+- }
+-
+- /** Constructs a ChannelDefinitionBox
based on the provided
+- * content in byte array.
+- */
+- public ChannelDefinitionBox(byte[] data) {
+- super(8 + data.length, 0x63646566, data);
+- }
+-
+- /** Constructs a ChannelDefinitionBox
based on the provided
+- * channel definitions.
+- */
+- public ChannelDefinitionBox(short[] channel, short[] types,
+- short[] associations) {
+- super(10 + channel.length * 6, 0x63646566, null);
+- this.num = (short)channel.length;
+- this.channels = channel;
+- this.types = types;
+- this.associations = associations;
+- }
+-
+- /** Constructs a ChannelDefinitionBox
based on the provided
+- * org.w3c.dom.Node
.
+- */
+- public ChannelDefinitionBox(Node node) throws IIOInvalidTreeException {
+- super(node);
+- NodeList children = node.getChildNodes();
+- int index = 0;
+-
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+- String name = child.getNodeName();
+-
+- if ("NumberOfDefinition".equals(name)) {
+- num = Box.getShortElementValue(child);
+- }
+-
+- if ("Definitions".equals(name)) {
+- channels = new short[num];
+- types = new short[num];
+- associations = new short[num];
+-
+- NodeList children1 = child.getChildNodes();
+-
+- for (int j = 0; j < children1.getLength(); j++) {
+- child = children1.item(j);
+- name = child.getNodeName();
+- if ("ChannelNumber".equals(name)) {
+- channels[index] = Box.getShortElementValue(child);
+- }
+-
+- if ("ChannelType".equals(name)) {
+- types[index] = Box.getShortElementValue(child);
+- }
+-
+- if ("Association".equals(name)) {
+- associations[index++] = Box.getShortElementValue(child);
+- }
+- }
+- }
+- }
+- }
+-
+- /** Parse the channel definitions from the content data array. */
+- protected void parse(byte[] data) {
+- num = (short)((data[0] << 8) | data[1]);
+- channels = new short[num];
+- types = new short[num];
+- associations = new short[num];
+-
+- for (int i = 0, j = 2; i < num; i++) {
+- channels[i] =
+- (short)(((data[j++] & 0xFF) << 8) + (data[j++] & 0xFF));
+- types[i] = (short)(((data[j++] & 0xFF) << 8) + (data[j++] & 0xFF));
+- associations[i] =
+- (short)(((data[j++] & 0xFF) << 8) + (data[j++] & 0xFF));
+- }
+- }
+-
+- /** Returns the defined channels. */
+- public short[] getChannel() {
+- return channels;
+- }
+-
+- /** Returns the channel types. */
+- public short[] getTypes() {
+- return types;
+- }
+-
+- /** Returns the association which associates a color channel to a color
+- * component in the color space of the image.
+- */
+- public short[] getAssociation() {
+- return associations;
+- }
+-
+- /** Creates an IIOMetadataNode
from this channel definition
+- * box. The format of this node is defined in the XML dtd and xsd
+- * for the JP2 image file.
+- */
+- public IIOMetadataNode getNativeNode() {
+- IIOMetadataNode node = new IIOMetadataNode(Box.getName(getType()));
+- setDefaultAttributes(node);
+-
+- IIOMetadataNode child = new IIOMetadataNode("NumberOfDefinition");
+- child.setUserObject(new Short(num));
+- child.setNodeValue("" + num);
+- node.appendChild(child);
+-
+- child = new IIOMetadataNode("Definitions");
+- node.appendChild(child);
+-
+- for (int i = 0; i < num; i++) {
+- IIOMetadataNode child1 = new IIOMetadataNode("ChannelNumber");
+- child1.setUserObject(new Short(channels[i]));
+- child1.setNodeValue("" + channels[i]);
+- child.appendChild(child1);
+-
+- child1 = new IIOMetadataNode("ChannelType");
+- child1.setUserObject(new Short(types[i]));
+- child1.setNodeValue("" + types[i]);
+- child.appendChild(child1);
+-
+- child1 = new IIOMetadataNode("Association");
+- child1.setUserObject(new Short(associations[i]));
+- child1.setNodeValue("" + associations[i]);
+- child.appendChild(child1);
+- }
+-
+- return node;
+- }
+-
+- protected void compose() {
+- if (data != null)
+- return;
+- int len = num * 6 + 2;
+- data = new byte[len];
+- data[0] = (byte)(num >> 8);
+- data[1] = (byte)(num & 0xFF);
+-
+- for (int i = 0, j = 2; i < num; i++) {
+- data[j++] = (byte)(channels[i] >> 8);
+- data[j++] = (byte)(channels[i] & 0xFF);
+-
+- data[j++] = (byte)(types[i] >> 8);
+- data[j++] = (byte)(types[i] & 0xFF);
+-
+- data[j++] = (byte)(associations[i] >> 8);
+- data[j++] = (byte)(associations[i] & 0xFF);
+- }
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ColorSpecificationBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ColorSpecificationBox.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ColorSpecificationBox.java 2005-02-11 00:01:32.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ColorSpecificationBox.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,222 +0,0 @@
+-/*
+- * $RCSfile: ColorSpecificationBox.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:32 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.awt.color.ICC_Profile;
+-import javax.imageio.metadata.IIOInvalidTreeException;
+-import javax.imageio.metadata.IIOMetadataNode;
+-import org.w3c.dom.Node;
+-import org.w3c.dom.NodeList;
+-
+-/** This class is defined to represent a Color Specification Box of JPEG JP2
+- * file format. A Channel Definition Box has a length, and a fixed type
+- * of "colr". Its content contains the method to define the color space,
+- * the precedence and approximation accuracy (0 for JP2 files), the
+- * enumerated color space, and the ICC color profile if any.
+- */
+-public class ColorSpecificationBox extends Box {
+- /** The enumerated color space defined in JP2 file format. */
+- public static final int ECS_sRGB = 16;
+- public static final int ECS_GRAY = 17;
+- public static final int ECS_YCC = 18;
+-
+- /** Cache the element names for this box's xml definition */
+- private static String[] elementNames = {"Method", "Precedence",
+- "ApproximationAccuracy",
+- "EnumeratedColorSpace",
+- "ICCProfile"};
+-
+- /** This method will be called by the getNativeNodeForSimpleBox of the
+- * class Box to get the element names.
+- */
+- public static String[] getElementNames() {
+- return elementNames;
+- }
+-
+- /** The elements' values. */
+- private byte method;
+- private byte precedence;
+- private byte approximation;
+- private int ecs;
+- private ICC_Profile profile;
+-
+- /** Computes the length of this box when profile is present. */
+- private static int computeLength(byte m, ICC_Profile profile) {
+- int ret = 15;
+- if (m == 2 && profile != null) {
+- ret += profile.getData().length;
+- }
+- return ret;
+- }
+-
+- /** Creates a ColorSpecificationBox
from the provided data
+- * elements.
+- */
+- public ColorSpecificationBox(byte m, byte p, byte a, int ecs,
+- ICC_Profile profile) {
+- super(computeLength(m, profile), 0x636F6C72, null);
+- this.method = m;
+- this.precedence = p;
+- this.approximation = a;
+- this.ecs = ecs;
+- this.profile = profile;
+- }
+-
+- /** Creates a ColorSpecificationBox
from the provided byte
+- * array.
+- */
+- public ColorSpecificationBox(byte[] data) {
+- super(8 + data.length, 0x636F6C72, data);
+- }
+-
+- /** Constructs a ColorSpecificationBox
based on the provided
+- * org.w3c.dom.Node
.
+- */
+- public ColorSpecificationBox(Node node) throws IIOInvalidTreeException {
+- super(node);
+- NodeList children = node.getChildNodes();
+-
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+- String name = child.getNodeName();
+-
+- if ("Method".equals(name)) {
+- method = Box.getByteElementValue(child);
+- }
+-
+- if ("Precedence".equals(name)) {
+- precedence = Box.getByteElementValue(child);
+- }
+-
+- if ("ApproximationAccuracy".equals(name)) {
+- approximation = Box.getByteElementValue(child);
+- }
+-
+- if ("EnumeratedColorSpace".equals(name)) {
+- ecs = Box.getIntElementValue(child);
+- }
+-
+- if ("ICCProfile".equals(name)) {
+- if (child instanceof IIOMetadataNode)
+- profile =
+- (ICC_Profile)((IIOMetadataNode)child).getUserObject();
+- else {
+- String value = node.getNodeValue();
+- if (value != null)
+- profile = ICC_Profile.getInstance(Box.parseByteArray(value));
+- }
+- }
+- }
+- }
+-
+- /** Returns the method to define the color space. */
+- public byte getMethod() {
+- return method;
+- }
+-
+- /** Returns Precedence
. */
+- public byte getPrecedence() {
+- return precedence;
+- }
+-
+- /** Returns ApproximationAccuracy
. */
+- public byte getApproximationAccuracy() {
+- return approximation;
+- }
+-
+- /** Returns the enumerated color space. */
+- public int getEnumeratedColorSpace() {
+- return ecs;
+- }
+-
+- /** Returns the ICC color profile in this color specification box. */
+- public ICC_Profile getICCProfile() {
+- return profile;
+- }
+-
+- /** Creates an IIOMetadataNode
from this color specification
+- * box. The format of this node is defined in the XML dtd and xsd
+- * for the JP2 image file.
+- */
+- public IIOMetadataNode getNativeNode() {
+- return getNativeNodeForSimpleBox();
+- }
+-
+- protected void parse(byte[] data) {
+- method = data[0];
+- precedence = data[1];
+- approximation = data[2];
+- if (method == 2) {
+- byte[] proData = new byte[data.length - 3];
+- System.arraycopy(data, 3, proData, 0, data.length - 3);
+- profile = ICC_Profile.getInstance(proData);
+- } else
+- ecs = ((data[3] & 0xFF) << 24) | ((data[4] & 0xFF) << 16) |
+- ((data[5] & 0xFF) << 8) | (data[6] & 0xFF);
+-
+- }
+-
+- protected void compose() {
+- if (data != null)
+- return;
+- int len = 7;
+- byte[] profileData = null;
+- if (profile != null) {
+- profileData = profile.getData();
+- len += profileData.length;
+- }
+-
+- data = new byte[len];
+-
+- data[0] = (byte)method;
+- data[1] = (byte)precedence;
+- data[2] = (byte)approximation;
+-
+- copyInt(data, 3, ecs);
+-
+- if (profile != null)
+- System.arraycopy(profileData, 0, data, 7, len - 7);
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ComponentMappingBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ComponentMappingBox.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ComponentMappingBox.java 2005-02-11 00:01:32.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ComponentMappingBox.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,181 +0,0 @@
+-/*
+- * $RCSfile: ComponentMappingBox.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:32 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import javax.imageio.metadata.IIOInvalidTreeException;
+-import javax.imageio.metadata.IIOMetadataNode;
+-import org.w3c.dom.Node;
+-import org.w3c.dom.NodeList;
+-
+-/** This class is defined to represent a Color Specification Box of JPEG JP2
+- * file format. A Channel Definition Box has a length, and a fixed type
+- * of "cmap". This box exists if and only is a PaletteBox exists. Its
+- * content defines the type LUT output components and their mapping to the
+- * color component.
+- */
+-public class ComponentMappingBox extends Box {
+- /** The data elements. */
+- private short[] components;
+- private byte[] type;
+- private byte[] map;
+-
+- /** Constructs a ComponentMappingBox
from the provided
+- * content byte array.
+- */
+- public ComponentMappingBox(byte[] data) {
+- super(8 + data.length, 0x636D6170, data);
+- }
+-
+- /** Constructs a ComponentMappingBox
from the provided
+- * component mapping.
+- */
+- public ComponentMappingBox(short[] comp, byte[] t, byte[] m) {
+- super(8 + (comp.length << 2), 0x636D6170, null);
+- this.components = comp;
+- this.type = t;
+- this.map = m;
+- }
+-
+- /** Constructs a ComponentMappingBox
based on the provided
+- * org.w3c.dom.Node
.
+- */
+- public ComponentMappingBox(Node node) throws IIOInvalidTreeException {
+- super(node);
+- NodeList children = node.getChildNodes();
+- int len = children.getLength() / 3;
+- components = new short[len];
+- type = new byte[len];
+- map = new byte[len];
+-
+- len *= 3;
+- int index = 0;
+-
+- for (int i = 0; i < len; i++) {
+- Node child = children.item(i);
+- String name = child.getNodeName();
+-
+- if ("Component".equals(name)) {
+- components[index] = Box.getShortElementValue(child);
+- }
+-
+- if ("ComponentType".equals(name)) {
+- type[index] = Box.getByteElementValue(child);
+- }
+-
+- if ("ComponentAssociation".equals(name)) {
+- map[index++] = Box.getByteElementValue(child);
+- }
+- }
+- }
+-
+- /** Parse the component mapping from the provided content data array. */
+- protected void parse(byte[] data) {
+- int len = data.length / 4;
+- components = new short[len];
+- type = new byte[len];
+- map = new byte[len];
+-
+- for (int i = 0, j = 0; i < len; i++) {
+- components[i] =
+- (short)(((data[j++] & 0xFF) << 8) | (data[j++] & 0xFF));
+- type[i] = data[j++];
+- map[i] = data[j++];
+- }
+- }
+-
+- /** Creates an IIOMetadataNode
from this component mapping
+- * box. The format of this node is defined in the XML dtd and xsd
+- * for the JP2 image file.
+- */
+- public IIOMetadataNode getNativeNode() {
+- IIOMetadataNode node = new IIOMetadataNode(Box.getName(getType()));
+- setDefaultAttributes(node);
+-
+- for (int i = 0; i < components.length; i++) {
+- IIOMetadataNode child = new IIOMetadataNode("Component");
+- Short obj = new Short(components[i]);
+- child.setUserObject(new Short(components[i]));
+- child.setNodeValue("" + components[i]);
+- node.appendChild(child);
+-
+- child = new IIOMetadataNode("ComponentType");
+- child.setUserObject(new Byte(type[i]));
+- child.setNodeValue("" + type[i]);
+- node.appendChild(child);
+-
+- child = new IIOMetadataNode("ComponentAssociation");
+- child.setUserObject(new Byte(map[i]));
+- child.setNodeValue("" + map[i]);
+- node.appendChild(child);
+- }
+-
+- return node;
+- }
+-
+- public short[] getComponent() {
+- return components;
+- }
+-
+- public byte[] getComponentType() {
+- return type;
+- }
+-
+- public byte[] getComponentAssociation() {
+- return map;
+- }
+-
+- protected void compose() {
+- if (data != null)
+- return;
+- data = new byte[type.length << 2];
+-
+- for (int i = 0, j = 0; i < type.length; i++) {
+- data[j++] = (byte)(components[i] >> 8);
+- data[j++] = (byte)(components[i] & 0xFF);
+- data[j++] = type[i];
+- data[j++] = map[i];
+- }
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/DataEntryURLBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/DataEntryURLBox.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/DataEntryURLBox.java 2005-02-11 00:01:32.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/DataEntryURLBox.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,154 +0,0 @@
+-/*
+- * $RCSfile: DataEntryURLBox.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:32 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import javax.imageio.metadata.IIOInvalidTreeException;
+-import javax.imageio.metadata.IIOMetadataNode;
+-import org.w3c.dom.Node;
+-import org.w3c.dom.NodeList;
+-
+-/** This class is defined to represent a Data Entry URL Box of JPEG JP2
+- * file format. A Data Entry URL Box has a length, and a fixed type
+- * of "url ". Its content are a one-byte version, a three-byte flags and
+- * a URL pertains to the UUID List box within its UUID Info superbox.
+- */
+-public class DataEntryURLBox extends Box {
+- /** Cache the element names for this box's xml definition */
+- private static String[] elementNames = {"Version", "Flags", "URL"};
+-
+- /** This method will be called by the getNativeNodeForSimpleBox of the
+- * class Box to get the element names.
+- */
+- public static String[] getElementNames() {
+- return elementNames;
+- }
+-
+- /** The element values. */
+- private byte version;
+- private byte[] flags;
+- private String url;
+-
+- /** Constructs a DataEntryURLBox
from its content data. */
+- public DataEntryURLBox(byte[] data) {
+- super(8 + data.length, 0x75726C20, data);
+- }
+-
+- /** Constructs a DataEntryURLBox
from its data elements. */
+- public DataEntryURLBox(byte version, byte[] flags, String url) {
+- super(12 + url.length(), 0x75726C20, null);
+- this.version = version;
+- this.flags = flags;
+- this.url = url;
+- }
+-
+- /** Constructs a DataEntryURLBox
from a Node. */
+- public DataEntryURLBox(Node node) throws IIOInvalidTreeException {
+- super(node);
+- NodeList children = node.getChildNodes();
+-
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+- String name = child.getNodeName();
+-
+- if ("Version".equals(name)) {
+- version = Box.getByteElementValue(child);
+- }
+-
+- if ("Flags".equals(name)) {
+- flags = Box.getByteArrayElementValue(child);
+- }
+-
+- if ("URL".equals(name)) {
+- url = Box.getStringElementValue(child);
+- }
+- }
+- }
+-
+- /** Parses the content of this box from its content byte array. */
+- protected void parse(byte[] data) {
+- version = data[0];
+- flags = new byte[3];
+- flags[0] = data[1];
+- flags[1] = data[2];
+- flags[2] = data[3];
+-
+- url = new String(data, 4, data.length - 4);
+- }
+-
+- /** Creates an IIOMetadataNode
from this data entry URL
+- * box. The format of this node is defined in the XML dtd and xsd
+- * for the JP2 image file.
+- */
+- public IIOMetadataNode getNativeNode() {
+- return getNativeNodeForSimpleBox();
+- }
+-
+- /** Returns the Version
data element. */
+- public byte getVersion() {
+- return version;
+- }
+-
+- /** Returns the Flags
data element. */
+- public byte[] getFlags() {
+- return flags;
+- }
+-
+- /** Returns the URL
data element. */
+- public String getURL() {
+- return url;
+- }
+-
+- protected void compose() {
+- if (data != null)
+- return;
+- data = new byte[4 + url.length()];
+-
+- data[0] = version;
+- data[1] = flags[0];
+- data[2] = flags[1];
+- data[3] = flags[2];
+- System.arraycopy(url.getBytes(), 0, data, 4, url.length());
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/FileTypeBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/FileTypeBox.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/FileTypeBox.java 2005-02-11 00:01:32.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/FileTypeBox.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,174 +0,0 @@
+-/*
+- * $RCSfile: FileTypeBox.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:32 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import javax.imageio.metadata.IIOInvalidTreeException;
+-import javax.imageio.metadata.IIOMetadataNode;
+-import org.w3c.dom.Node;
+-import org.w3c.dom.NodeList;
+-
+-/** This class is defined to represent a File Type Box of JPEG JP2 file
+- * format. A File Type Box has a length, and a fixed type of "ftyp".
+- *
+- * The content of a file type box contains the brand ("jp2 " for JP2 file",
+- * the minor version (0 for JP2 file format), and a compatibility list (one of
+- * which should be "jp2 " if brand is not "jp2 ".)
+- */
+-public class FileTypeBox extends Box {
+- /** Cache the element names for this box's xml definition */
+- private static String[] elementNames = {"Brand",
+- "MinorVersion",
+- "CompatibilityList"};
+-
+- /** This method will be called by the getNativeNodeForSimpleBox of the
+- * class Box to get the element names.
+- */
+- public static String[] getElementNames() {
+- return elementNames;
+- }
+-
+- /** The element values. */
+- private int brand;
+- private int minorVersion;
+- private int[] compatibility;
+-
+- /** Constructs a FileTypeBox
from the provided brand, minor
+- * version and compatibility list.
+- */
+- public FileTypeBox(int br, int minorVersion, int[] comp) {
+- super(16 + (comp == null ? 0 : (comp.length << 2)), 0x66747970, null);
+- this.brand = br;
+- this.minorVersion = minorVersion;
+- this.compatibility = comp;
+- }
+-
+- /** Constructs a FileTypeBox
from the provided byte array.
+- */
+- public FileTypeBox(byte[] data) {
+- super(8 + data.length, 0x66747970, data);
+- }
+-
+- /** Constructs a FileTypeBox
from
+- * org.w3c.dom.Node
.
+- */
+- public FileTypeBox(Node node) throws IIOInvalidTreeException {
+- super(node);
+- NodeList children = node.getChildNodes();
+-
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+- String name = child.getNodeName();
+-
+- if ("Brand".equals(name)) {
+- brand = Box.getIntElementValue(child);
+- }
+-
+- if ("MinorVersion".equals(name)) {
+- minorVersion = Box.getIntElementValue(child);
+- }
+-
+- if ("CompatibilityList".equals(name)) {
+- compatibility = Box.getIntArrayElementValue(child);
+- }
+- }
+- }
+-
+- /** Returns the brand of this file type box. */
+- public int getBrand() {
+- return brand;
+- }
+-
+- /** Returns the minor version of this file type box. */
+- public int getMinorVersion() {
+- return minorVersion;
+- }
+-
+- /** Returns the compatibilty list of this file type box. */
+- public int[] getCompatibilityList() {
+- return compatibility;
+- }
+-
+- /** Creates an IIOMetadataNode
from this file type box.
+- * The format of this node is defined in the XML dtd and xsd
+- * for the JP2 image file.
+- */
+- public IIOMetadataNode getNativeNode() {
+- return getNativeNodeForSimpleBox();
+- }
+-
+- protected void parse(byte[] data) {
+- if (data == null)
+- return;
+- brand = ((data[0] & 0xFF) << 24) | ((data[1] & 0xFF) << 16) |
+- ((data[2] & 0xFF) << 8) | (data[3] & 0xFF);
+-
+- minorVersion = ((data[4] & 0xFF) << 24) | ((data[5] & 0xFF) << 16) |
+- ((data[6] & 0xFF) << 8) | (data[7] & 0xFF);
+-
+- int len = (data.length - 8) / 4;
+- if (len > 0) {
+- compatibility = new int[len];
+- for (int i = 0, j = 8; i < len; i++, j += 4)
+- compatibility[i] = ((data[j] & 0xFF) << 24) |
+- ((data[j+1] & 0xFF) << 16) |
+- ((data[j+2] & 0xFF) << 8) |
+- (data[j+3] & 0xFF);
+- }
+- }
+-
+- protected void compose() {
+- if (data != null)
+- return;
+- data =
+- new byte[8 +
+- (compatibility != null ? (compatibility.length << 2) : 0)];
+-
+- copyInt(data, 0, brand);
+- copyInt(data, 4, minorVersion);
+- if (compatibility != null)
+- for (int i = 0, j = 8; i < compatibility.length; i++, j += 4)
+- copyInt(data, j, compatibility[i]);
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/HeaderBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/HeaderBox.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/HeaderBox.java 2005-02-11 00:01:32.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/HeaderBox.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,218 +0,0 @@
+-/*
+- * $RCSfile: HeaderBox.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:32 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import javax.imageio.metadata.IIOInvalidTreeException;
+-import javax.imageio.metadata.IIOMetadataNode;
+-import org.w3c.dom.Node;
+-import org.w3c.dom.NodeList;
+-
+-/** This class is defined to represent an Image Header Box of JPEG JP2 file
+- * format. An Image Header Box has a length, and a fixed type of "ihdr".
+- *
+- * The content of an image header box contains the width/height, number of
+- * image components, the bit depth (coded with sign/unsign information),
+- * the compression type (7 for JP2 file), the flag to indicate the color
+- * space is known or not, and a flag to indicate whether the intellectual
+- * property information included in this file.
+- */
+-public class HeaderBox extends Box {
+- /** Cache the element names for this box's xml definition */
+- private static String[] elementNames = {"Height",
+- "Width",
+- "NumComponents",
+- "BitDepth",
+- "CompressionType",
+- "UnknownColorspace",
+- "IntellectualProperty"};
+-
+- /** This method will be called by the getNativeNodeForSimpleBox of the
+- * class Box to get the element names.
+- */
+- public static String[] getElementNames() {
+- return elementNames;
+- }
+-
+- /** The element values. */
+- private int width;
+- private int height;
+- private short numComp;
+- private byte bitDepth;
+- private byte compressionType;
+- private byte unknownColor;
+- private byte intelProp;
+-
+- /** Create an Image Header Box from the element values. */
+- public HeaderBox(int height, int width, int numComp, int bitDepth,
+- int compressionType, int unknownColor, int intelProp) {
+- super(22, 0x69686472, null);
+- this.height = height;
+- this.width = width;
+- this.numComp = (short)numComp;
+- this.bitDepth = (byte)bitDepth;
+- this.compressionType = (byte)compressionType;
+- this.unknownColor = (byte)unknownColor;
+- this.intelProp = (byte)intelProp;
+- }
+-
+- /** Create an Image Header Box using the content data. */
+- public HeaderBox(byte[] data) {
+- super(8 + data.length, 0x69686472, data);
+- }
+-
+- /** Constructs an Image Header Box from a Node. */
+- public HeaderBox(Node node) throws IIOInvalidTreeException {
+- super(node);
+- NodeList children = node.getChildNodes();
+-
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+- String name = child.getNodeName();
+-
+- if ("Height".equals(name)) {
+- height = Box.getIntElementValue(child);
+- }
+-
+- if ("Width".equals(name)) {
+- width = Box.getIntElementValue(child);
+- }
+-
+- if ("NumComponents".equals(name)) {
+- numComp = Box.getShortElementValue(child);
+- }
+-
+- if ("BitDepth".equals(name)) {
+- bitDepth = Box.getByteElementValue(child);
+- }
+-
+- if ("CompressionType".equals(name)) {
+- compressionType = Box.getByteElementValue(child);
+- }
+-
+- if ("UnknownColorspace".equals(name)) {
+- unknownColor = Box.getByteElementValue(child);
+- }
+-
+- if ("IntellectualProperty".equals(name)) {
+- intelProp = Box.getByteElementValue(child);
+- }
+- }
+- }
+-
+- /** Parse the data elements from the byte array of the content. */
+- protected void parse(byte[] data) {
+- height = ((data[0] & 0xFF) << 24) |
+- ((data[1] & 0xFF) << 16) |
+- ((data[2] & 0xFF) << 8) |
+- (data[3]& 0xFF);
+- width = ((data[4] & 0xFF) << 24) |
+- ((data[5] & 0xFF) << 16) |
+- ((data[6] & 0xFF) << 8) |
+- (data[7] & 0xFF);
+- numComp = (short)(((data[8] & 0xFF) << 8) | (data[9] & 0xFF));
+- bitDepth = data[10];
+- compressionType = data[11];
+- unknownColor = data[12];
+- intelProp = data[13];
+- }
+-
+- /** Returns the height of the image. */
+- public int getHeight() {
+- return height;
+- }
+-
+- /** Returns the width of the image. */
+- public int getWidth() {
+- return width;
+- }
+-
+- /** Returns the number of image components. */
+- public short getNumComponents() {
+- return numComp;
+- }
+-
+- /** Returns the compression type. */
+- public byte getCompressionType() {
+- return compressionType;
+- }
+-
+- /** Returns the bit depth for all the image components. */
+- public byte getBitDepth() {
+- return bitDepth;
+- }
+-
+- /** Returns the UnknowColorspace
flag. */
+- public byte getUnknownColorspace() {
+- return unknownColor;
+- }
+-
+- /** Returns the IntellectualProperty
flag. */
+- public byte getIntellectualProperty() {
+- return intelProp;
+- }
+-
+- /** Creates an IIOMetadataNode
from this image header box.
+- * The format of this node is defined in the XML dtd and xsd
+- * for the JP2 image file.
+- */
+- public IIOMetadataNode getNativeNode() {
+- return getNativeNodeForSimpleBox();
+- }
+-
+- protected void compose() {
+- if (data != null)
+- return;
+- data = new byte[14];
+- copyInt(data, 0, height);
+- copyInt(data, 4, width);
+-
+- data[8] = (byte)(numComp >> 8);
+- data[9] = (byte)(numComp & 0xFF);
+- data[10] = bitDepth;
+- data[11] = compressionType;
+- data[12] = unknownColor;
+- data[13] = intelProp;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/I18N.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/I18N.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/I18N.java 2005-02-11 00:01:32.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/I18N.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,53 +0,0 @@
+-/*
+- * $RCSfile: I18N.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:32 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import com.sun.media.imageioimpl.common.I18NImpl;
+-
+-final class I18N extends I18NImpl {
+- static String getString(String key) {
+- return getString("com.sun.media.imageioimpl.plugins.jpeg2000.I18N", key);
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/IISRandomAccessIO.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/IISRandomAccessIO.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/IISRandomAccessIO.java 2006-08-07 20:31:47.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/IISRandomAccessIO.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,235 +0,0 @@
+-/*
+- * $RCSfile: IISRandomAccessIO.java,v $
+- *
+- *
+- * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2006/08/08 00:31:47 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.io.IOException;
+-import java.nio.ByteOrder;
+-import javax.imageio.stream.ImageInputStream;
+-import jj2000.j2k.io.EndianType;
+-import jj2000.j2k.io.RandomAccessIO;
+-
+-/**
+- * A wrapper for converting an ImageInputStream
into a
+- * RandomAccessIO
. The resulting class is read-only.
+- */
+-public class IISRandomAccessIO implements RandomAccessIO {
+-
+- /** The ImageInputStream
that is wrapped */
+- private ImageInputStream iis;
+-
+- /**
+- * Creates a RandomAccessIO
instance from the supplied
+- * ImageInputStream
.
+- *
+- * @param iis The source ImageInputStream
.
+- */
+- public IISRandomAccessIO(ImageInputStream iis) {
+- if (iis == null) {
+- throw new IllegalArgumentException("iis == null!");
+- }
+- this.iis = iis;
+- }
+-
+- public void close() throws IOException {
+- iis.close();
+- }
+-
+- /**
+- * Returns the stream position clamped to a maximum of
+- * Integer.MAX_VALUE
.
+- */
+- public int getPos() throws IOException {
+- long pos = iis.getStreamPosition();
+- return pos > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)pos;
+- }
+-
+- public void seek(int off) throws IOException {
+- iis.seek(off);
+- }
+-
+- /**
+- * Returns the length of the data stream.
+- *
+- * If the length of the ImageInputStream
is not
+- * -1
, then it is returned after being clamped to
+- * a maximum value of Integer.MAX_VALUE
. If the
+- * ImageInputStream
is -1
, the stream
+- * is read to a maximum position of Integer.MAX_VALUE
+- * and its final position is returned. The position of the stream
+- * is unchanged from the value it had prior to the call.
+- */
+- public int length() throws IOException {
+- long len = iis.length();
+-
+- // If the length is non-negative, use it.
+- if(len != -1L) {
+- return len > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)len;
+- }
+-
+- // If the length is negative, read until the stream ends.
+- iis.mark();
+- int bufLen = 1024;
+- byte[] buf = new byte[bufLen];
+- long pos = iis.getStreamPosition();
+- while(pos < Integer.MAX_VALUE) {
+- int numRead = iis.read(buf, 0, bufLen);
+- if(numRead == -1) break; // EOF
+- pos += numRead;
+- }
+- iis.reset();
+-
+- // Return the last position.
+- return pos > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)pos;
+- }
+-
+- public int read() throws IOException {
+- return iis.read();
+- }
+-
+- public void readFully(byte b[], int off, int n) throws IOException {
+- iis.readFully(b, off, n);
+- }
+-
+- public int getByteOrdering() {
+- return iis.getByteOrder() == ByteOrder.BIG_ENDIAN ?
+- EndianType.BIG_ENDIAN : EndianType.LITTLE_ENDIAN;
+- }
+-
+- public byte readByte() throws IOException {
+- return iis.readByte();
+- }
+-
+- public int readUnsignedByte() throws IOException {
+- return iis.readUnsignedByte();
+- }
+-
+- public short readShort() throws IOException {
+- return iis.readShort();
+- }
+-
+- public int readUnsignedShort() throws IOException {
+- return iis.readUnsignedShort();
+- }
+-
+- public int readInt() throws IOException {
+- return iis.readInt();
+- }
+-
+- public long readUnsignedInt() throws IOException {
+- return iis.readUnsignedInt();
+- }
+-
+- public long readLong() throws IOException {
+- return iis.readLong();
+- }
+-
+- public float readFloat() throws IOException {
+- return iis.readFloat();
+- }
+-
+- public double readDouble() throws IOException {
+- return iis.readDouble();
+- }
+-
+- public int skipBytes(int n) throws IOException {
+- return iis.skipBytes(n);
+- }
+-
+- /**
+- * A null operation as writing is not supported.
+- */
+- public void flush() {
+- // Intentionally empty.
+- }
+-
+- /**
+- * Throws an IOException
as writing is not supported.
+- */
+- public void write(int b) throws IOException {
+- throw new IOException("Writing is not supported!");
+- }
+-
+- /**
+- * Throws an IOException
as writing is not supported.
+- */
+- public void writeByte(int v) throws IOException {
+- throw new IOException("Writing is not supported!");
+- }
+-
+- /**
+- * Throws an IOException
as writing is not supported.
+- */
+- public void writeShort(int v) throws IOException {
+- throw new IOException("Writing is not supported!");
+- }
+-
+- /**
+- * Throws an IOException
as writing is not supported.
+- */
+- public void writeInt(int v) throws IOException {
+- throw new IOException("Writing is not supported!");
+- }
+-
+- /**
+- * Throws an IOException
as writing is not supported.
+- */
+- public void writeLong(long v) throws IOException {
+- throw new IOException("Writing is not supported!");
+- }
+-
+- /**
+- * Throws an IOException
as writing is not supported.
+- */
+- public void writeFloat(float v) throws IOException {
+- throw new IOException("Writing is not supported!");
+- }
+-
+- /**
+- * Throws an IOException
as writing is not supported.
+- */
+- public void writeDouble(double v) throws IOException {
+- throw new IOException("Writing is not supported!");
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ImageInputStreamWrapper.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ImageInputStreamWrapper.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ImageInputStreamWrapper.java 2005-02-11 00:01:32.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ImageInputStreamWrapper.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,104 +0,0 @@
+-/*
+- * $RCSfile: ImageInputStreamWrapper.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:32 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.io.InputStream;
+-import java.io.IOException;
+-import javax.imageio.stream.ImageInputStream;
+-
+-/**
+- * This class is designed to wrap a ImageInputStream into
+- * a InputStream
. The reason is that ImageInputStream
+- * implements DataInput
but doesn't extend
+- * InputStream
. However, the JJ2000 JPEG 2000 packages accepts
+- * a InputStream
when reads a JPEG 2000 image file.
+- */
+-public class ImageInputStreamWrapper extends InputStream {
+-
+- /** The ImageInputStream
to be wrapped. */
+- private ImageInputStream src;
+-
+- /** Constructs an ImageInputStreamWrapper
from the provided
+- * ImageInputStream
.
+- *
+- * @param src The ImageInputStream
to be wrapped.
+- */
+- public ImageInputStreamWrapper(ImageInputStream src) {
+- this.src = src;
+- }
+-
+- // Override the methods defined in InputStream
+- public int read() throws IOException {
+- return src.read();
+- }
+-
+- public void close() throws IOException {
+- src.close();
+- }
+-
+- public synchronized void mark(int readlimit) {
+- src.mark();
+- }
+-
+- public boolean markSupported() {
+- return true;
+- }
+-
+- public int read(byte b[]) throws IOException {
+- return src.read(b, 0, b.length);
+- }
+-
+- public int read(byte b[], int off, int len) throws IOException {
+- return src.read(b, off, len);
+- }
+-
+- public synchronized void reset() throws IOException {
+- src.reset();
+- }
+-
+- public long skip(long n) throws IOException {
+- return src.skipBytes(n);
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderCodecLib.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderCodecLib.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderCodecLib.java 2006-09-29 16:19:55.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderCodecLib.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,471 +0,0 @@
+-/*
+- * $RCSfile: J2KImageReaderCodecLib.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.4 $
+- * $Date: 2006/09/29 20:19:55 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import com.sun.media.imageio.plugins.jpeg2000.J2KImageReadParam;
+-
+-import java.awt.Point;
+-import java.awt.image.ColorModel;
+-import java.awt.image.Raster;
+-import java.awt.image.RenderedImage;
+-import java.awt.image.SampleModel;
+-import java.awt.image.WritableRaster;
+-import java.io.IOException;
+-import java.util.Hashtable;
+-
+-import javax.imageio.IIOException;
+-import javax.imageio.ImageReader;
+-import javax.imageio.ImageReadParam;
+-import javax.imageio.ImageTypeSpecifier;
+-import javax.imageio.metadata.IIOMetadata;
+-import javax.imageio.spi.ImageReaderSpi;
+-import javax.imageio.stream.ImageInputStream;
+-
+-import java.util.ArrayList;
+-import java.util.Iterator;
+-import javax.imageio.metadata.IIOMetadata;
+-import java.awt.image.BufferedImage;
+-
+-import com.sun.media.imageioimpl.common.SimpleRenderedImage;
+-
+-import com.sun.medialib.codec.jp2k.Decoder;
+-import com.sun.medialib.codec.jp2k.Size;
+-import com.sun.medialib.codec.jiio.*;
+-
+-public class J2KImageReaderCodecLib extends ImageReader {
+- /** Wrapper for the protected method processImageUpdate
+- * So it can be access from the classes which are not in
+- * ImageReader
hierachy.
+- */
+- public void processImageUpdateWrapper(BufferedImage theImage,
+- int minX, int minY,
+- int width, int height,
+- int periodX, int periodY,
+- int[] bands) {
+- processImageUpdate(theImage,
+- minX, minY,
+- width, height,
+- periodX, periodY,
+- bands);
+- }
+-
+- /** Wrapper for the protected method processImageProgress
+- * So it can be access from the classes which are not in
+- * ImageReader
hierachy.
+- */
+- public void processImageProgressWrapper(float percentageDone) {
+- processImageProgress(percentageDone);
+- }
+-
+- /** The input stream where reads from */
+- private ImageInputStream iis = null;
+-
+- /** Stream position when setInput() was called. */
+- private long streamPosition0;
+-
+- /** Indicates whether the header is read. */
+- private boolean gotHeader = false;
+-
+- /** The image width. */
+- private int width = -1;
+-
+- /** The image height. */
+- private int height = -1;
+-
+- /** The image tile width. */
+- private int tileWidth = -1;
+-
+- /** The image tile height. */
+- private int tileHeight = -1;
+-
+- /** The image tile grid X offset. */
+- private int tileGridXOffset = 0;
+-
+- /** The image tile grid Y offset. */
+- private int tileGridYOffset = 0;
+-
+- /** Image metadata, valid for the imageMetadataIndex only. */
+- private J2KMetadata imageMetadata = null;
+-
+- /** The RenderedImage decoded from the stream. */
+- SimpleRenderedImage image = null;
+-
+- public J2KImageReaderCodecLib(ImageReaderSpi originator) {
+- super(originator);
+- }
+-
+- /** Overrides the method defined in the superclass. */
+- public void setInput(Object input,
+- boolean seekForwardOnly,
+- boolean ignoreMetadata) {
+- super.setInput(input, seekForwardOnly, ignoreMetadata);
+- this.ignoreMetadata = ignoreMetadata;
+- iis = (ImageInputStream) input; // Always works
+- iis.mark(); // Mark the initial position.
+- imageMetadata = null;
+- try {
+- this.streamPosition0 = iis.getStreamPosition();
+- } catch(IOException e) {
+- // XXX ignore
+- }
+- }
+-
+- public ImageReadParam getDefaultReadParam() {
+- return new J2KImageReadParam();
+- }
+- public int getNumImages(boolean allowSearch) throws java.io.IOException {
+- if(input == null) {
+- throw new IllegalStateException(I18N.getString("J2KImageReader6"));
+- } else if(seekForwardOnly) {
+- throw new IllegalStateException(I18N.getString("J2KImageReader7"));
+- }
+-
+- return 1;
+- }
+-
+- public Iterator getImageTypes(int imageIndex) throws java.io.IOException {
+- checkIndex(imageIndex);
+- readHeader();
+- if (image != null) {
+- ArrayList list = new ArrayList();
+- list.add(new ImageTypeSpecifier(image.getColorModel(),
+- image.getSampleModel()));
+- return list.iterator();
+- }
+- return null;
+- }
+-
+- public int getWidth(int imageIndex) throws java.io.IOException {
+- checkIndex(imageIndex);
+- readHeader();
+- return width;
+- }
+-
+- public int getHeight(int imageIndex) throws java.io.IOException {
+- checkIndex(imageIndex);
+- readHeader();
+- return height;
+- }
+-
+- public int getTileGridXOffset(int imageIndex) throws IOException {
+- checkIndex(imageIndex);
+- readHeader();
+- return tileGridXOffset;
+- }
+-
+- public int getTileGridYOffset(int imageIndex) throws IOException {
+- checkIndex(imageIndex);
+- readHeader();
+- return tileGridYOffset;
+- }
+-
+- public int getTileWidth(int imageIndex) throws IOException {
+- checkIndex(imageIndex);
+- readHeader();
+- return tileWidth;
+- }
+-
+- public int getTileHeight(int imageIndex) throws IOException {
+- checkIndex(imageIndex);
+- readHeader();
+- return tileHeight;
+- }
+-
+- /**
+- * Returns true
if the image is organized into
+- * tiles, that is, equal-sized non-overlapping rectangles.
+- *
+- * A reader plug-in may choose whether or not to expose tiling
+- * that is present in the image as it is stored. It may even
+- * choose to advertise tiling when none is explicitly present. In
+- * general, tiling should only be advertised if there is some
+- * advantage (in speed or space) to accessing individual tiles.
+- * Regardless of whether the reader advertises tiling, it must be
+- * capable of reading an arbitrary rectangular region specified in
+- * an ImageReadParam
.
+- *
+- *
A reader for which all images are guaranteed to be tiled,
+- * or are guaranteed not to be tiled, may return true
+- * or false
respectively without accessing any image
+- * data. In such cases, it is not necessary to throw an exception
+- * even if no input source has been set or the image index is out
+- * of bounds.
+- *
+- *
The default implementation just returns false
.
+- *
+- * @param imageIndex the index of the image to be queried.
+- *
+- * @return true
if the image is tiled.
+- *
+- * @exception IllegalStateException if an input source is required
+- * to determine the return value, but none has been set.
+- * @exception IndexOutOfBoundsException if an image must be
+- * accessed to determine the return value, but the supplied index
+- * is out of bounds.
+- * @exception IOException if an error occurs during reading.
+- */
+- public boolean isImageTiled(int imageIndex) throws IOException {
+- int w = getWidth(imageIndex);
+- int tw = getTileWidth(imageIndex);
+- if(tw > 0 && ((w + tw - 1)/tw) > 1) {
+- return true;
+- }
+-
+- int h = getHeight(imageIndex);
+- int th = getTileHeight(imageIndex);
+- if(th > 0 && ((h + th - 1)/th) > 1) {
+- return true;
+- }
+-
+- return false;
+- }
+-
+- public IIOMetadata getStreamMetadata() throws java.io.IOException {
+- return null;
+- }
+-
+- public IIOMetadata getImageMetadata(int imageIndex) throws
+- java.io.IOException {
+- if (ignoreMetadata)
+- return null;
+-
+- checkIndex(imageIndex);
+-
+- if (imageMetadata == null) {
+- try {
+- iis.reset(); // Reset to initial position.
+- iis.mark(); // Re-mark initial position.
+- if (image == null ||
+- !(image instanceof J2KRenderedImageCodecLib))
+- image = new J2KRenderedImageCodecLib(iis, this, null);
+- imageMetadata =
+- ((J2KRenderedImageCodecLib)image).readImageMetadata();
+- } catch(IOException ioe) {
+- throw ioe;
+- } catch(RuntimeException re) {
+- throw re;
+- } finally {
+- iis.reset(); // Reset to initial position.
+- iis.mark(); // Re-mark initial position.
+- }
+- }
+- return imageMetadata;
+- }
+-
+- public boolean isRandomAccessEasy(int imageIndex) throws IOException {
+- // No check done because neither input source nor image is
+- // required to determine the return value.
+- return true;
+- }
+-
+- public RenderedImage readAsRenderedImage(int imageIndex,
+- ImageReadParam param)
+- throws java.io.IOException {
+- checkIndex(imageIndex);
+- if (param == null)
+- param = getDefaultReadParam();
+- clearAbortRequest();
+- processImageStarted(0);
+-
+- if(param instanceof J2KImageReadParam &&
+- ((J2KImageReadParam)param).getResolution() >= 0) {
+- // XXX Workaround for java.sun.com change request 5089981:
+- // fall back to Java reader for lower resolution levels.
+- // This code should be removed when this problem is fixed
+- // in the codecLib JPEG2000 decoder.
+- ImageReader jreader = new J2KImageReader(null);
+- iis.seek(streamPosition0);
+- jreader.setInput(iis);
+- image =
+- (SimpleRenderedImage)jreader.readAsRenderedImage(imageIndex,
+- param);
+- } else {
+- image = new J2KRenderedImageCodecLib(iis,
+- this,
+- param);
+- }
+- if (abortRequested())
+- processReadAborted();
+- else
+- processImageComplete();
+- return image;
+- }
+-
+- public BufferedImage read(int imageIndex,
+- ImageReadParam param) throws java.io.IOException {
+- checkIndex(imageIndex);
+- clearAbortRequest();
+- if (param == null)
+- param = getDefaultReadParam();
+- processImageStarted(imageIndex);
+-
+- if(param instanceof J2KImageReadParam &&
+- ((J2KImageReadParam)param).getResolution() >= 0) {
+- // XXX Workaround for java.sun.com change request 5089981:
+- // fall back to Java reader for lower resolution levels.
+- // This code should be removed when this problem is fixed
+- // in the codecLib JPEG2000 decoder.
+- ImageReader jreader = new J2KImageReader(null);
+- iis.seek(streamPosition0);
+- jreader.setInput(iis);
+- if (abortRequested())
+- processReadAborted();
+- else
+- processImageComplete();
+- return jreader.read(imageIndex, param);
+- }
+-
+- BufferedImage bi = param.getDestination();
+- iis.reset(); // Reset to initial position.
+- iis.mark(); // Re-mark initial position.
+- // XXX Need to add a try-catch IOException block and reset/mark iis.
+- image = new J2KRenderedImageCodecLib(iis,
+- this,
+- param);
+- J2KRenderedImageCodecLib jclibImage = (J2KRenderedImageCodecLib)image;
+- Point offset = param.getDestinationOffset();
+- WritableRaster raster;
+-
+- if (bi == null) {
+- ColorModel colorModel = jclibImage.getColorModel();
+- SampleModel sampleModel = jclibImage.getSampleModel();
+-
+- // If the destination type is specified, use the color model of it.
+- ImageTypeSpecifier type = param.getDestinationType();
+- if (type != null)
+- colorModel = type.getColorModel();
+-
+- raster = Raster.createWritableRaster(
+- sampleModel.createCompatibleSampleModel(jclibImage.getMinX()+
+- jclibImage.getWidth(),
+- jclibImage.getMinY() +
+- jclibImage.getHeight()),
+- new Point(0, 0));
+-
+- bi = new BufferedImage(colorModel,
+- raster,
+- colorModel != null ?
+- colorModel.isAlphaPremultiplied() : false,
+- new Hashtable());
+- } else {
+- raster = bi.getWritableTile(0, 0);
+- }
+-
+- jclibImage.setDestImage(bi);
+- jclibImage.readAsRaster(raster);
+- jclibImage.clearDestImage();
+-
+- if (abortRequested())
+- processReadAborted();
+- else
+- processImageComplete();
+- return bi;
+- }
+-
+- public Raster readRaster(int imageIndex,
+- ImageReadParam param) throws IOException {
+- BufferedImage bi = read(imageIndex, param);
+- return bi.getWritableTile(0, 0);
+- }
+-
+- public void readHeader() throws java.io.IOException {
+- if (gotHeader)
+- return;
+-
+- try {
+- iis.reset(); // Reset to initial position.
+- iis.mark(); // Re-mark initial position.
+-
+- if (image == null)
+- image = new J2KRenderedImageCodecLib(iis, this, null);
+-
+- this.width = image.getWidth();
+- this.height = image.getHeight();
+- this.tileWidth = image.getTileWidth();
+- this.tileHeight = image.getTileHeight();
+- this.tileGridXOffset = image.getTileGridXOffset();
+- this.tileGridYOffset = image.getTileGridYOffset();
+- } catch(IOException ioe) {
+- throw ioe;
+- } catch(RuntimeException re) {
+- throw re;
+- } finally {
+- iis.reset(); // Reset to initial position.
+- iis.mark(); // Re-mark initial position.
+- }
+-
+- this.gotHeader = true;
+- }
+-
+- private void checkIndex(int imageIndex) {
+- if(input == null) {
+- throw new IllegalStateException(I18N.getString("J2KImageReader6"));
+- }
+- if (imageIndex != 0) {
+- throw new IndexOutOfBoundsException(I18N.getString("J2KImageReader4"));
+- }
+- }
+-
+- /** This method wraps the protected method abortRequested
+- * to allow the abortions be monitored by J2KReadState
.
+- */
+- public boolean getAbortRequest() {
+- return abortRequested();
+- }
+-
+- public void reset() {
+- super.reset();
+- iis = null;
+- gotHeader = false;
+- width = -1;
+- height = -1;
+- tileWidth = -1;
+- tileHeight = -1;
+- tileGridXOffset = 0;
+- tileGridYOffset = 0;
+- imageMetadata = null;
+- image = null;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderCodecLibSpi.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderCodecLibSpi.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderCodecLibSpi.java 2006-03-31 14:43:39.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderCodecLibSpi.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,171 +0,0 @@
+-/*
+- * $RCSfile: J2KImageReaderCodecLibSpi.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.2 $
+- * $Date: 2006/03/31 19:43:39 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.util.Locale;
+-import javax.imageio.spi.ImageReaderSpi;
+-import javax.imageio.stream.ImageInputStream;
+-import javax.imageio.spi.IIORegistry;
+-import javax.imageio.spi.ServiceRegistry;
+-import java.io.IOException;
+-import javax.imageio.ImageReader;
+-import javax.imageio.IIOException;
+-
+-import com.sun.media.imageioimpl.common.PackageUtil;
+-
+-public class J2KImageReaderCodecLibSpi extends ImageReaderSpi {
+-
+- private static String [] writerSpiNames =
+- {"com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriterCodecLibSpi"};
+- private static String[] formatNames =
+- {"jpeg 2000", "JPEG 2000", "jpeg2000", "JPEG2000"};
+- private static String[] extensions =
+- {"jp2"}; // Should add jpx or jpm
+- private static String[] mimeTypes = {"image/jp2", "image/jpeg2000"};
+- private boolean registered = false;
+-
+- public J2KImageReaderCodecLibSpi() {
+- super(PackageUtil.getVendor(),
+- PackageUtil.getVersion(),
+- formatNames,
+- extensions,
+- mimeTypes,
+- "com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReaderCodecLib",
+- STANDARD_INPUT_TYPE,
+- writerSpiNames,
+- false,
+- null, null,
+- null, null,
+- true,
+- "com_sun_media_imageio_plugins_jpeg2000_image_1.0",
+- "com.sun.media.imageioimpl.plugins.jpeg2000.J2KMetadataFormat",
+- null, null);
+- }
+-
+- public void onRegistration(ServiceRegistry registry,
+- Class category) {
+- if (registered) {
+- return;
+- }
+-
+- registered = true;
+-
+- // Branch based on codecLib availability.
+- if(!PackageUtil.isCodecLibAvailable()) {
+- // Deregister provider.
+- registry.deregisterServiceProvider(this);
+- } else {
+- // Set pairwise ordering to give codecLib reader precedence.
+- Class javaReaderSPIClass = null;
+- try {
+- javaReaderSPIClass =
+- Class.forName("com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReaderSpi");
+- } catch(Throwable t) {
+- // Ignore it.
+- }
+-
+- if(javaReaderSPIClass != null) {
+- Object javaReaderSPI =
+- registry.getServiceProviderByClass(javaReaderSPIClass);
+- if(javaReaderSPI != null) {
+- registry.setOrdering(category, this, javaReaderSPI);
+- }
+- }
+- }
+- }
+-
+- public String getDescription(Locale locale) {
+- String desc = PackageUtil.getSpecificationTitle() +
+- " natively-accelerated JPEG 2000 Image Reader";
+- return desc;
+- }
+-
+- public boolean canDecodeInput(Object source) throws IOException {
+- if (!(source instanceof ImageInputStream)) {
+- return false;
+- }
+-
+- ImageInputStream stream = (ImageInputStream)source;
+-
+- //fix of 4938421
+- stream.mark();
+- int marker = (stream.read() << 8) | stream.read();
+-
+- if (marker == 0xFF4F) {
+- stream.reset();
+- return true;
+- }
+-
+- stream.reset();
+- stream.mark();
+- byte[] b = new byte[12];
+- stream.readFully(b);
+- stream.reset();
+-
+- //Verify the signature box
+-
+- // The length of the signature box is 12
+- if (b[0] !=0 || b[1]!=0 || b[2] != 0 || b[3] != 12)
+- return false;
+-
+- // The signature box type is "jP "
+- if ((b[4] & 0xff) != 0x6A || (b[5] & 0xFF) != 0x50 ||
+- (b[6] & 0xFF) !=0x20 || (b[7] & 0xFF) != 0x20)
+- return false;
+-
+- // The signture content is 0x0D0A870A
+- if ((b[8] & 0xFF) != 0x0D || (b[9] & 0xFF) != 0x0A ||
+- (b[10] & 0xFF) != 0x87 || (b[11] &0xFF) != 0x0A)
+- return false;
+-
+- return true;
+- }
+-
+- public ImageReader createReaderInstance(Object extension)
+- throws IIOException {
+- return new J2KImageReaderCodecLib(this);
+- }
+-}
+-
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReader.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReader.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReader.java 2006-10-04 21:08:30.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReader.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,601 +0,0 @@
+-/*
+- * $RCSfile: J2KImageReader.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.7 $
+- * $Date: 2006/10/05 01:08:30 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.awt.Rectangle;
+-import java.awt.Point;
+-
+-import javax.imageio.IIOException;
+-import javax.imageio.ImageReader;
+-import javax.imageio.ImageReadParam;
+-import javax.imageio.ImageTypeSpecifier;
+-import javax.imageio.metadata.IIOMetadata;
+-import javax.imageio.spi.ImageReaderSpi;
+-import javax.imageio.stream.ImageInputStream;
+-import com.sun.media.imageio.plugins.jpeg2000.J2KImageReadParam;
+-
+-import java.awt.image.BufferedImage;
+-import java.awt.image.Raster;
+-import java.awt.image.RenderedImage;
+-
+-import java.io.*;
+-import java.util.List;
+-import java.util.Iterator;
+-import java.util.ArrayList;
+-
+-import jj2000.j2k.quantization.dequantizer.*;
+-import jj2000.j2k.wavelet.synthesis.*;
+-import jj2000.j2k.image.invcomptransf.*;
+-import jj2000.j2k.fileformat.reader.*;
+-import jj2000.j2k.codestream.reader.*;
+-import jj2000.j2k.entropy.decoder.*;
+-import jj2000.j2k.codestream.*;
+-import jj2000.j2k.decoder.*;
+-import jj2000.j2k.image.*;
+-import jj2000.j2k.util.*;
+-import jj2000.j2k.roi.*;
+-import jj2000.j2k.io.*;
+-import jj2000.j2k.*;
+-
+-/** This class is the Java Image IO plugin reader for JPEG 2000 JP2 image file
+- * format. It has the capability to load the compressed bilevel images,
+- * color-indexed byte images, or multi-band images in byte/ushort/short/int
+- * data type. It may subsample the image, select bands, clip the image,
+- * and shift the decoded image origin if the proper decoding parameter
+- * are set in the provided J2KImageReadParam
.
+- */
+-public class J2KImageReader extends ImageReader implements MsgLogger {
+- /** The input stream where reads from */
+- private ImageInputStream iis = null;
+-
+- /** Stream position when setInput() was called. */
+- private long streamPosition0;
+-
+- /** Indicates whether the header is read. */
+- private boolean gotHeader = false;
+-
+- /** The image width. */
+- private int width;
+-
+- /** The image height. */
+- private int height;
+-
+- /** Image metadata, valid for the imageMetadataIndex only. */
+- private J2KMetadata imageMetadata = null;
+-
+- /** The image index for the cached metadata. */
+- private int imageMetadataIndex = -1;
+-
+- /** The J2K HeaderDecoder defined in jj2000 packages. Used to extract image
+- * header information.
+- */
+- private HeaderDecoder hd;
+-
+- /** The J2KReadState for this reading session based on the current input
+- * and J2KImageReadParam.
+- */
+- private J2KReadState readState = null;
+-
+- /**
+- * Whether to log JJ2000 messages.
+- */
+- private boolean logJJ2000Msg = false;
+-
+- /** Wrapper for the protected method computeRegions
. So it
+- * can be access from the classes which are not in ImageReader
+- * hierarchy.
+- */
+- public static void computeRegionsWrapper(ImageReadParam param,
+- boolean allowZeroDestOffset,
+- int srcWidth,
+- int srcHeight,
+- BufferedImage image,
+- Rectangle srcRegion,
+- Rectangle destRegion) {
+- if (srcRegion == null) {
+- throw new IllegalArgumentException(I18N.getString("J2KImageReader0"));
+- }
+- if (destRegion == null) {
+- throw new IllegalArgumentException(I18N.getString("J2KImageReader1"));
+- }
+-
+- // Clip that to the param region, if there is one
+- int periodX = 1;
+- int periodY = 1;
+- int gridX = 0;
+- int gridY = 0;
+- if (param != null) {
+- Rectangle paramSrcRegion = param.getSourceRegion();
+- if (paramSrcRegion != null) {
+- srcRegion.setBounds(srcRegion.intersection(paramSrcRegion));
+- }
+- periodX = param.getSourceXSubsampling();
+- periodY = param.getSourceYSubsampling();
+- gridX = param.getSubsamplingXOffset();
+- gridY = param.getSubsamplingYOffset();
+- srcRegion.translate(gridX, gridY);
+- srcRegion.width -= gridX;
+- srcRegion.height -= gridY;
+- if(allowZeroDestOffset) {
+- destRegion.setLocation(param.getDestinationOffset());
+- } else {
+- Point destOffset = param.getDestinationOffset();
+- if(destOffset.x != 0 || destOffset.y != 0) {
+- destRegion.setLocation(param.getDestinationOffset());
+- }
+- }
+- }
+-
+- // Now clip any negative destination offsets, i.e. clip
+- // to the top and left of the destination image
+- if (destRegion.x < 0) {
+- int delta = -destRegion.x*periodX;
+- srcRegion.x += delta;
+- srcRegion.width -= delta;
+- destRegion.x = 0;
+- }
+- if (destRegion.y < 0) {
+- int delta = -destRegion.y*periodY;
+- srcRegion.y += delta;
+- srcRegion.height -= delta;
+- destRegion.y = 0;
+- }
+-
+- // Now clip the destination Region to the subsampled width and height
+- int subsampledWidth = (srcRegion.width + periodX - 1)/periodX;
+- int subsampledHeight = (srcRegion.height + periodY - 1)/periodY;
+- destRegion.width = subsampledWidth;
+- destRegion.height = subsampledHeight;
+-
+- // Now clip that to right and bottom of the destination image,
+- // if there is one, taking subsampling into account
+- if (image != null) {
+- Rectangle destImageRect = new Rectangle(0, 0,
+- image.getWidth(),
+- image.getHeight());
+- destRegion.setBounds(destRegion.intersection(destImageRect));
+- if (destRegion.isEmpty()) {
+- throw new IllegalArgumentException
+- (I18N.getString("J2KImageReader2"));
+- }
+-
+- int deltaX = destRegion.x + subsampledWidth - image.getWidth();
+- if (deltaX > 0) {
+- srcRegion.width -= deltaX*periodX;
+- }
+- int deltaY = destRegion.y + subsampledHeight - image.getHeight();
+- if (deltaY > 0) {
+- srcRegion.height -= deltaY*periodY;
+- }
+- }
+- if (srcRegion.isEmpty() || destRegion.isEmpty()) {
+- throw new IllegalArgumentException(I18N.getString("J2KImageReader3"));
+- }
+- }
+-
+- /** Wrapper for the protected method checkReadParamBandSettings
.
+- * So it can be access from the classes which are not in
+- * ImageReader
hierarchy.
+- */
+- public static void checkReadParamBandSettingsWrapper(ImageReadParam param,
+- int numSrcBands,
+- int numDstBands) {
+- checkReadParamBandSettings(param, numSrcBands, numDstBands);
+- }
+-
+- /**
+- * Convert a rectangle provided in the coordinate system of the JPEG2000
+- * reference grid to coordinates at a lower resolution level where zero
+- * denotes the lowest resolution level.
+- *
+- * @param r A rectangle in references grid coordinates.
+- * @param maxLevel The highest resolution level in the image.
+- * @param level The resolution level of the returned rectangle.
+- * @param subX The horizontal subsampling step size.
+- * @param subY The vertical subsampling step size.
+- * @return The parameter rectangle converted to a lower resolution level.
+- * @throws IllegalArgumentException if r
is null
,
+- * maxLevel
or level
is negative, or
+- * level
is greater than maxLevel
.
+- */
+- static Rectangle getReducedRect(Rectangle r, int maxLevel, int level,
+- int subX, int subY) {
+- if(r == null) {
+- throw new IllegalArgumentException("r == null!");
+- } else if(maxLevel < 0 || level < 0) {
+- throw new IllegalArgumentException("maxLevel < 0 || level < 0!");
+- } else if(level > maxLevel) {
+- throw new IllegalArgumentException("level > maxLevel");
+- }
+-
+- // At the highest level; return the parameter.
+- if(level == maxLevel && subX == 1 && subY == 1) {
+- return r;
+- }
+-
+- // Resolution divisor is step*2^(maxLevel - level).
+- int divisor = 1 << (maxLevel - level);
+- int divX = divisor*subX;
+- int divY = divisor*subY;
+-
+- // Convert upper left and lower right corners.
+- int x1 = (r.x + divX - 1)/divX;
+- int x2 = (r.x + r.width + divX - 1)/divX;
+- int y1 = (r.y + divY - 1)/divY;
+- int y2 = (r.y + r.height + divY - 1)/divY;
+-
+- // Create lower resolution rectangle and return.
+- return new Rectangle(x1, y1, x2 - x1, y2 - y1);
+- }
+-
+- /** Wrapper for the protected method processImageUpdate
+- * So it can be access from the classes which are not in
+- * ImageReader
hierarchy.
+- */
+- public void processImageUpdateWrapper(BufferedImage theImage,
+- int minX, int minY,
+- int width, int height,
+- int periodX, int periodY,
+- int[] bands) {
+- processImageUpdate(theImage,
+- minX, minY,
+- width, height,
+- periodX, periodY,
+- bands);
+- }
+-
+- /** Wrapper for the protected method processImageProgress
+- * So it can be access from the classes which are not in
+- * ImageReader
hierarchy.
+- */
+- public void processImageProgressWrapper(float percentageDone) {
+- processImageProgress(percentageDone);
+- }
+-
+- /** Constructs J2KImageReader
from the provided
+- * ImageReaderSpi
.
+- */
+- public J2KImageReader(ImageReaderSpi originator) {
+- super(originator);
+-
+- this.logJJ2000Msg = Boolean.getBoolean("jj2000.j2k.decoder.log");
+-
+- FacilityManager.registerMsgLogger(null, this);
+- }
+-
+- /** Overrides the method defined in the superclass. */
+- public void setInput(Object input,
+- boolean seekForwardOnly,
+- boolean ignoreMetadata) {
+- super.setInput(input, seekForwardOnly, ignoreMetadata);
+- this.ignoreMetadata = ignoreMetadata;
+- iis = (ImageInputStream) input; // Always works
+- imageMetadata = null;
+- try {
+- this.streamPosition0 = iis.getStreamPosition();
+- } catch(IOException e) {
+- // XXX ignore
+- }
+- }
+-
+- /** Overrides the method defined in the superclass. */
+- public int getNumImages(boolean allowSearch) throws IOException {
+- return 1;
+- }
+-
+- public int getWidth(int imageIndex) throws IOException {
+- checkIndex(imageIndex);
+- readHeader();
+- return width;
+- }
+-
+- public int getHeight(int imageIndex) throws IOException {
+- checkIndex(imageIndex);
+- readHeader();
+- return height;
+- }
+-
+- public int getTileGridXOffset(int imageIndex) throws IOException {
+- checkIndex(imageIndex);
+- readHeader();
+- return hd.getTilingOrigin(null).x;
+- }
+-
+- public int getTileGridYOffset(int imageIndex) throws IOException {
+- checkIndex(imageIndex);
+- readHeader();
+- return hd.getTilingOrigin(null).y;
+- }
+-
+- public int getTileWidth(int imageIndex) throws IOException {
+- checkIndex(imageIndex);
+- readHeader();
+- return hd.getNomTileWidth();
+- }
+-
+- public int getTileHeight(int imageIndex) throws IOException {
+- checkIndex(imageIndex);
+- readHeader();
+- return hd.getNomTileHeight();
+- }
+-
+- private void checkIndex(int imageIndex) {
+- if (imageIndex != 0) {
+- throw new IndexOutOfBoundsException(I18N.getString("J2KImageReader4"));
+- }
+- }
+-
+- public void readHeader() {
+- if (gotHeader)
+- return;
+-
+- if (readState == null) {
+- try {
+- iis.seek(streamPosition0);
+- } catch(IOException e) {
+- // XXX ignore
+- }
+-
+- readState =
+- new J2KReadState(iis,
+- new J2KImageReadParamJava(getDefaultReadParam()),
+- this);
+- }
+-
+- hd = readState.getHeader();
+- gotHeader = true;
+-
+- this.width = hd.getImgWidth();
+- this.height = hd.getImgHeight();
+- }
+-
+- public Iterator getImageTypes(int imageIndex)
+- throws IOException {
+- checkIndex(imageIndex);
+- readHeader();
+- if (readState != null) {
+- ArrayList list = new ArrayList();
+- list.add(new ImageTypeSpecifier(readState.getColorModel(),
+- readState.getSampleModel()));
+- return list.iterator();
+- }
+- return null;
+- }
+-
+- public ImageReadParam getDefaultReadParam() {
+- return new J2KImageReadParam();
+- }
+-
+- public IIOMetadata getImageMetadata(int imageIndex)
+- throws IOException {
+- checkIndex(imageIndex);
+- if (ignoreMetadata)
+- return null;
+-
+- if (imageMetadata == null) {
+- iis.mark();
+- imageMetadata = new J2KMetadata(iis, this);
+- iis.reset();
+- }
+- return imageMetadata;
+- }
+-
+- public IIOMetadata getStreamMetadata() throws IOException {
+- return null;
+- }
+-
+- public BufferedImage read(int imageIndex, ImageReadParam param)
+- throws IOException {
+- checkIndex(imageIndex);
+- clearAbortRequest();
+- processImageStarted(imageIndex);
+-
+- if (param == null)
+- param = getDefaultReadParam();
+-
+- param = new J2KImageReadParamJava(param);
+-
+- if (!ignoreMetadata) {
+- imageMetadata = new J2KMetadata();
+- iis.seek(streamPosition0);
+- readState = new J2KReadState(iis,
+- (J2KImageReadParamJava)param,
+- imageMetadata,
+- this);
+- } else {
+- iis.seek(streamPosition0);
+- readState = new J2KReadState(iis,
+- (J2KImageReadParamJava)param,
+- this);
+- }
+-
+- BufferedImage bi = readState.readBufferedImage();
+- if (abortRequested())
+- processReadAborted();
+- else
+- processImageComplete();
+- return bi;
+- }
+-
+- public RenderedImage readAsRenderedImage(int imageIndex,
+- ImageReadParam param)
+- throws IOException {
+- checkIndex(imageIndex);
+- RenderedImage ri = null;
+- clearAbortRequest();
+- processImageStarted(imageIndex);
+-
+- if (param == null)
+- param = getDefaultReadParam();
+-
+- param = new J2KImageReadParamJava(param);
+- if (!ignoreMetadata) {
+- if (imageMetadata == null)
+- imageMetadata = new J2KMetadata();
+- ri = new J2KRenderedImage(iis,
+- (J2KImageReadParamJava)param,
+- imageMetadata,
+- this);
+- }
+- else
+- ri = new J2KRenderedImage(iis, (J2KImageReadParamJava)param, this);
+- if (abortRequested())
+- processReadAborted();
+- else
+- processImageComplete();
+- return ri;
+- }
+-
+- public boolean canReadRaster() {
+- return true;
+- }
+-
+- public boolean isRandomAccessEasy(int imageIndex) throws IOException {
+- checkIndex(imageIndex);
+- return false;
+- }
+-
+- public Raster readRaster(int imageIndex,
+- ImageReadParam param) throws IOException {
+- checkIndex(imageIndex);
+- processImageStarted(imageIndex);
+- param = new J2KImageReadParamJava(param);
+-
+- if (!ignoreMetadata) {
+- imageMetadata = new J2KMetadata();
+- iis.seek(streamPosition0);
+- readState = new J2KReadState(iis,
+- (J2KImageReadParamJava)param,
+- imageMetadata,
+- this);
+- } else {
+- iis.seek(streamPosition0);
+- readState = new J2KReadState(iis,
+- (J2KImageReadParamJava)param,
+- this);
+- }
+-
+- Raster ras = readState.readAsRaster();
+- if (abortRequested())
+- processReadAborted();
+- else
+- processImageComplete();
+- return ras;
+- }
+-
+- public boolean isImageTiled(int imageIndex) {
+- checkIndex(imageIndex);
+- readHeader();
+- if (readState != null) {
+- RenderedImage image = new J2KRenderedImage(readState);
+- if (image.getNumXTiles() * image.getNumYTiles() > 0)
+- return true;
+- return false;
+- }
+- return false;
+- }
+-
+- public void reset() {
+- // reset local Java structures
+- super.reset();
+-
+- iis = null;
+- gotHeader = false;
+- imageMetadata = null;
+- readState = null;
+- System.gc();
+- }
+-
+- /** This method wraps the protected method abortRequested
+- * to allow the abortions be monitored by J2KReadState
.
+- */
+- public boolean getAbortRequest() {
+- return abortRequested();
+- }
+-
+- private ImageTypeSpecifier getImageType(int imageIndex)
+- throws IOException {
+- checkIndex(imageIndex);
+- readHeader();
+- if (readState != null) {
+- return new ImageTypeSpecifier(readState.getColorModel(),
+- readState.getSampleModel());
+- }
+- return null;
+- }
+-
+- // --- Begin jj2000.j2k.util.MsgLogger implementation ---
+- public void flush() {
+- // Do nothing.
+- }
+-
+- public void println(String str, int flind, int ind) {
+- printmsg(INFO, str);
+- }
+-
+- public void printmsg(int sev, String msg) {
+- if(logJJ2000Msg) {
+- String msgSev;
+- switch(sev) {
+- case ERROR:
+- msgSev = "ERROR";
+- break;
+- case INFO:
+- msgSev = "INFO";
+- break;
+- case LOG:
+- msgSev = "LOG";
+- break;
+- case WARNING:
+- default:
+- msgSev = "WARNING";
+- break;
+- }
+-
+- processWarningOccurred("[JJ2000 "+msgSev+"] "+msg);
+- }
+- }
+- // --- End jj2000.j2k.util.MsgLogger implementation ---
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderResources.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderResources.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderResources.java 2005-02-11 00:01:34.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderResources.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,56 +0,0 @@
+-/*
+- * $RCSfile: J2KImageReaderResources.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:34 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-public class J2KImageReaderResources {
+- static final Object[][] contents = {
+- };
+-
+- public J2KImageReaderResources() {}
+-
+- public Object[][] getContents() {
+- return contents;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderSpi.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderSpi.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderSpi.java 2006-03-31 14:43:39.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderSpi.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,167 +0,0 @@
+-/*
+- * $RCSfile: J2KImageReaderSpi.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.2 $
+- * $Date: 2006/03/31 19:43:39 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.util.Locale;
+-import javax.imageio.spi.ImageReaderSpi;
+-import javax.imageio.stream.ImageInputStream;
+-import javax.imageio.spi.IIORegistry;
+-import javax.imageio.spi.ServiceRegistry;
+-import java.io.IOException;
+-import javax.imageio.ImageReader;
+-import javax.imageio.IIOException;
+-
+-import com.sun.media.imageioimpl.common.PackageUtil;
+-
+-import com.sun.medialib.codec.jiio.Util;
+-
+-public class J2KImageReaderSpi extends ImageReaderSpi {
+-
+- private static String [] writerSpiNames =
+- {"com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriterSpi"};
+- private static String[] formatNames =
+- {"jpeg 2000", "JPEG 2000", "jpeg2000", "JPEG2000"};
+- private static String[] extensions =
+- {"jp2"}; // Should add jpx or jpm
+- private static String[] mimeTypes = {"image/jp2", "image/jpeg2000"};
+- private boolean registered = false;
+-
+- public J2KImageReaderSpi() {
+- super(PackageUtil.getVendor(),
+- PackageUtil.getVersion(),
+- formatNames,
+- extensions,
+- mimeTypes,
+- "com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReader",
+- STANDARD_INPUT_TYPE,
+- writerSpiNames,
+- false,
+- null, null,
+- null, null,
+- true,
+- "com_sun_media_imageio_plugins_jpeg2000_image_1.0",
+- "com.sun.media.imageioimpl.plugins.jpeg2000.J2KMetadataFormat",
+- null, null);
+- }
+-
+- public void onRegistration(ServiceRegistry registry,
+- Class category) {
+- if (registered) {
+- return;
+- }
+-
+- registered = true;
+-
+- // Set pairwise ordering to give codecLib reader precedence.
+- Class codecLibReaderSPIClass = null;
+- try {
+- codecLibReaderSPIClass =
+- Class.forName("com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReaderCodecLibSpi");
+- } catch(Throwable t) {
+- // Ignore it.
+- }
+-
+- if(codecLibReaderSPIClass != null) {
+- Object codecLibReaderSPI =
+- registry.getServiceProviderByClass(codecLibReaderSPIClass);
+- if(codecLibReaderSPI != null) {
+- registry.setOrdering(category, codecLibReaderSPI, this);
+- }
+- }
+- }
+-
+- public String getDescription(Locale locale) {
+- String desc = PackageUtil.getSpecificationTitle() +
+- " JPEG 2000 Image Reader";
+- return desc;
+- }
+-
+- public boolean canDecodeInput(Object source) throws IOException {
+- if (!(source instanceof ImageInputStream)) {
+- return false;
+- }
+-
+- ImageInputStream stream = (ImageInputStream)source;
+-
+- //fix of 4938421
+- stream.mark();
+- int marker = (stream.read() << 8) | stream.read();
+-
+- if (marker == 0xFF4F) {
+- stream.reset();
+- return true;
+- }
+-
+- stream.reset();
+- stream.mark();
+- byte[] b = new byte[12];
+- stream.readFully(b);
+- stream.reset();
+-
+- //Verify the signature box
+-
+- // The length of the signature box is 12
+- if (b[0] !=0 || b[1]!=0 || b[2] != 0 || b[3] != 12)
+- return false;
+-
+- // The signature box type is "jP "
+- if ((b[4] & 0xff) != 0x6A || (b[5] & 0xFF) != 0x50 ||
+- (b[6] & 0xFF) !=0x20 || (b[7] & 0xFF) != 0x20)
+- return false;
+-
+- // The signture content is 0x0D0A870A
+- if ((b[8] & 0xFF) != 0x0D || (b[9] & 0xFF) != 0x0A ||
+- (b[10] & 0xFF) != 0x87 || (b[11] &0xFF) != 0x0A)
+- return false;
+-
+- return true;
+- }
+-
+- public ImageReader createReaderInstance(Object extension)
+- throws IIOException {
+- return new J2KImageReader(this);
+- }
+-}
+-
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReadParamJava.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReadParamJava.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReadParamJava.java 2005-02-11 00:01:33.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReadParamJava.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,166 +0,0 @@
+-/*
+- * $RCSfile: J2KImageReadParamJava.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:33 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import javax.imageio.ImageReadParam;
+-import com.sun.media.imageio.plugins.jpeg2000.J2KImageReadParam;
+-/**
+- * A subclass of ImageReadParam
for reading images in
+- * the JPEG 2000 format.
+- *
+- * The decoding parameters for JPEG 2000 are listed below:
+- *
+- *
+- * JPEG 2000 Plugin Decoding Parameters
+- * Parameter Name Description
+- *
+- * decodingRate
+- * Specifies the decoding rate in bits per pixel (bpp) where the
+- * number of pixels is related to the image's original size (Note:
+- * this parameter is not affected by resolution
). The
+- * codestream is either parsed (default) or truncated depending
+- * parsingEnabled
. The default is Double.MAX_VALUE
.
+- * It means decoding with the encoding rate.
+- *
+- *
+- *
+- * resolution
+- * Specifies the resolution level wanted for the decoded image
+- * (0 means the lowest available resolution, the resolution
+- * level gives an image with the original dimension). If the given index
+- * is greater than the number of available resolution levels of the
+- * compressed image, the decoded image has the lowest available
+- * resolution (among all tile-components). This parameter affects only
+- * the inverse wavelet transform and not the number of bytes read by the
+- * codestream parser, which depends only on decodingRate
.
+- *
+- *
+- *
+- * noROIDescaling
+- * Ensures that no ROI de-scaling is performed. Decompression is done
+- * like there is no ROI in the image.
+- *
+- *
+- *
+- * parsingEnabled
+- * Enable the parsing mode or not when the decoding rate is specified.
+- * If it is false, the codestream is decoded as if it were truncated to
+- * the given rate. If it is true, the decoder creates, truncates and
+- * decodes a virtual layer progressive codestream with the same
+- * truncation points in each code-block.
+- *
+- *
+- *
+- */
+-public class J2KImageReadParamJava extends J2KImageReadParam {
+-
+- /** Ensures that no ROI de-scaling is performed. Decompression
+- * is done like there is no ROI in the image.
+- */
+- private boolean noROIDescaling = true;
+-
+- /** Enable the parsing mode or not when the decoding rate is specified .
+- * If it is false, the codestream is decoded as if it were truncated to
+- * the given rate. If it is true, the decoder creates, truncates and
+- * decodes a virtual layer progressive codestream with the same
+- * truncation points in each code-block.
+- */
+- private boolean parsingEnabled = true;
+-
+- /** Constructs a default instance of J2KImageReadParamJava
. */
+- public J2KImageReadParamJava() {
+- super();
+- }
+-
+- public J2KImageReadParamJava(ImageReadParam param) {
+- super();
+-
+- // Generic settings.
+- if(param.hasController()) {
+- setController(param.getController());
+- }
+- setSourceRegion(param.getSourceRegion());
+- setSourceBands(param.getSourceBands());
+- setDestinationBands(param.getDestinationBands());
+- setDestination(param.getDestination());
+-
+- setDestinationOffset(param.getDestinationOffset());
+- setSourceSubsampling(param.getSourceXSubsampling(),
+- param.getSourceYSubsampling(),
+- param.getSubsamplingXOffset(),
+- param.getSubsamplingYOffset());
+- setDestinationType(param.getDestinationType());
+-
+- // J2K settings.
+- J2KImageReadParam j2kParam;
+- if(param instanceof J2KImageReadParam) {
+- j2kParam = (J2KImageReadParam)param;
+- } else {
+- j2kParam = new J2KImageReadParam();
+- }
+- setDecodingRate(j2kParam.getDecodingRate());
+- setResolution(j2kParam.getResolution());
+- }
+-
+- /** Sets noROIDescaling
*/
+- public void setNoROIDescaling(boolean value) {
+- this.noROIDescaling = value;
+- }
+-
+- /** Gets noROIDescaling
*/
+- public boolean getNoROIDescaling() {
+- return noROIDescaling;
+- }
+-
+- /** Sets parsingEnabled
*/
+- public void setParsingEnabled(boolean value) {
+- this.parsingEnabled = value;
+- }
+-
+- /** Gets parsingEnabled
*/
+- public boolean getParsingEnabled() {
+- return parsingEnabled;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriteParamJava.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriteParamJava.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriteParamJava.java 2006-09-20 19:23:30.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriteParamJava.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,1297 +0,0 @@
+-/*
+- * $RCSfile: J2KImageWriteParamJava.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.2 $
+- * $Date: 2006/09/20 23:23:30 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.awt.Rectangle;
+-import java.awt.image.Raster;
+-import java.awt.image.RenderedImage;
+-import java.util.Collections;
+-import java.util.Locale;
+-import java.util.Iterator;
+-import javax.imageio.IIOImage;
+-import javax.imageio.ImageWriteParam;
+-import jj2000.j2k.*;
+-import jj2000.j2k.roi.*;
+-import jj2000.j2k.quantization.*;
+-import jj2000.j2k.wavelet.analysis.AnWTFilterSpec;
+-import jj2000.j2k.image.forwcomptransf.ForwCompTransfSpec;
+-import jj2000.j2k.entropy.CBlkSizeSpec;
+-import jj2000.j2k.entropy.PrecinctSizeSpec;
+-import jj2000.j2k.entropy.ProgressionSpec;
+-import jj2000.j2k.image.BlkImgDataSrc;
+-import jj2000.j2k.entropy.encoder.LayersInfo;
+-import com.sun.media.imageio.plugins.jpeg2000.J2KImageWriteParam;
+-
+-/**
+- * A subclass of ImageWriteParam
for writing images in
+- * the JPEG 2000 format.
+- *
+- * JPEG 2000 plugin supports to losslessly or lossy compress gray-scale,
+- * RGB, and RGBA images with byte, unsigned short or short data type. It also
+- * supports losslessly compress bilevel, and 8-bit indexed. The result data
+- * is in the format of JP2 (JPEG 2000 Part 1 or baseline format).
+- *
+- *
Many encoding parameters for JPEG 2000 can be tile-component specific.
+- * These parameters are marked as Yes
in the column
+- * TC_SPEC
in the following parameter table.
+- * They must be provided according to the pattern:
+- * [<tile-component idx>] <param> (repeated as many time as needed),
+- * where <tile-component idx> respect the following policy according to
+- * the degree of priority:
+- *
+- * (1) t<idx> c<idx> : Tile-component specification.
+- * (2) t<idx> : Tile specification.
+- * (3) c<idx> : Component specification.
+- * (4) <void> : Default specification.
+- *
+- * Where the priorities of the specifications are:
+- * (1) > (2) > (3) > (4), (">" means "overrides")
+- * <idx>: "," separates indexes, "-" separates bounds of indexes list.
+- * (for example, 0,2-4 means indexes 0,2,3 and 4).
+- *
+- *
The parameters for encoding JPEG 2000 are listed in the following table:
+- *
+- * *
+- * JPEG 2000 Plugin Decoding Parameters
+- * Parameter Name Description TC_SPEC
+- *
+- * encodingRate
+- * The bitrate in bits-per-pixel for encoding. Should be set when
+- * lossy compression scheme is used. With the default value
+- * Double.MAX_VALUE
, a lossless compression will be done.
+- *
+- * No
+- *
+- *
+- * lossless
+- * Indicates using the loseless scheme or not. It is equivalent to
+- * use reversible quantization and 5x3 integer wavelet filters. The
+- * default is true
.
+- *
+- * No
+- *
+- *
+- * componentTransformation
+- * Specifies to utilize the component transformation on some tiles.
+- * If the wavelet transform is reversible (w5x3 filter), the Reversible
+- * Component Transformation (RCT) is applied. If not reversible
+- * (w9x7 filter), the Irreversible Component Transformation (ICT) is used.
+- *
+- * Yes, Tile_Specific
+- *
+- *
+- * filters
+- * Specifies which wavelet filters to use for the specified
+- * tile-components. JPEG 2000 part I only supports w5x3 and w9x7 filters.
+- *
+- * Yes
+- *
+- *
+- * decompositionLevel
+- * Specifies the wavelet decomposition levels to apply to
+- * the image. If it is 0, no wavelet transform is performed, in which
+- * case the original image data will be sent to the encoder and an example
+- * is the binary data. All components and all tiles have the same number
+- * of decomposition levels. The default value is 5.
+- *
+- * No
+- *
+- *
+- * guardBits
+- * The number of bits used for each tile-component in the quantizer
+- * to avoid overflow. It takes values in the range 0 through 7. The
+- * default value is 2.
+- *
+- * Yes
+- *
+- *
+- * quantizationStep
+- * This parameter specifies the base normalized quantization step
+- * size for the tiles/components. It is normalized to a dynamic range
+- * of 1 in the image domain. This parameter is ignored in reversible
+- * coding. The default value is 0.0078125.
+- *
+- * Yes
+- *
+- *
+- * quantizationType
+- * Specifies which quantization type to use for specified
+- * tiles/components. Not specified for lossless compression. By default,
+- * the quantization step size is "expounded". Supported quantization
+- * types specification are : "reversible" (no quantization), "derived"
+- * (derived quantization step size) and "expounded".
+- *
+- * Yes
+- *
+- *
+- * codeBlockSize
+- * Specifies the maximum code-block size to use for tile-component.
+- * The maximum width and height is 1024, however the block size
+- * (i.e. width x height) must not exceed 4096. The minimum width and
+- * height is 4. The default values are (64, 64).
+- *
+- * Yes
+- *
+- *
+- * progressionType
+- * Specifies which type of progression should be used when generating
+- * the codestream.
+- * The format is [<tile index>]
+- * res|layer|res-pos|pos-comp|comp-pos [res_start comp_start layer_end
+- * res_end comp_end prog] [[res_start comp_start layer_end res_end
+- * comp_end prog]...] [[<tile-component idx]...].
+- *
The value "res" generates a resolution progressive
+- * codestream with the number of layers specified by "layers" parameter.
+- * The value "layer" generates a layer progressive codestream with
+- * multiple layers. In any case, the rate-allocation algorithm optimizes
+- * for best quality in each layer. The quality measure is mean squared
+- * error (MSE) or a weighted version of it (WMSE). If no progression
+- * type is specified or imposed by other parameters, the default value
+- * is "layer". It is also possible to describe progression order
+- * changes. In this case, "res_start" is the index (from 0) of the
+- * first resolution level, "comp_start" is the index (from 0) of the
+- * first component, "layer_end" is the index (from 0) of the first layer
+- * not included, "res_end" is the index (from 0) of the first
+- * resolution level not included, "comp_end" is index (from 0) of
+- * the first component not included and "prog" is the progression type
+- * to be used for the rest of the tile/image. Several progression
+- * order changes can be specified, one after the other.
+- *
+- * Yes
+- *
+- *
+- * packPacketHeaderInTile
+- * Indicates that the packet headers are packed in the tiles' headers.
+- * The default is false.
+- *
+- * No
+- *
+- *
+- * packPacketHeaderInMain
+- * Indicates that the packet headers are packed in the main header.
+- * The default is false.
+- *
+- * No
+- *
+- *
+- * packetPerTilePart
+- * Specifies the maximum number of packets to be put into one tile-part.
+- * Zero means putting all packets in the first tile-part of each tile.
+- *
+- * No
+- *
+- *
+- * ROIs
+- * Specifies ROIs shape and location. The component index specifies
+- * which components contain the ROI. If this parameter is used, the
+- * codestream is layer progressive by default unless it is overridden by
+- * the progressionType
. A rectanglar or circular ROI can be
+- * specified in the format: [<component idx>] R <left>
+- * <top> <width> <height> or [<component idx>] C
+- * <center x> <center y> <radius>. An arbitrary shape
+- * can be assigned by [<component idx>] A <PGM file>
+- *
+- * Yes, component-specified
+- *
+- *
+- * startLevelROI
+- * This parameter defines the lowest resolution levels to belong to
+- * the ROI. By doing this, it is possible to avoid getting
+- * information for the ROI at an early stage of transmission.
+- * startLevelROI = 0 means the lowest resolution level belongs to
+- * the ROI, 1 means the second lowest etc. The default values, -1,
+- * deactivates this parameter.
+- *
+- * No
+- *
+- *
+- * alignROI
+- * By specifying this parameter, the ROI mask will be limited to
+- * covering only entire code-blocks. The ROI coding can then be
+- * performed without any actual scaling of the coefficients but by
+- * instead scaling the distortion estimates.
+- *
+- * No
+- *
+- *
+- * bypass
+- * Uses the lazy coding mode with the entropy coder. This will bypass
+- * the MQ coder for some of the coding passes, where the distribution
+- * is often close to uniform. Since the MQ codeword will be terminated
+- * at least once per lazy pass, it is important to use an efficient
+- * termination algorithm, methodForMQTermination
.
+- * true enables, and false disables it. The default value is false.
+- *
+- * Yes
+- *
+- *
+- * resetMQ
+- * If this is enabled the probability estimates of the MQ coder are
+- * reset after each arithmetically coded (i.e. non-lazy) coding pass.
+- * true enables, and false disables it. The default value is false.
+- *
+- * Yes
+- *
+- *
+- * terminateOnByte
+- * If this is enabled the codeword (raw or MQ) is terminated on a byte
+- * boundary after each coding pass. In this case it is important to use
+- * an efficient termination algorithm, "methodForMQTermination".
+- * true enables, and false disables it. The default value is false.
+- *
+- * Yes
+- *
+- *
+- * causalCXInfo
+- * Uses vertically stripe causal context formation. If this is
+- * enabled the context formation process in one stripe is independant of
+- * the next stripe (i.e. the one below it). true enables, and false
+- * disables it. The default value is false.
+- *
+- * Yes
+- *
+- *
+- * codeSegSymbol
+- * Inserts an error resilience segmentation symbol in the MQ codeword
+- * at the end of each bit-plane (cleanup pass). Decoders can use this
+- * information to detect and conceal errors. true enables, and false
+- * disables it. The default value is false.
+- *
+- * Yes
+- *
+- *
+- * methodForMQTermination
+- * Specifies the algorithm used to terminate the MQ codeword. The
+- * most efficient one is "near_opt", which delivers a codeword which
+- * in almost all cases is the shortest possible. The "easy" is a
+- * simpler algorithm that delivers a codeword length that is close
+- * to the previous one (in average 1 bit longer). The "predict" is
+- * almost the same as the "easy" but it leaves error resilient
+- * information on the spare least significant bits (in average 3.5 bits),
+- * which can be used by a decoder to detect errors. The "full" algorithm
+- * performs a full flush of the MQ coder and is highly inefficient. It
+- * is important to use a good termination policy since the MQ codeword
+- * can be terminated quite often, specially if the "bypass" or
+- * "terminateOnByte" parameters are enabled (in the normal case it would
+- * be terminated once per code-block, while "terminateOnByte" is specified
+- * it will be done almost 3 times per bit-plane in each code-block).
+- * The default value is "near_opt".
+- *
+- * Yes
+- *
+- *
+- * methodForMQLengthCalc
+- * Specifies the algorithm to use in calculating the necessary MQ
+- * length for each decoding pass. The best one is "near_opt", which
+- * performs a rather sophisticated calculation and provides the best
+- * results. The "lazy_good" and "lazy" are very simple algorithms
+- * that provide rather conservative results. "lazy_good" performs
+- * slightly better. Please use the default unless the experiments
+- * show the benefits of different length calculation algorithms.
+- * The default value is "near_opt".
+- *
+- * Yes
+- *
+- *
+- * precinctPartition
+- * Specifies precinct partition dimensions for tiles/components. They
+- * are stored from those applied to the highest resolution to those
+- * applied to the remaining resolutions in decreasing order. If less
+- * values than the number of decomposition levels are specified, then
+- * the last two values are used for the remaining resolutions.
+- *
+- * Yes
+- *
+- *
+- * layers
+- * Explicitly specifies the codestream layer formation parameters.
+- * The rate (double) parameter specifies the bitrate to which the first
+- * layer should be optimized. The layers (int) parameter, if present,
+- * specifies the number of extra layers that should be added for
+- * scalability. These extra layers are not optimized. Any extra rate
+- * and layers parameters add more layers, in the same way. An
+- * additional layer is always added at the end, which is optimized
+- * to the overall target bitrate of the bit stream. Any layers
+- * (optimized or not) whose target bitrate is higher that the overall
+- * target bitrate are silently ignored. The bitrates of the extra layers
+- * that are added through the layers parameter are approximately
+- * log-spaced between the other target bitrates. If several (rate, layers)
+- * constructs appear the rate parameters must appear in increasing order.
+- * The rate allocation algorithm ensures that all coded layers have a
+- * minimal reasonable size, if not these layers are silently ignored.
+- * Default: 0.015 +20 2.0 +10.
+- *
+- * No
+- *
+- *
+- * SOP
+- * Specifies whether start of packet (SOP) markers should be used.
+- * true enables, false disables it. The default value is false.
+- *
+- * Yes
+- *
+- *
+- * EPH
+- * Specifies whether end of packet header (EPH) markers should be used.
+- * true enables, false disables it. The default value is false.
+- *
+- * Yes
+- *
+- *
+- */
+-public class J2KImageWriteParamJava extends ImageWriteParam {
+- /**
+- * Indicates that the packet headers are packed in the tiles' headers.
+- */
+- private boolean packPacketHeaderInTile = false;
+-
+- /**
+- * Indicates that the packet headers are packed in the main header.
+- */
+- private boolean packPacketHeaderInMain = false;
+-
+- /**
+- * Specifies the maximum number of packets to be put into one tile-part.
+- * Zero means include all packets in first tile-part of each tile.
+- */
+- private int packetPerTilePart = 0;
+-
+- /**
+- * The bitrate in bits-per-pixel for encoding. Should be set when lossy
+- * compression scheme is used. The default is
+- * Double.MAX_VALUE
.
+- */
+- private double encodingRate = Double.MAX_VALUE;
+-
+- /**
+- * Indicates using the loseless scheme or not. It is equivalent to
+- * use reversible quantization and 5x3 integer wavelet filters.
+- */
+- private boolean lossless = true;
+-
+- /** Specifies to utilize the component transformation with some tiles.
+- * If the wavelet transform is reversible (w5x3 filter), the
+- * Reversible Component Transformation (RCT) is applied. If not reversible
+- * (w9x7 filter), the Irreversible Component Transformation (ICT)
+- * is used.
+- */
+- private ForwCompTransfSpec componentTransformation = null;
+- private boolean enableCT = true;
+-
+- /** Specifies which filters to use for the specified tile-components.
+- * JPEG 2000 part I only supports w5x3 and w9x7 filters.
+- */
+- private AnWTFilterSpec filters = null;
+-
+- /** Specifies the number of wavelet decomposition levels to apply to
+- * the image. If it is 0, no wavelet transform is performed, in which
+- * case the original image data will be sent to the encoder and an
+- * example is the binary data. All components and all tiles have
+- * the same number of decomposition levels. Default: 5.
+- */
+- private IntegerSpec decompositionLevel = null; // = 5;
+-
+- /** The number of bits used for each tile-component in
+- * the quantizer to avoid overflow. It takes values in the range 0
+- * through 7. Default: 2.
+- */
+- private GuardBitsSpec guardBits = null;
+-
+- /** This parameter specifies the base normalized quantization step
+- * size for the tiles/components. It is normalized to a dynamic range
+- * of 1 in the image domain. This parameter is ignored in reversible
+- * coding. Default: 0.0078125.
+- */
+- private QuantStepSizeSpec quantizationStep = null;
+-
+- /** Specifies which quantization type to use for specified
+- * tiles/components. Not specified for lossless compression. By
+- * default , the quantization step size is "expounded". Supported
+- * quantization types specification are : "reversible" (no quantization),
+- * "derived" (derived quantization step size) and "expounded".
+- */
+- private QuantTypeSpec quantizationType = null;
+-
+- /** This parameter defines the lowest resolution levels to belong to
+- * the ROI. By doing this, it is possible to avoid only getting
+- * information for the ROI at an early stage of transmission.
+- * startLevelROI = 0 means the lowest resolution level belongs to
+- * the ROI, 1 means the second lowest etc. The default values, -1,
+- * deactivates this parameter.
+- */
+- private int startLevelROI = -1;
+-
+- /** By specifying this parameter, the ROI mask will be limited to
+- * covering only entire code-blocks. The ROI coding can then be
+- * performed without any actual scaling of the coefficients but
+- * by instead scaling the distortion estimates.
+- */
+- private boolean alignROI = false;
+-
+- /** Specifies ROIs shape and location. The component index specifies
+- * which components contain the ROI. If this parameter is used, the
+- * codestream is layer progressive by default unless it is
+- * overridden by the progressionType
.
+- */
+- private MaxShiftSpec ROIs = null;
+-
+- /** Specifies the maximum code-block size to use for tile-component.
+- * The maximum width and height is 1024, however the image area
+- * (i.e. width x height) must not exceed 4096. The minimum
+- * width and height is 4. Default: 64 64.
+- */
+- private CBlkSizeSpec codeBlockSize = null;
+-
+- /** Uses the lazy coding mode with the entropy coder. This will bypass
+- * the MQ coder for some of the coding passes, where the distribution
+- * is often close to uniform. Since the MQ codeword will be terminated
+- * at least once per lazy pass, it is important to use an efficient
+- * termination algorithm, methodForMQTermination
.
+- * true enables, and false disables it. Default: false.
+- */
+- private StringSpec bypass = null;
+-
+- /** If this is enabled the probability estimates of the MQ coder are
+- * reset after each arithmetically coded (i.e. non-lazy) coding pass.
+- * true enables, and false disables it. Default: false.
+- */
+- private StringSpec resetMQ = null;
+-
+- /** If this is enabled the codeword (raw or MQ) is terminated on a byte
+- * boundary after each coding pass. In this case it is important to
+- * use an efficient termination algorithm, the "methodForMQTermination".
+- * true enables, and false disables it. Default: false.
+- */
+- private StringSpec terminateOnByte = null;
+-
+- /** Uses vertically stripe causal context formation. If this is
+- * enabled the context formation process in one stripe is independant
+- * of the next stripe (i.e. the one below it). true enables, and
+- * false disables it. Default: false.
+- */
+- private StringSpec causalCXInfo = null;
+-
+- /** Inserts an error resilience segmentation symbol in the MQ codeword
+- * at the end of each bit-plane (cleanup pass). Decoders can use this
+- * information to detect and conceal errors. true enables,
+- * and false disables it. Default: false.
+- */
+- private StringSpec codeSegSymbol = null;
+-
+- /** Specifies the algorithm used to terminate the MQ codeword. The
+- * most efficient one is "near_opt", which delivers a codeword which
+- * in almost all cases is the shortest possible. The "easy" is a
+- * simpler algorithm that delivers a codeword length that is close
+- * to the previous one (in average 1 bit longer). The "predict" is
+- * almost the same as the "easy" but it leaves error resilient
+- * information on the spare least significant bits (in average
+- * 3.5 bits), which can be used by a decoder to detect errors.
+- * The "full" algorithm performs a full flush of the MQ coder and
+- * is highly inefficient. It is important to use a good termination
+- * policy since the MQ codeword can be terminated quite often,
+- * specially if the "bypass" or "terminateOnByte" parameters are
+- * enabled (in the normal case it would be terminated once per
+- * code-block, while "terminateOnByte" is specified it will be
+- * done almost 3 times per bit-plane in each code-block).
+- * Default: near_opt.
+- */
+- private StringSpec methodForMQTermination = null;
+-
+- /** Specifies the algorithm to use in calculating the necessary MQ
+- * length for each decoding pass. The best one is "near_opt", which
+- * performs a rather sophisticated calculation and provides the best
+- * results. The "lazy_good" and "lazy" are very simple algorithms
+- * that provide rather conservative results. "lazy_good" performs
+- * slightly better. Please use the default unless the experiments
+- * show the benefits of different length calculation algorithms.
+- * Default: near_opt.
+- */
+- private StringSpec methodForMQLengthCalc = null;
+-
+- /** Specifies precinct partition dimensions for tiles/components. They
+- * are stored from those applied to the highest resolution to those
+- * applied to the remaining resolutions in decreasing order. If less
+- * values than the number of decomposition levels are specified, then
+- * the last two values are used for the remaining resolutions.
+- */
+- private PrecinctSizeSpec precinctPartition = null;
+-
+- /** Specifies which type of progression should be used when generating
+- * the codestream. The value "res" generates a resolution progressive
+- * codestream with the number of layers specified by "layers" parameter.
+- * The value "layer" generates a layer progressive codestream with
+- * multiple layers. In any case, the rate-allocation algorithm optimizes
+- * for best quality in each layer. The quality measure is mean squared
+- * error (MSE) or a weighted version of it (WMSE). If no progression
+- * type is specified or imposed by other modules, the default value
+- * is "layer". It is also possible to describe progression order
+- * changes. In this case, "res_start" is the index (from 0) of the
+- * first resolution level, "comp_start" is the index (from 0) of the
+- * first component, "ly_end" is the index (from 0) of the first layer
+- * not included, "res_end" is the index (from 0) of the first
+- * resolution level not included, "comp_end" is index (from 0) of
+- * the first component not included and "prog" is the progression type
+- * to be used for the rest of the tile/image. Several progression
+- * order changes can be specified, one after the other.
+- */
+- private ProgressionSpec progressionType = null;
+-
+- /**
+- * The specified (tile-component) progression. Will be used to generate
+- * the progression type.
+- */
+- private String progressionName = null;
+-
+- /** Explicitly specifies the codestream layer formation parameters.
+- * The rate (double) parameter specifies the bitrate to which the first
+- * layer should be optimized. The layers (int) parameter, if present,
+- * specifies the number of extra layers that should be added for
+- * scalability. These extra layers are not optimized. Any extra rate
+- * and layers parameters add more layers, in the same way. An
+- * additional layer is always added at the end, which is optimized
+- * to the overall target bitrate of the bit stream. Any layers
+- * (optimized or not) whose target bitrate is higher that the
+- * overall target bitrate are silently ignored. The bitrates of
+- * the extra layers that are added through the layers parameter
+- * are approximately log-spaced between the other target bitrates.
+- * If several (rate, layers) constructs appear the rate parameters
+- * must appear in increasing order. The rate allocation algorithm
+- * ensures that all coded layers have a minimal reasonable size,
+- * if not these layers are silently ignored. Default: 0.015 +20 2.0 +10.
+- */
+- private String layers = "0.015 +20 2.0 +10";
+-
+- /** Specifies whether end of packet header (EPH) markers should be used.
+- * true enables, false disables it. Default: false.
+- */
+- private StringSpec EPH = null;
+-
+- /** Specifies whether start of packet (SOP) markers should be used.
+- * true enables, false disables it. Default: false.
+- */
+- private StringSpec SOP = null;
+-
+- private int numTiles;
+- private int numComponents;
+-
+- private RenderedImage imgsrc;
+- private Raster raster;
+-
+- private int minX;
+- private int minY;
+-
+- /** Constructor to set locales. */
+- public J2KImageWriteParamJava(RenderedImage imgsrc, Locale locale) {
+- super(locale);
+- setDefaults(imgsrc);
+- }
+-
+- /** Constructor to set locales. */
+- public J2KImageWriteParamJava(IIOImage image, ImageWriteParam param) {
+- super(param.getLocale());
+- if(image != null) {
+- if (image.hasRaster())
+- setDefaults(image.getRaster());
+- else
+- setDefaults(image.getRenderedImage());
+- }
+-
+- setSourceRegion(param.getSourceRegion());
+- setSourceBands(param.getSourceBands());
+- try {
+- setTiling(param.getTileWidth(), param.getTileHeight(),
+- param.getTileGridXOffset(), param.getTileGridYOffset());
+- } catch (IllegalStateException e) {
+- // tileing is not set do nothing.
+- }
+-
+- setDestinationOffset(param.getDestinationOffset());
+- setSourceSubsampling(param.getSourceXSubsampling(),
+- param.getSourceYSubsampling(),
+- param.getSubsamplingXOffset(),
+- param.getSubsamplingYOffset());
+- setDestinationType(param.getDestinationType());
+-
+- J2KImageWriteParam j2kParam;
+- if(param instanceof J2KImageWriteParam) {
+- j2kParam = (J2KImageWriteParam)param;
+- } else {
+- j2kParam = new J2KImageWriteParam();
+- }
+-
+- setDecompositionLevel(""+j2kParam.getNumDecompositionLevels());
+- setEncodingRate(j2kParam.getEncodingRate());
+- setLossless(j2kParam.getLossless());
+- setFilters(j2kParam.getFilter());
+- setEPH("" + j2kParam.getEPH());
+- setSOP("" + j2kParam.getSOP());
+- setProgressionName(j2kParam.getProgressionType());
+- int[] size = j2kParam.getCodeBlockSize();
+- setCodeBlockSize("" + size[0] +" " + size[1]);
+- enableCT = j2kParam.getComponentTransformation();
+- setComponentTransformation("" + enableCT);
+- }
+-
+-
+- /**
+- * Constructs a J2KImageWriteParamJava
object with default
+- * values for all parameters.
+- */
+- public J2KImageWriteParamJava() {
+- super();
+- setSuperProperties();
+- }
+-
+- /**
+- * Constructs a J2KImageWriteParamJava
object with default
+- * values for all parameters.
+- */
+- public J2KImageWriteParamJava(RenderedImage imgsrc) {
+- super();
+- setDefaults(imgsrc);
+- }
+-
+- /**
+- * Constructs a J2KImageWriteParamJava
object with default
+- * values for all parameters.
+- */
+- public J2KImageWriteParamJava(Raster raster) {
+- super();
+- setDefaults(raster);
+- }
+-
+- private void setSuperProperties() {
+- canOffsetTiles = true;
+- canWriteTiles = true;
+- canOffsetTiles = true;
+- canWriteProgressive = true;
+- tilingMode = MODE_EXPLICIT;
+- }
+-
+- /** Set source */
+- private void setDefaults(Raster raster) {
+- // override the params in the super class
+- setSuperProperties();
+-
+- if (raster != null) {
+- this.raster = raster;
+- tileGridXOffset = raster.getMinX();
+- tileGridYOffset = raster.getMinY();
+- tileWidth = raster.getWidth();
+- tileHeight = raster.getHeight();
+- tilingSet = true;
+-
+- numTiles = 1;
+- numComponents = raster.getSampleModel().getNumBands();
+- }
+- setDefaults();
+- }
+-
+- /** Set source */
+- private void setDefaults(RenderedImage imgsrc) {
+- // override the params in the super class
+- setSuperProperties();
+-
+- tilingMode = MODE_EXPLICIT;
+-
+- if (imgsrc != null) {
+- this.imgsrc = imgsrc;
+- tileGridXOffset = imgsrc.getTileGridXOffset();
+- tileGridYOffset = imgsrc.getTileGridYOffset();
+- tileWidth = imgsrc.getTileWidth();
+- tileHeight = imgsrc.getTileHeight();
+- tilingSet = true;
+-
+- numTiles = imgsrc.getNumXTiles() * imgsrc.getNumYTiles();
+- numComponents = imgsrc.getSampleModel().getNumBands();
+- }
+- setDefaults();
+- }
+-
+- private void setDefaults() {
+- setROIs(null);
+- setQuantizationType(null);
+- setQuantizationStep(null);
+- setGuardBits(null);
+- setFilters(null);
+- setDecompositionLevel(null);
+- setComponentTransformation(null);
+- setMethodForMQLengthCalc(null);
+- setMethodForMQTermination(null);
+- setCodeSegSymbol(null);
+- setCausalCXInfo(null);
+- setTerminateOnByte(null);
+- setResetMQ(null);
+- setBypass(null);
+- setCodeBlockSize(null);
+- setPrecinctPartition(null);
+- setSOP(null);
+- setEPH(null);
+- }
+-
+- /** Sets encodingRate
*/
+- public void setEncodingRate(double rate) {
+- this.encodingRate = rate;
+- }
+-
+- /** Gets encodingRate
*/
+- public double getEncodingRate() {
+- return encodingRate;
+- }
+-
+- /** Sets lossless
*/
+- public void setLossless(boolean lossless) {
+- this.lossless = lossless;
+- }
+-
+- /** Gets encodingRate
*/
+- public boolean getLossless() {
+- return lossless;
+- }
+- /** Sets packetPerTilePart
*/
+- public void setPacketPerTilePart(int packetPerTilePart) {
+- if (packetPerTilePart < 0)
+- throw new IllegalArgumentException(I18N.getString("J2KImageWriteParamJava0"));
+-
+- this.packetPerTilePart = packetPerTilePart;
+- if (packetPerTilePart > 0) {
+- setSOP("true");
+- setEPH("true");
+- }
+- }
+-
+- /** Gets packetPerTilePart
*/
+- public int getPacketPerTilePart() {
+- return packetPerTilePart;
+- }
+-
+- /** Sets packPacketHeaderInTile
*/
+- public void setPackPacketHeaderInTile(boolean packPacketHeaderInTile) {
+- this.packPacketHeaderInTile = packPacketHeaderInTile;
+- if (packPacketHeaderInTile) {
+- setSOP("true");
+- setEPH("true");
+- }
+- }
+-
+- /** Gets packPacketHeaderInTile
*/
+- public boolean getPackPacketHeaderInTile() {
+- return packPacketHeaderInTile;
+- }
+-
+- /** Sets packPacketHeaderInMain
*/
+- public void setPackPacketHeaderInMain(boolean packPacketHeaderInMain) {
+- this.packPacketHeaderInMain = packPacketHeaderInMain;
+- if (packPacketHeaderInMain) {
+- setSOP("true");
+- setEPH("true");
+- }
+- }
+-
+- /** Gets packPacketHeaderInMain
*/
+- public boolean getPackPacketHeaderInMain() {
+- return packPacketHeaderInMain;
+- }
+-
+- /** Sets alignROI
*/
+- public void setAlignROI(boolean align) {
+- alignROI = align;
+- }
+-
+- /** Gets alignROI
*/
+- public boolean getAlignROI() {
+- return alignROI;
+- }
+-
+- /** Sets ROIs
*/
+- public void setROIs(String values) {
+- ROIs = new MaxShiftSpec(numTiles, numComponents, ModuleSpec.SPEC_TYPE_TILE_COMP, values);
+- }
+-
+- /** Gets ROIs
*/
+- public MaxShiftSpec getROIs() {
+- return ROIs;
+- }
+-
+- /** Sets quantizationType
*/
+- public void setQuantizationType(String values) {
+- quantizationType = new QuantTypeSpec(numTiles, numComponents,
+- ModuleSpec.SPEC_TYPE_TILE_COMP, this, values);
+- }
+-
+- /** Gets quantizationType
*/
+- public QuantTypeSpec getQuantizationType() {
+- return quantizationType;
+- }
+-
+- /** Sets quantizationStep
*/
+- public void setQuantizationStep(String values) {
+- quantizationStep = new QuantStepSizeSpec(numTiles,
+- numComponents,
+- ModuleSpec.SPEC_TYPE_TILE_COMP,
+- this,
+- values);
+- }
+-
+- /** Gets quantizationStep
*/
+- public QuantStepSizeSpec getQuantizationStep() {
+- return quantizationStep;
+- }
+-
+- /** Sets guardBits
*/
+- public void setGuardBits(String values) {
+- guardBits = new GuardBitsSpec(numTiles,
+- numComponents,
+- ModuleSpec.SPEC_TYPE_TILE_COMP,
+- this,
+- values);
+- }
+-
+- /** Gets guardBits
*/
+- public GuardBitsSpec getGuardBits() {
+- return guardBits;
+- }
+-
+- /** Sets filters
*/
+- // NOTE This also sets quantizationType and componentTransformation.
+- public void setFilters(String values) {
+- if (J2KImageWriteParam.FILTER_97.equals(values))
+- setQuantizationType ("expounded");
+- else
+- setQuantizationType("reversible");
+-
+- filters = new AnWTFilterSpec(numTiles,
+- numComponents,
+- ModuleSpec.SPEC_TYPE_TILE_COMP,
+- (QuantTypeSpec)quantizationType,
+- this,
+- values);
+- setComponentTransformation(""+enableCT);
+- }
+-
+- /** Gets filters
*/
+- public AnWTFilterSpec getFilters() {
+- return filters;
+- }
+-
+- /** Sets decompositionLevel
*/
+- public void setDecompositionLevel(String values) {
+- decompositionLevel = new IntegerSpec(numTiles,
+- numComponents,
+- ModuleSpec.SPEC_TYPE_TILE_COMP,
+- this,
+- values,
+- "5");
+-
+- // NOTE The precinctPartition depends upon decompositionLevel
+- // so it needs to be re-initialized. Note that the parameter of
+- // setPrecinctPartition() is not used in the current implementation.
+- setPrecinctPartition(null);
+- }
+-
+- /** Gets decompositionLevel
*/
+- public IntegerSpec getDecompositionLevel() {
+- return decompositionLevel;
+- }
+-
+- /** Sets componentTransformation
*/
+- // NOTE This requires filters having been set previously.
+- public void setComponentTransformation(String values) {
+- componentTransformation =
+- new ForwCompTransfSpec(numTiles,
+- numComponents,
+- ModuleSpec.SPEC_TYPE_TILE,
+- (AnWTFilterSpec)filters,
+- this,
+- values);
+- }
+-
+- /** Gets componentTransformation
*/
+- public ForwCompTransfSpec getComponentTransformation() {
+- return componentTransformation;
+- }
+- /** Sets methodForMQLengthCalc
*/
+- public void setMethodForMQLengthCalc(String values) {
+- String[] strLcs = {"near_opt","lazy_good","lazy"};
+- methodForMQLengthCalc =
+- new StringSpec(numTiles,
+- numComponents,
+- ModuleSpec.SPEC_TYPE_TILE_COMP,
+- "near_opt",
+- strLcs,
+- this,
+- values);
+- }
+-
+- /** Gets methodForMQLengthCalc
*/
+- public StringSpec getMethodForMQLengthCalc() {
+- return methodForMQLengthCalc;
+- }
+-
+- /** Sets methodForMQTermination
*/
+- public void setMethodForMQTermination(String values) {
+- String[] strTerm = {"near_opt","easy","predict","full"};
+- methodForMQTermination =
+- new StringSpec(numTiles,
+- numComponents,
+- ModuleSpec.SPEC_TYPE_TILE_COMP,
+- "near_opt",
+- strTerm,
+- this,
+- values);
+- }
+-
+- /** Gets methodForMQTermination
*/
+- public StringSpec getMethodForMQTermination() {
+- return methodForMQTermination;
+- }
+-
+- /** Sets codeSegSymbol
*/
+- public void setCodeSegSymbol(String values) {
+- String[] strBoolean = {"true","false"};
+- codeSegSymbol =
+- new StringSpec(numTiles,
+- numComponents,
+- ModuleSpec.SPEC_TYPE_TILE_COMP,
+- "false",
+- strBoolean,
+- this,
+- values);
+- }
+-
+- /** Gets codeSegSymbol
*/
+- public StringSpec getCodeSegSymbol() {
+- return codeSegSymbol;
+- }
+-
+- /** Sets causalCXInfo
*/
+- public void setCausalCXInfo(String values) {
+- String[] strBoolean = {"true","false"};
+- causalCXInfo = new StringSpec(numTiles,
+- numComponents,
+- ModuleSpec.SPEC_TYPE_TILE_COMP,
+- "false",
+- strBoolean,
+- this,
+- values);
+- }
+-
+- /** Gets causalCXInfo
*/
+- public StringSpec getCausalCXInfo() {
+- return causalCXInfo;
+- }
+-
+- /** Sets terminateOnByte
*/
+- public void setTerminateOnByte(String values) {
+- String[] strBoolean = {"true","false"};
+- terminateOnByte = new StringSpec(numTiles,
+- numComponents,
+- ModuleSpec.SPEC_TYPE_TILE_COMP,
+- "false",
+- strBoolean,
+- this,
+- values);
+- }
+-
+- /** Gets terminateOnByte
*/
+- public StringSpec getTerminateOnByte() {
+- return terminateOnByte;
+- }
+-
+- /** Sets resetMQ
*/
+- public void setResetMQ(String values) {
+- String[] strBoolean = {"true","false"};
+- resetMQ = new StringSpec(numTiles,
+- numComponents,
+- ModuleSpec.SPEC_TYPE_TILE_COMP,
+- "false",
+- strBoolean,
+- this,
+- values);
+- }
+-
+- /** Gets resetMQ
*/
+- public StringSpec getResetMQ() {
+- return resetMQ;
+- }
+-
+- /** Sets bypass
*/
+- public void setBypass(String values) {
+- String[] strBoolean = {"true","false"};
+- bypass = new StringSpec(numTiles,
+- numComponents,
+- ModuleSpec.SPEC_TYPE_TILE_COMP,
+- "false",
+- strBoolean,
+- this,
+- values);
+- }
+-
+- /** Gets bypass
*/
+- public StringSpec getBypass() {
+- return bypass;
+- }
+-
+- /** Sets codeBlockSize
*/
+- public void setCodeBlockSize(String values) {
+- codeBlockSize = new CBlkSizeSpec(numTiles,
+- numComponents,
+- ModuleSpec.SPEC_TYPE_TILE_COMP,
+- this,
+- values);
+- }
+-
+- /** Gets codeBlockSize
*/
+- public CBlkSizeSpec getCodeBlockSize() {
+- return codeBlockSize;
+- }
+-
+- /** Sets precinctPartition
*/
+- public void setPrecinctPartition(String values) {
+- String[] strBoolean = {"true","false"};
+- if (imgsrc != null)
+- precinctPartition =
+- new PrecinctSizeSpec(numTiles,
+- numComponents,
+- ModuleSpec.SPEC_TYPE_TILE_COMP,
+- new RenderedImageSrc(imgsrc, this, null),
+- decompositionLevel,
+- this,
+- values);
+- else if (raster != null)
+- precinctPartition =
+- new PrecinctSizeSpec(numTiles,
+- numComponents,
+- ModuleSpec.SPEC_TYPE_TILE_COMP,
+- new RenderedImageSrc(raster, this, null),
+- decompositionLevel,
+- this,
+- values);
+- }
+-
+- /** Gets precinctPartition
*/
+- public PrecinctSizeSpec getPrecinctPartition() {
+- return precinctPartition;
+- }
+-
+- /** Sets SOP
*/
+- public void setSOP(String values) {
+- String[] strBoolean = {"true","false"};
+- SOP = new StringSpec(numTiles,
+- numComponents,
+- ModuleSpec.SPEC_TYPE_TILE_COMP,
+- "false",
+- strBoolean,
+- this,
+- values);
+- }
+-
+- /** Gets SOP
*/
+- public StringSpec getSOP() {
+- return SOP;
+- }
+-
+- /** Sets EPH
*/
+- public void setEPH(String values) {
+- String[] strBoolean = {"true","false"};
+- EPH = new StringSpec(numTiles,
+- numComponents,
+- ModuleSpec.SPEC_TYPE_TILE_COMP,
+- "false",
+- strBoolean,
+- this,
+- values);
+- }
+-
+- /** Gets EPH
*/
+- public StringSpec getEPH() {
+- return EPH;
+- }
+-
+- /** Sets progressionName
*/
+- public void setProgressionName(String values) {
+- progressionName = values;
+- }
+-
+- /** Gets progressionType
*/
+- public String getProgressionName() {
+- return progressionName;
+- }
+-
+- /** Sets progressionType
*/
+- public void setProgressionType(LayersInfo lyrs, String values) {
+- String[] strBoolean = {"true","false"};
+- progressionType = new ProgressionSpec(numTiles,
+- numComponents,
+- lyrs.getTotNumLayers(),
+- decompositionLevel,
+- ModuleSpec.SPEC_TYPE_TILE_COMP,
+- this,
+- values);
+- }
+-
+- /** Gets progressionType
*/
+- public ProgressionSpec getProgressionType() {
+- return progressionType;
+- }
+-
+- /** Sets the startLevelROI
*/
+- public void setStartLevelROI(int value) {
+- startLevelROI = value;
+- }
+-
+- /** Gets startLevel
*/
+- public int getStartLevelROI() {
+- return startLevelROI;
+- }
+-
+- /** Sets the layers
*/
+- public void setLayers(String value) {
+- layers = value;
+- }
+-
+- /** Gets layers
*/
+- public String getLayers() {
+- return layers;
+- }
+-
+- /** Sets minX
*/
+- public void setMinX(int minX) {
+- this.minX = minX;
+- }
+-
+- /** Gets minX
*/
+- public int getMinX() {
+- return minX;
+- }
+-
+- /** Sets minY
*/
+- public void setMinY(int minY) {
+- this.minY = minY;
+- }
+-
+- /** Gets minY
*/
+- public int getMinY() {
+- return minY;
+- }
+-
+- /** Gets the number of tiles */
+- public int getNumTiles() {
+- Rectangle sourceRegion = getSourceRegion();
+- if (sourceRegion == null) {
+- if (imgsrc != null)
+- sourceRegion = new Rectangle(imgsrc.getMinX(),
+- imgsrc.getMinY(),
+- imgsrc.getWidth(),
+- imgsrc.getHeight());
+- else sourceRegion = raster.getBounds();
+- } else {
+- if (imgsrc != null)
+- sourceRegion =
+- sourceRegion.intersection(new Rectangle(imgsrc.getMinX(),
+- imgsrc.getMinY(),
+- imgsrc.getWidth(),
+- imgsrc.getHeight()));
+- else sourceRegion = sourceRegion.intersection(raster.getBounds());
+- }
+-
+- int scaleX = getSourceXSubsampling();
+- int scaleY = getSourceYSubsampling();
+- int xOffset = getSubsamplingXOffset();
+- int yOffset = getSubsamplingYOffset();
+-
+- int w = (sourceRegion.width - xOffset + scaleX - 1) / scaleX;
+- int h = (sourceRegion.height - yOffset + scaleY - 1) / scaleY;
+-
+- minX = (sourceRegion.x + xOffset) / scaleX;
+- minY = (sourceRegion.y + yOffset) / scaleY;
+-
+- numTiles = (int)((Math.floor((minX + w + tileWidth - 1.0) / tileWidth) -
+- Math.floor((double)minX/tileWidth) ) *
+- (Math.floor((minY + h + tileHeight - 1.0) / tileHeight) -
+- Math.floor((double)minY/tileHeight) ) );
+- tileGridXOffset += (minX - tileGridXOffset) / tileWidth * tileWidth;
+- tileGridYOffset += (minY - tileGridYOffset) / tileHeight * tileHeight;
+-
+- return numTiles;
+- }
+-
+- /** Gets the number of components */
+- public int getNumComponents() {
+- return numComponents;
+- }
+-
+- /** Override the method setSourceBands in the super class. This method
+- * should be called before any tile-specific parameter setting method
+- * to be called.
+- */
+- public void setSourceBands(int[] bands) {
+- super.setSourceBands(bands);
+- if (bands != null) {
+- numComponents = bands.length;
+- setDefaults();
+- }
+- }
+-
+- /** Override the method setTiling in the super class. This method
+- * should be called before any tile-specific parameter setting method
+- * to be called.
+- */
+- public void setTiling(int tw, int th, int xOff, int yOff) {
+- super.setTiling(tw, th, xOff, yOff);
+- getNumTiles();
+- setDefaults();
+- }
+-
+- /** Override the method setSourceSubsampling in the super class. This
+- * method should be called before any tile-specific parameter setting
+- * method to be called.
+- */
+- public void setSourceSubsampling(int sx, int sy, int xOff, int yOff) {
+- super.setSourceSubsampling(sx, sy, xOff, yOff);
+- getNumTiles();
+- setDefaults();
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterCodecLib.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterCodecLib.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterCodecLib.java 2006-09-22 19:07:25.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterCodecLib.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,879 +0,0 @@
+-/*
+- * $RCSfile: J2KImageWriterCodecLib.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.3 $
+- * $Date: 2006/09/22 23:07:25 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.awt.Point;
+-import java.awt.Rectangle;
+-import java.awt.image.ColorModel;
+-import java.awt.image.DataBuffer;
+-import java.awt.image.DataBufferByte;
+-import java.awt.image.IndexColorModel;
+-import java.awt.image.Raster;
+-import java.awt.image.RenderedImage;
+-import java.awt.image.SampleModel;
+-import java.awt.image.WritableRaster;
+-
+-import java.io.IOException;
+-
+-import java.util.Arrays;
+-import java.util.List;
+-
+-import javax.imageio.IIOImage;
+-import javax.imageio.IIOException;
+-import javax.imageio.ImageTypeSpecifier;
+-import javax.imageio.ImageWriteParam;
+-import javax.imageio.ImageWriter;
+-import javax.imageio.metadata.IIOMetadata;
+-import javax.imageio.metadata.IIOMetadataFormatImpl;
+-import javax.imageio.metadata.IIOMetadataNode;
+-import javax.imageio.metadata.IIOInvalidTreeException;
+-import javax.imageio.spi.ImageWriterSpi;
+-import javax.imageio.stream.ImageOutputStream;
+-
+-import com.sun.media.imageio.plugins.jpeg2000.J2KImageWriteParam;
+-import com.sun.media.imageioimpl.common.ImageUtil;
+-import org.w3c.dom.Node;
+-import org.w3c.dom.NodeList;
+-
+-import com.sun.medialib.codec.jp2k.CompParams;
+-import com.sun.medialib.codec.jp2k.Constants;
+-import com.sun.medialib.codec.jp2k.Encoder;
+-import com.sun.medialib.codec.jp2k.Params;
+-import com.sun.medialib.codec.jp2k.Size;
+-import com.sun.medialib.codec.jiio.*;
+-
+-public class J2KImageWriterCodecLib extends ImageWriter {
+- /** When the writing is aborted, RenderedImageSrc
throws a
+- * RuntimeException
.
+- */
+- public static String WRITE_ABORTED = "Write aborted.";
+-
+- /** The output stream to write into */
+- private ImageOutputStream stream = null;
+-
+- /** The metadata format object. */
+- private J2KMetadataFormat format;
+-
+- /** medialib encoder. */
+- private Encoder encoder;
+-
+- /** size parameters for medialib. */
+- private Size size;
+-
+- /** The tile width for encoding */
+- private int tileWidth;
+-
+- /** The tile height for encoding */
+- private int tileHeight;
+-
+- /** The tile grid offset for encoding */
+- private int tileXOffset, tileYOffset;
+-
+- /** The source -> destination transformation */
+- private int scaleX, scaleY, xOffset, yOffset;
+-
+- /** The source bands to be encoded. */
+- private int[] sourceBands = null;
+-
+- /** The number of components in the image */
+- private int numComp;
+-
+- private RenderedImage input;
+- private J2KImageWriteParam param;
+-
+- /** The input source raster. */
+- private Raster inputRaster;
+-
+- private Rectangle destinationRegion = null;
+-
+- private SampleModel sampleModel;
+-
+- /** Coordinate transform or sub selection is needed before encoding. */
+- private boolean noTransform = true;
+- private boolean noSubband = true;
+-
+- /** Indicates a raster
rather than a RenderedImage
+- * to be encoded.
+- */
+- private boolean writeRaster = false;
+-
+- /** Constructs J2KImageWriter
based on the provided
+- * ImageWriterSpi
.
+- */
+- public J2KImageWriterCodecLib(ImageWriterSpi originator) {
+- super(originator);
+- }
+-
+- public void setOutput(Object output) {
+- super.setOutput(output); // validates output
+- if (output != null) {
+- if (!(output instanceof ImageOutputStream))
+- throw new IllegalArgumentException(I18N.getString("J2KImageWriter0"));
+- this.stream = (ImageOutputStream)output;
+- } else
+- this.stream = null;
+- }
+-
+- public ImageWriteParam getDefaultWriteParam() {
+- return new J2KImageWriteParam();
+- }
+-
+- public IIOMetadata convertStreamMetadata(IIOMetadata inData,
+- ImageWriteParam param) {
+- return null;
+- }
+-
+- public void write(IIOMetadata streamMetadata,
+- IIOImage image,
+- ImageWriteParam param) throws java.io.IOException {
+- if (stream == null) {
+- throw new IllegalStateException(I18N.getString("J2KImageWriterMedialib1"));
+- }
+- if (image == null) {
+- throw new IllegalArgumentException(I18N.getString("J2KImageWriterMedialib2"));
+- }
+- clearAbortRequest();
+- processImageStarted(0);
+- encoder = new Encoder(stream);
+-
+- writeRaster = image.hasRaster();
+- ColorModel colorModel = null;
+-
+- if (writeRaster) {
+- inputRaster = image.getRaster();
+- sampleModel = inputRaster.getSampleModel();
+- } else {
+- input = image.getRenderedImage();
+- sampleModel = input.getSampleModel();
+- colorModel = input.getColorModel();
+- }
+-
+- if (param == null)
+- param = new J2KImageWriteParam();
+-
+- if(param instanceof J2KImageWriteParam) {
+- J2KImageWriteParam j2kParam = (J2KImageWriteParam)param;
+- if (!writeRaster &&
+- input.getColorModel() instanceof IndexColorModel) {
+- j2kParam.setLossless(true);
+- j2kParam.setEncodingRate(Double.MAX_VALUE);
+- j2kParam.setFilter(J2KImageWriteParam.FILTER_53);
+- } else if (j2kParam.getEncodingRate() ==
+- Double.MAX_VALUE) {
+- j2kParam.setLossless(true);
+- j2kParam.setFilter(J2KImageWriteParam.FILTER_53);
+- }
+- }
+- setParameters(param);
+-
+- Rectangle sourceRegion = param.getSourceRegion();
+- if (sourceRegion == null) {
+- if (writeRaster)
+- sourceRegion = inputRaster.getBounds();
+- else
+- sourceRegion = new Rectangle(input.getMinX(), input.getMinY(),
+- input.getWidth(),
+- input.getHeight());
+- } else {
+- if (writeRaster)
+- sourceRegion =
+- sourceRegion.intersection(inputRaster.getBounds());
+- else
+- sourceRegion =
+- sourceRegion.intersection(new Rectangle(input.getMinX(),
+- input.getMinY(),
+- input.getWidth(),
+- input.getHeight()));
+- }
+-
+- if (sourceRegion.isEmpty())
+- throw new RuntimeException(I18N.getString("J2KImageWriterCodecLib0"));
+-
+- try {
+- tileWidth = param.getTileWidth();
+- tileHeight = param.getTileHeight();
+- tileXOffset = param.getTileGridXOffset();
+- tileYOffset = param.getTileGridYOffset();
+- } catch (IllegalStateException e) {
+- param.setTilingMode(ImageWriteParam.MODE_EXPLICIT);
+- if (writeRaster) {
+- param.setTiling(inputRaster.getWidth(),
+- inputRaster.getHeight(),
+- inputRaster.getMinX(),
+- inputRaster.getMinY());
+- } else {
+- param.setTiling(input.getTileWidth(),
+- input.getTileHeight(),
+- input.getTileGridXOffset(),
+- input.getTileGridYOffset());
+- }
+- tileWidth = param.getTileWidth();
+- tileHeight = param.getTileHeight();
+- tileXOffset = param.getTileGridXOffset();
+- tileYOffset = param.getTileGridYOffset();
+- }
+-
+- scaleX = param.getSourceXSubsampling();
+- scaleY = param.getSourceYSubsampling();
+- xOffset = param.getSubsamplingXOffset();
+- yOffset = param.getSubsamplingYOffset();
+-
+- sourceRegion.translate(xOffset, yOffset);
+- sourceRegion.width -= xOffset;
+- sourceRegion.height -= yOffset;
+-
+- xOffset = sourceRegion.x % scaleX;
+- yOffset = sourceRegion.y % scaleY;
+-
+- int minX = sourceRegion.x / scaleX;
+- int minY = sourceRegion.y / scaleY;
+-
+- int w = (sourceRegion.width + scaleX - 1) / scaleX;
+- int h = (sourceRegion.height + scaleY - 1) / scaleY;
+-
+- tileXOffset += (minX - tileXOffset)/tileWidth * tileWidth;
+- tileYOffset += (minY - tileYOffset)/tileHeight * tileHeight;
+-
+- destinationRegion = new Rectangle(minX, minY, w, h);
+-
+- if (!destinationRegion.equals(sourceRegion) ||
+- tileWidth != sampleModel.getWidth() ||
+- tileHeight != sampleModel.getHeight() ||
+- (!writeRaster &&
+- (tileXOffset != input.getTileGridXOffset() ||
+- tileYOffset != input.getTileGridYOffset())) ||
+- (writeRaster &&
+- (tileXOffset != inputRaster.getMinX() ||
+- tileYOffset != inputRaster.getMinY())))
+- noTransform = false;
+-
+- numComp = sampleModel.getNumBands();
+- sourceBands = param.getSourceBands();
+- if (sourceBands != null) {
+- sampleModel = sampleModel.createSubsetSampleModel(sourceBands);
+- colorModel = null;
+- noSubband = false;
+- } else {
+- sourceBands = new int[numComp];
+- for (int i = 0; i < numComp; i++)
+- sourceBands[i] = i;
+- }
+-
+- numComp = sourceBands.length;
+-
+- sampleModel =
+- sampleModel.createCompatibleSampleModel(tileWidth, tileHeight);
+-
+- setSize();
+-
+- setCompParameters(colorModel, sampleModel, param);
+-
+- encoder.setMode(Constants.JP2K_COMPOSITE_TILE);
+-
+- /* XXX
+- J2KMetadata metadata = (J2KMetadata)image.getMetadata();
+- ImageTypeSpecifier type = null;
+- if (colorModel != null)
+- type = new ImageTypeSpecifier(colorModel, sampleModel);
+-
+- J2KMetadata metadata1 =
+- new J2KMetadata(colorModel, sampleModel, destinationRegion.width,
+- destinationRegion.height, param, this);
+-
+- if (metadata == null)
+- metadata = metadata1;
+- else
+- metadata.mergeTree("com_sun_media_imageio_plugins_jpeg2000_image_1.0",
+- metadata1.getAsTree("com_sun_media_imageio_plugins_jpeg2000_image_1.0"));
+- */
+-
+- //write the metadata
+- if (!((J2KImageWriteParam)param).getWriteCodeStreamOnly()) {
+- IIOMetadata inMetadata = image.getMetadata();
+-
+- J2KMetadata metadata1 = new J2KMetadata(colorModel,
+- sampleModel,
+- destinationRegion.width,
+- destinationRegion.height,
+- param,
+- this);
+-
+- J2KMetadata metadata = null;
+-
+- if (inMetadata == null) {
+- metadata = metadata1;
+- } else {
+- // Convert the input metadata tree to a J2KMetadata.
+- if(colorModel != null) {
+- ImageTypeSpecifier imageType =
+- new ImageTypeSpecifier(colorModel, sampleModel);
+- metadata =
+- (J2KMetadata)convertImageMetadata(inMetadata,
+- imageType,
+- param);
+- } else {
+- String metaFormat = null;
+- List metaFormats =
+- Arrays.asList(inMetadata.getMetadataFormatNames());
+- if(metaFormats.contains(J2KMetadata.nativeMetadataFormatName)) {
+- // Initialize from native image metadata format.
+- metaFormat = J2KMetadata.nativeMetadataFormatName;
+- } else if(inMetadata.isStandardMetadataFormatSupported()) {
+- // Initialize from standard metadata form of the
+- // input tree.
+- metaFormat =
+- IIOMetadataFormatImpl.standardMetadataFormatName;
+- }
+-
+- metadata = new J2KMetadata();
+- if(metaFormat != null) {
+- metadata.setFromTree(metaFormat,
+- inMetadata.getAsTree(metaFormat));
+- }
+- }
+-
+- metadata.mergeTree(J2KMetadata.nativeMetadataFormatName,
+- metadata1.getAsTree(J2KMetadata.nativeMetadataFormatName));
+- }
+-
+- writeMetadata(metadata);
+- } else {
+- encoder.setEncodeCodeStreamOnly();
+- }
+-
+- for (int y = getMinTileY(); y <= getMaxTileY(); y++) {
+- for (int x = getMinTileX(); x <= getMaxTileX(); x++) {
+- Raster currentTile = getTile(x, y);
+- int sourceFormatTag =
+- MediaLibAccessor.findCompatibleTag(currentTile);
+-
+- MediaLibAccessor accessor =
+- new MediaLibAccessor(currentTile,
+- currentTile.getBounds(),
+- sourceFormatTag, true);
+- mediaLibImage[] mlImage = accessor.getMediaLibImages();
+-
+- encoder.encode(mlImage, x + y * size.nxtiles);
+- float percentage =
+- (x + y * size.nxtiles + 1.0F) / (size.nxtiles * size.nytiles);
+- processImageProgress(percentage * 100.0F);
+- }
+- }
+- }
+-
+- public IIOMetadata getDefaultImageMetadata(ImageTypeSpecifier imageType,
+- ImageWriteParam param) {
+- return new J2KMetadata(imageType, param, this);
+- }
+-
+- public IIOMetadata getDefaultStreamMetadata(ImageWriteParam param) {
+- return null;
+- }
+-
+- public IIOMetadata convertImageMetadata(IIOMetadata inData,
+- ImageTypeSpecifier imageType,
+- ImageWriteParam param) {
+- // Check arguments.
+- if(inData == null) {
+- throw new IllegalArgumentException("inData == null!");
+- }
+- if(imageType == null) {
+- throw new IllegalArgumentException("imageType == null!");
+- }
+-
+- // If it's one of ours, return a clone.
+- if (inData instanceof J2KMetadata) {
+- return (IIOMetadata)((J2KMetadata)inData).clone();
+- }
+-
+- try {
+- J2KMetadata outData = new J2KMetadata();
+-
+- List formats = Arrays.asList(inData.getMetadataFormatNames());
+-
+- String format = null;
+- if(formats.contains(J2KMetadata.nativeMetadataFormatName)) {
+- // Initialize from native image metadata format.
+- format = J2KMetadata.nativeMetadataFormatName;
+- } else if(inData.isStandardMetadataFormatSupported()) {
+- // Initialize from standard metadata form of the input tree.
+- format = IIOMetadataFormatImpl.standardMetadataFormatName;
+- }
+-
+- if(format != null) {
+- outData.setFromTree(format, inData.getAsTree(format));
+- return outData;
+- }
+- } catch(IIOInvalidTreeException e) {
+- return null;
+- }
+-
+- return null;
+- }
+-
+- public boolean canWriteRasters() {
+- return true;
+- }
+-
+- public synchronized void abort() {
+- super.abort();
+- }
+-
+- public void reset() {
+- // reset local Java structures
+- super.reset();
+- stream = null;
+- }
+-
+- /** This method wraps the protected method abortRequested
+- * to allow the abortions be monitored by J2KRenderedImage
.
+- */
+- public boolean getAbortRequest() {
+- return abortRequested();
+- }
+-
+- private void checkSampleModel(SampleModel sm) {
+- int type = sm.getDataType();
+-
+- if (type < DataBuffer.TYPE_BYTE || type > DataBuffer.TYPE_INT)
+- throw new IllegalArgumentException(I18N.getString("J2KImageWriter5"));
+- if (sm.getNumBands() > 16384)
+- throw new IllegalArgumentException(I18N.getString("J2KImageWriter6"));
+- }
+-
+- private void writeMetadata(J2KMetadata metadata) throws IOException {
+- if (metadata == null)
+- return;
+-
+- IIOMetadataNode root =
+- (IIOMetadataNode)metadata.getAsTree("com_sun_media_imageio_plugins_jpeg2000_image_1.0");
+- if (root == null)
+- return;
+- format =
+- (J2KMetadataFormat)metadata.getMetadataFormat("com_sun_media_imageio_plugins_jpeg2000_image_1.0");
+- writeSuperBox(root);
+- }
+-
+- private void writeSuperBox(IIOMetadataNode node) throws IOException {
+- NodeList list = node.getChildNodes();
+-
+- String name = node.getNodeName();
+- if (name.startsWith("JPEG2000")) {
+-/*
+- int length = computeLength(node);
+- byte[] data = new byte[length];
+- generateSuperBoxContent(node, data, 0);
+- com.sun.medialib.codec.jp2k.Box box =
+- new com.sun.medialib.codec.jp2k.Box();
+- box.data = data;
+- box.type = Box.getTypeInt((String)Box.getTypeByName(name));
+- encoder.encodeSuperBox(box.type, new com.sun.medialib.codec.jp2k.Box[]{box});
+- return;
+-*/
+-/*
+- com.sun.medialib.codec.jp2k.Box box =
+- new com.sun.medialib.codec.jp2k.Box();
+- box.type = Box.getTypeInt((String)Box.getTypeByName(name));
+- encoder.encodeSuperBox(box.type, null);
+-*/
+- }
+-
+- for (int i = 0; i < list.getLength(); i++) {
+- IIOMetadataNode child = (IIOMetadataNode)list.item(i);
+-
+- name = child.getNodeName();
+- if (name.startsWith("JPEG2000") && format.isLeaf(name))
+- writeBox(child);
+- else
+- writeSuperBox(child);
+- }
+- }
+-
+- private void writeBox(IIOMetadataNode node) throws IOException {
+- com.sun.medialib.codec.jp2k.Box mlibBox =
+- new com.sun.medialib.codec.jp2k.Box();
+- mlibBox.type = Box.getTypeInt((String)Box.getAttribute(node, "Type"));
+- Box box = Box.createBox(mlibBox.type, node);
+- mlibBox.data = box.getContent();
+- encoder.encodeBox(mlibBox);
+- }
+-
+- private int computeLength(IIOMetadataNode root) {
+- NodeList list = root.getChildNodes();
+- int length = 0;
+- for (int i = 0; i < list.getLength(); i++) {
+- IIOMetadataNode node = (IIOMetadataNode)list.item(i);
+- String name = node.getNodeName();
+-
+- if (format.isLeaf(name)) {
+- String s = (String)Box.getAttribute(node, "Length");
+- length += new Integer(s).intValue();
+- } else
+- length += computeLength(node);
+-
+- }
+-
+- return length + (root.getNodeName().startsWith("JPEG2000") ? 8 : 0) ;
+- }
+-
+- private int generateSuperBoxContent(IIOMetadataNode root,
+- byte[] data,
+- int pos) throws IOException {
+- String name = root.getNodeName();
+- if (name.startsWith("JPEG2000")) {
+- int length = computeLength(root);
+- Box.copyInt(data, pos, length);
+- pos += 4;
+- int type = Box.getTypeInt((String)Box.getTypeByName(name));
+- Box.copyInt(data, pos, type);
+- pos += 4;
+- }
+-
+- NodeList list = root.getChildNodes();
+- for (int i = 0; i < list.getLength(); i++) {
+- IIOMetadataNode node = (IIOMetadataNode)list.item(i);
+- name = node.getNodeName();
+-
+- if (format.isLeaf(name)) {
+- int type =
+- Box.getTypeInt((String)Box.getAttribute(node, "Type"));
+- Box box = Box.createBox(type, node);
+- byte[] data1 = box.getContent();
+- Box.copyInt(data, pos, data1.length + 8);
+- pos += 4;
+-
+- Box.copyInt(data, pos, type);
+- pos += 4;
+- System.arraycopy(data1, 0, data, pos, data1.length);
+- pos += data1.length;
+- } else {
+- pos = generateSuperBoxContent(node, data, pos);
+- }
+- }
+-
+- return pos;
+- }
+-
+- private Raster getTile(int tileX, int tileY) {
+- int sx = tileXOffset + tileX * tileWidth;
+- int sy = tileYOffset + tileY * tileHeight;
+- Rectangle bounds = new Rectangle(sx, sy, tileWidth, tileHeight);
+-
+- if (writeRaster) {
+- bounds = bounds.intersection(destinationRegion);
+- if (noTransform) {
+- return inputRaster.createChild(bounds.x, bounds.y,
+- bounds.width, bounds.height,
+- bounds.x, bounds.y, sourceBands);
+- }
+-
+- sx = bounds.x;
+- sy = bounds.y;
+- WritableRaster ras =
+- Raster.createWritableRaster(sampleModel, new Point(sx, sy));
+-
+- int x = mapToSourceX(sx);
+- int y = mapToSourceY(sy);
+-
+- int minY = inputRaster.getMinY();
+- int maxY = inputRaster.getMinY() + inputRaster.getHeight();
+-
+- int cTileWidth = bounds.width;
+-
+- int length = (cTileWidth - 1) * scaleX + 1;
+-
+- for (int j = 0; j < bounds.height; j++, sy++, y += scaleY) {
+- if (y < minY || y >= maxY)
+- continue;
+- Raster source =
+- inputRaster.createChild(x, y, length, 1,
+- x, y, null);
+- int tempX = sx;
+- for (int i = 0, offset = x; i < cTileWidth;
+- i++, tempX++, offset += scaleX) {
+- for (int k = 0; k < numComp; k++) {
+- int p = source.getSample(offset, y, sourceBands[k]);
+- ras.setSample(tempX, sy, k, p);
+- }
+- }
+- }
+-
+- return ras;
+-
+- } else {
+- if (noTransform) {
+- Raster ras = input.getTile(tileX, tileY);
+- if (destinationRegion.contains(bounds) && noSubband)
+- return ras;
+- else {
+- bounds = bounds.intersection(destinationRegion);
+- return ras.createChild(bounds.x, bounds.y,
+- bounds.width, bounds.height,
+- bounds.x, bounds.y, sourceBands);
+- }
+- }
+-
+- bounds = bounds.intersection(destinationRegion);
+- sx = bounds.x;
+- sy = bounds.y;
+-
+- WritableRaster ras =
+- Raster.createWritableRaster(sampleModel, new Point(sx, sy));
+-
+- int x = mapToSourceX(sx);
+- int y = mapToSourceY(sy);
+-
+- int minY = input.getMinY();
+- int maxY = input.getMinY() + input.getHeight();
+-
+- int cTileWidth = bounds.width;
+- int length = (cTileWidth -1) * scaleX + 1;
+-
+- for (int j = 0; j < bounds.height; j++, sy++, y += scaleY) {
+- if (y < minY || y >= maxY)
+- continue;
+-
+- Raster source =
+- input.getData(new Rectangle(x, y, length, 1));
+-
+- int tempX = sx;
+- for (int i = 0, offset = x; i < cTileWidth;
+- i++, tempX++, offset += scaleX) {
+- for (int k = 0; k < numComp; k++) {
+- int p = source.getSample(offset, y, sourceBands[k]);
+- ras.setSample(tempX, sy, k, p);
+- }
+- }
+- }
+- return ras;
+- }
+- }
+-
+- private int mapToSourceX(int x) {
+- return x * scaleX + xOffset;
+- }
+-
+- private int mapToSourceY(int y) {
+- return y * scaleY + yOffset;
+- }
+-
+- private int getMinTileX() {
+- return ToTile(destinationRegion.x, tileXOffset, tileWidth);
+- }
+-
+- private int getMaxTileX() {
+- return ToTile(destinationRegion.x + destinationRegion.width - 1,
+- tileXOffset, tileWidth);
+- }
+-
+- private int getMinTileY() {
+- return ToTile(destinationRegion.y, tileYOffset, tileHeight);
+- }
+-
+- private int getMaxTileY() {
+- return ToTile(destinationRegion.y + destinationRegion.height - 1,
+- tileYOffset, tileHeight);
+- }
+-
+- private static int ToTile(int pos, int tileOffset, int tileSize) {
+- pos -= tileOffset;
+- if (pos < 0) {
+- pos += 1 - tileSize; // force round to -infinity (ceiling)
+- }
+- return pos/tileSize;
+- }
+-
+- private void setSize() {
+- size = new Size();
+- size.csize = numComp;
+- size.nxtiles = getMaxTileX() - getMinTileX() + 1;
+- size.nytiles = getMaxTileY() - getMinTileY() + 1;
+-
+- size.xosize = destinationRegion.x;
+- size.yosize = destinationRegion.y;
+- size.xsize = destinationRegion.width + destinationRegion.x;
+- size.ysize = destinationRegion.height + destinationRegion.y;
+- size.xtosize = tileXOffset;
+- size.ytosize = tileYOffset;
+- size.xtsize = tileWidth;
+- size.ytsize = tileHeight;
+-
+- encoder.setSize(size);
+- }
+-
+- private void setCompParameters(ColorModel colorModel,
+- SampleModel sampleModel,
+- ImageWriteParam compParamArg) {
+- // Check the parameters.
+- if (colorModel == null && sampleModel == null &&
+- (compParamArg == null ||
+- !(compParamArg instanceof J2KImageWriteParam))) {
+- return;
+- }
+-
+- // Get the bit depths.
+- int[] bitDepths = null;
+- boolean isSigned = false;
+- if(colorModel != null) {
+- bitDepths = colorModel.getComponentSize();
+- isSigned = colorModel.getTransferType() == DataBuffer.TYPE_SHORT;
+- } else if(sampleModel != null) {
+- bitDepths = sampleModel.getSampleSize();
+- isSigned = sampleModel.getDataType() == DataBuffer.TYPE_SHORT;
+- }
+-
+- // Get the number of decomposition levels.
+- int numDecompositionLevels = -1;
+- if(compParamArg != null) {
+- // Cast is safe due to parameter check above.
+- numDecompositionLevels =
+- ((J2KImageWriteParam)compParamArg).getNumDecompositionLevels();
+- }
+-
+- // Return if nothing to set.
+- if(bitDepths == null && numDecompositionLevels == -1) return;
+-
+- // Check for unequal bit depths.
+- boolean bitDepthVaries = false;
+- if(bitDepths != null) {
+- for(int i = 1; i < bitDepths.length; i++) {
+- if(bitDepths[i] != bitDepths[0]) {
+- bitDepthVaries = true;
+- break;
+- }
+- }
+- }
+-
+- CompParams cp = encoder.getCompParams(null, -1);
+-
+- // Update the COD segment if needed.
+- if((numDecompositionLevels != -1 &&
+- numDecompositionLevels != cp.maxlvls) ||
+- (bitDepths != null &&
+- ((isSigned ? 0x80 : 0x00) | (bitDepths[0] - 1)) != cp.depth)) {
+-
+- if(numDecompositionLevels != -1) {
+- cp.maxlvls = numDecompositionLevels;
+- }
+-
+- // Set the main COD bit depth to bitDepths[0].
+- if(bitDepths != null) {
+- cp.depth = (isSigned ? 0x80 : 0x00) | (bitDepths[0] - 1);
+- }
+-
+- encoder.setCompParams(cp, -1);
+- }
+-
+- // Update COC segments if needed.
+- if(bitDepthVaries) { // only true if bitDepths != null
+- // Loop over component zero even though unnecessary.
+- for(int i = 0; i < numComp; i++) {
+- cp = encoder.getCompParams(null, i);
+-
+- if(numDecompositionLevels != -1) {
+- cp.maxlvls = numDecompositionLevels;
+- }
+-
+- cp.depth = (isSigned ? 0x80 : 0x00) | (bitDepths[i] - 1);
+-
+- encoder.setCompParams(cp, i);
+- }
+- }
+- }
+-
+- private void setParameters(ImageWriteParam paramArg) {
+- if (paramArg == null ||
+- !(paramArg instanceof J2KImageWriteParam)) {
+- return;
+- }
+-
+- J2KImageWriteParam param = (J2KImageWriteParam)paramArg;
+-
+- // set the rate
+- double rate = param.getEncodingRate();
+- if (rate != Double.MAX_VALUE) {
+- // convert the rate to the medialib definition
+- rate /= ImageUtil.getElementSize(sampleModel);
+- encoder.setRate(rate, 0);
+- } else
+- encoder.setRate(0.0, 0);
+-
+- Params params = new Params();
+-
+- // set the component transformation flag
+- params.enablemct = param.getComponentTransformation() ?
+- Constants.JP2K_MCT_ENABLE :
+- Constants.JP2K_MCT_DISABLE;
+-
+- // set coding style
+- if (param.getEPH())
+- params.cstyle |= Constants.JP2K_COD_EPH;
+- if (param.getSOP())
+- params.cstyle |= Constants.JP2K_COD_SOP;
+-
+- // set the wavelet filter type
+- if (J2KImageWriteParam.FILTER_53.equals(param.getFilter()))
+- params.wavemode = Constants.JP2K_WAVEMODE_53;
+- else if (J2KImageWriteParam.FILTER_97.equals(param.getFilter()))
+- params.wavemode = Constants.JP2K_WAVEMODE_97;
+-
+- //Set the progressive mode
+- String progressiveType = param.getProgressionType();
+-
+- if ("layer".equals(progressiveType))
+- params.prgorder = Constants.JP2K_COD_LRCPPRG;
+- if ("res".equals(progressiveType))
+- params.prgorder = Constants.JP2K_COD_RLCPPRG;
+- if ("res-pos".equals(progressiveType))
+- params.prgorder = Constants.JP2K_COD_RPCLPRG;
+- if ("pos-comp".equals(progressiveType))
+- params.prgorder = Constants.JP2K_COD_PCRLPRG;
+- if ("comp-pos".equals(progressiveType))
+- params.prgorder = Constants.JP2K_COD_CPRLPRG;
+-
+- encoder.setParams(params);
+- }
+-}
+-
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterCodecLibSpi.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterCodecLibSpi.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterCodecLibSpi.java 2006-03-31 14:43:39.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterCodecLibSpi.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,144 +0,0 @@
+-/*
+- * $RCSfile: J2KImageWriterCodecLibSpi.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.2 $
+- * $Date: 2006/03/31 19:43:39 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.awt.image.DataBuffer;
+-import java.awt.image.SampleModel;
+-
+-import javax.imageio.spi.ImageWriterSpi;
+-import javax.imageio.spi.ServiceRegistry;
+-import javax.imageio.spi.IIORegistry;
+-import javax.imageio.ImageWriter;
+-import javax.imageio.ImageTypeSpecifier;
+-import javax.imageio.IIOException;
+-
+-import java.awt.image.ColorModel;
+-import java.awt.image.IndexColorModel;
+-import java.util.Locale;
+-
+-import com.sun.media.imageioimpl.common.PackageUtil;
+-
+-public class J2KImageWriterCodecLibSpi extends ImageWriterSpi {
+- private static String [] readerSpiNames =
+- {"com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReaderCodecLibSpi"};
+- private static String[] formatNames =
+- {"jpeg 2000", "JPEG 2000", "jpeg2000", "JPEG2000"};
+- private static String[] extensions =
+- {"jp2"}; // Should add jpx or jpm
+- private static String[] mimeTypes = {"image/jp2", "image/jpeg2000"};
+-
+- private boolean registered = false;
+-
+- public J2KImageWriterCodecLibSpi() {
+- super(PackageUtil.getVendor(),
+- PackageUtil.getVersion(),
+- formatNames,
+- extensions,
+- mimeTypes,
+- "com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriterCodecLib",
+- STANDARD_OUTPUT_TYPE,
+- readerSpiNames,
+- false,
+- null, null,
+- null, null,
+- true,
+- "com_sun_media_imageio_plugins_jpeg2000_image_1.0",
+- "com.sun.media.imageioimpl.plugins.jpeg2000.J2KMetadataFormat",
+- null, null);
+- }
+-
+- public String getDescription(Locale locale) {
+- String desc = PackageUtil.getSpecificationTitle() +
+- " natively-accelerated JPEG 2000 Image Writer";
+- return desc;
+- }
+-
+- public void onRegistration(ServiceRegistry registry,
+- Class category) {
+- if (registered) {
+- return;
+- }
+-
+- registered = true;
+-
+- // Branch based on codecLib availability.
+- if(!PackageUtil.isCodecLibAvailable()) {
+- // Deregister provider.
+- registry.deregisterServiceProvider(this);
+- } else {
+- // Set pairwise ordering to give codecLib writer precedence.
+- Class javaWriterSPIClass = null;
+- try {
+- javaWriterSPIClass =
+- Class.forName("com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriterSpi");
+- } catch(Throwable t) {
+- // Ignore it.
+- }
+-
+- if(javaWriterSPIClass != null) {
+- Object javaWriterSPI =
+- registry.getServiceProviderByClass(javaWriterSPIClass);
+- if(javaWriterSPI != null) {
+- registry.setOrdering(category, this, javaWriterSPI);
+- }
+- }
+- }
+- }
+-
+- public boolean canEncodeImage(ImageTypeSpecifier type) {
+- SampleModel sm = type.getSampleModel();
+- if (sm.getNumBands() > 16384)
+- return false;
+- if (sm.getDataType() < DataBuffer.TYPE_BYTE ||
+- sm.getDataType() > DataBuffer.TYPE_INT)
+- return false;
+- return true;
+- }
+-
+- public ImageWriter createWriterInstance(Object extension)
+- throws IIOException {
+- return new J2KImageWriterCodecLib(this);
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriter.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriter.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriter.java 2005-02-11 00:01:34.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriter.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,514 +0,0 @@
+-/*
+- * $RCSfile: J2KImageWriter.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:34 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.awt.image.ColorModel;
+-import java.awt.image.DataBuffer;
+-import java.awt.image.DataBufferByte;
+-import java.awt.image.IndexColorModel;
+-import java.awt.image.MultiPixelPackedSampleModel;
+-import java.awt.image.Raster;
+-import java.awt.image.RenderedImage;
+-import java.awt.image.SampleModel;
+-
+-import java.io.File;
+-import java.io.IOException;
+-
+-import java.util.Arrays;
+-import java.util.List;
+-
+-import javax.imageio.IIOImage;
+-import javax.imageio.IIOException;
+-import javax.imageio.ImageTypeSpecifier;
+-import javax.imageio.ImageWriteParam;
+-import javax.imageio.ImageWriter;
+-import javax.imageio.metadata.IIOMetadata;
+-import javax.imageio.metadata.IIOMetadataFormatImpl;
+-import javax.imageio.metadata.IIOInvalidTreeException;
+-import javax.imageio.spi.ImageWriterSpi;
+-import javax.imageio.stream.ImageOutputStream;
+-
+-import jj2000.j2k.codestream.writer.CodestreamWriter;
+-import jj2000.j2k.codestream.writer.FileCodestreamWriter;
+-import jj2000.j2k.codestream.writer.HeaderEncoder;
+-import jj2000.j2k.entropy.encoder.EntropyCoder;
+-import jj2000.j2k.entropy.encoder.PostCompRateAllocator;
+-import jj2000.j2k.fileformat.writer.FileFormatWriter;
+-import jj2000.j2k.image.ImgDataConverter;
+-import jj2000.j2k.image.Tiler;
+-import jj2000.j2k.image.forwcomptransf.ForwCompTransf;
+-import jj2000.j2k.quantization.quantizer.Quantizer;
+-import jj2000.j2k.roi.encoder.ROIScaler;
+-import jj2000.j2k.util.CodestreamManipulator;
+-import jj2000.j2k.wavelet.analysis.ForwardWT;
+-
+-import com.sun.media.imageioimpl.common.ImageUtil;
+-import com.sun.media.imageio.plugins.jpeg2000.J2KImageWriteParam;
+-import org.w3c.dom.Node;
+-
+-/**
+- * The Java Image IO plugin writer for encoding a RenderedImage into
+- * a JPEG 2000 part 1 file (JP2) format.
+- *
+- * This writer has the capability to (1) Losslessly encode
+- * RenderedImage
s with an IndexColorModel
(for
+- * example, bi-level or color indexed images). (2) Losslessly or lossy encode
+- * RenderedImage
with a byte, short, ushort or integer types with
+- * band number upto 16384. (3) Encode an image with alpha channel.
+- * (4) Write the provided metadata into the code stream. It also can encode
+- * a raster wrapped in the provided IIOImage
.
+- *
+- * The encoding process may re-tile image, clip, subsample, and select bands
+- * using the parameters specified in the ImageWriteParam
.
+- *
+- * @see com.sun.media.imageio.plugins.J2KImageWriteParam
+- */
+-public class J2KImageWriter extends ImageWriter {
+- /** Wrapper for the protected method processImageProgress
+- * So it can be access from the classes which are not in
+- * ImageWriter
hierachy.
+- */
+- public void processImageProgressWrapper(float percentageDone) {
+- processImageProgress(percentageDone);
+- }
+-
+-
+- /** When the writing is aborted, RenderedImageSrc
throws a
+- * RuntimeException
.
+- */
+- public static String WRITE_ABORTED = "Write aborted.";
+-
+- /** The output stream to write into */
+- private ImageOutputStream stream = null;
+-
+- /** Constructs J2KImageWriter
based on the provided
+- * ImageWriterSpi
.
+- */
+- public J2KImageWriter(ImageWriterSpi originator) {
+- super(originator);
+- }
+-
+- public void setOutput(Object output) {
+- super.setOutput(output); // validates output
+- if (output != null) {
+- if (!(output instanceof ImageOutputStream))
+- throw new IllegalArgumentException(I18N.getString("J2KImageWriter0"));
+- this.stream = (ImageOutputStream)output;
+- } else
+- this.stream = null;
+- }
+-
+- public ImageWriteParam getDefaultWriteParam() {
+- return new J2KImageWriteParam();
+- }
+-
+- public IIOMetadata getDefaultStreamMetadata(ImageWriteParam param) {
+- return null;
+- }
+-
+- public IIOMetadata getDefaultImageMetadata(ImageTypeSpecifier imageType,
+- ImageWriteParam param) {
+- return new J2KMetadata(imageType, param, this);
+- }
+-
+- public IIOMetadata convertStreamMetadata(IIOMetadata inData,
+- ImageWriteParam param) {
+- return null;
+- }
+-
+- public IIOMetadata convertImageMetadata(IIOMetadata inData,
+- ImageTypeSpecifier imageType,
+- ImageWriteParam param) {
+- // Check arguments.
+- if(inData == null) {
+- throw new IllegalArgumentException("inData == null!");
+- }
+- if(imageType == null) {
+- throw new IllegalArgumentException("imageType == null!");
+- }
+-
+- // If it's one of ours, return a clone.
+- if (inData instanceof J2KMetadata) {
+- return (IIOMetadata)((J2KMetadata)inData).clone();
+- }
+-
+- try {
+- J2KMetadata outData = new J2KMetadata();
+-
+- List formats = Arrays.asList(inData.getMetadataFormatNames());
+-
+- String format = null;
+- if(formats.contains(J2KMetadata.nativeMetadataFormatName)) {
+- // Initialize from native image metadata format.
+- format = J2KMetadata.nativeMetadataFormatName;
+- } else if(inData.isStandardMetadataFormatSupported()) {
+- // Initialize from standard metadata form of the input tree.
+- format = IIOMetadataFormatImpl.standardMetadataFormatName;
+- }
+-
+- if(format != null) {
+- outData.setFromTree(format, inData.getAsTree(format));
+- return outData;
+- }
+- } catch(IIOInvalidTreeException e) {
+- return null;
+- }
+-
+- return null;
+- }
+-
+- public boolean canWriteRasters() {
+- return true;
+- }
+-
+- public void write(IIOMetadata streamMetadata,
+- IIOImage image,
+- ImageWriteParam param) throws IOException {
+- if (stream == null) {
+- throw new IllegalStateException(I18N.getString("J2KImageWriter7"));
+- }
+- if (image == null) {
+- throw new IllegalArgumentException(I18N.getString("J2KImageWriter8"));
+- }
+-
+- clearAbortRequest();
+- processImageStarted(0);
+- RenderedImage input = null;
+-
+- boolean writeRaster = image.hasRaster();
+- Raster raster = null;
+-
+- SampleModel sampleModel = null;
+- if (writeRaster) {
+- raster = image.getRaster();
+- sampleModel = raster.getSampleModel();
+- } else {
+- input = image.getRenderedImage();
+- sampleModel = input.getSampleModel();
+- }
+-
+- checkSampleModel(sampleModel);
+- if (param == null)
+- param = getDefaultWriteParam();
+-
+- J2KImageWriteParamJava j2kwparam =
+- new J2KImageWriteParamJava(image, param);
+-
+- // Packet header cannot exist in two places.
+- if (j2kwparam.getPackPacketHeaderInTile() &&
+- j2kwparam.getPackPacketHeaderInMain())
+- throw new IllegalArgumentException(I18N.getString("J2KImageWriter1"));
+-
+- // Lossless and encoding rate cannot be set at the same time
+- if (j2kwparam.getLossless() &&
+- j2kwparam.getEncodingRate()!=Double.MAX_VALUE)
+- throw new IllegalArgumentException(I18N.getString("J2KImageWriter2"));
+-
+- // If the source image is bilevel or color-indexed, or, the
+- // encoding rate is Double.MAX_VALUE, use lossless
+- if ((!writeRaster && input.getColorModel() instanceof IndexColorModel) ||
+- (writeRaster &&
+- raster.getSampleModel() instanceof MultiPixelPackedSampleModel)) {
+- j2kwparam.setDecompositionLevel("0");
+- j2kwparam.setLossless(true);
+- j2kwparam.setEncodingRate(Double.MAX_VALUE);
+- j2kwparam.setQuantizationType("reversible");
+- j2kwparam.setFilters(J2KImageWriteParam.FILTER_53);
+- } else if (j2kwparam.getEncodingRate() == Double.MAX_VALUE) {
+- j2kwparam.setLossless(true);
+- j2kwparam.setQuantizationType("reversible");
+- j2kwparam.setFilters(J2KImageWriteParam.FILTER_53);
+- }
+-
+- // Gets parameters from the write parameter
+- boolean pphTile = j2kwparam.getPackPacketHeaderInTile();
+- boolean pphMain = j2kwparam.getPackPacketHeaderInMain();
+- boolean tempSop = false;
+- boolean tempEph = false;
+-
+- int[] bands = param.getSourceBands();
+- int ncomp = sampleModel.getNumBands();
+-
+- if (bands != null)
+- ncomp = bands.length;
+-
+- // create the encoding source recognized by jj2000 packages
+- RenderedImageSrc imgsrc = null;
+- if (writeRaster)
+- imgsrc = new RenderedImageSrc(raster, j2kwparam, this);
+- else
+- imgsrc = new RenderedImageSrc(input, j2kwparam, this);
+-
+- // if the components signed
+- boolean[] imsigned = new boolean[ncomp];
+- if (bands != null) {
+- for (int i=0; i refx || trefy > refy)
+- throw new IIOException(I18N.getString("J2KImageWriter4"));
+-
+- // Instantiate tiler
+- Tiler imgtiler = new Tiler(imgsrc,refx,refy,trefx,trefy,tw,th);
+-
+- // Creates the forward component transform
+- ForwCompTransf fctransf = new ForwCompTransf(imgtiler, j2kwparam);
+-
+- // Creates ImgDataConverter
+- ImgDataConverter converter = new ImgDataConverter(fctransf);
+-
+- // Creates ForwardWT (forward wavelet transform)
+- ForwardWT dwt = ForwardWT.createInstance(converter, j2kwparam);
+-
+- // Creates Quantizer
+- Quantizer quant = Quantizer.createInstance(dwt,j2kwparam);
+-
+- // Creates ROIScaler
+- ROIScaler rois = ROIScaler.createInstance(quant, j2kwparam);
+-
+- // Creates EntropyCoder
+- EntropyCoder ecoder =
+- EntropyCoder.createInstance(rois, j2kwparam,
+- j2kwparam.getCodeBlockSize(),
+- j2kwparam.getPrecinctPartition(),
+- j2kwparam.getBypass(),
+- j2kwparam.getResetMQ(),
+- j2kwparam.getTerminateOnByte(),
+- j2kwparam.getCausalCXInfo(),
+- j2kwparam.getCodeSegSymbol(),
+- j2kwparam.getMethodForMQLengthCalc(),
+- j2kwparam.getMethodForMQTermination());
+-
+- // Rely on rate allocator to limit amount of data
+- File tmpFile = File.createTempFile("jiio-", ".tmp");
+- tmpFile.deleteOnExit();
+-
+- // Creates CodestreamWriter
+- FileCodestreamWriter bwriter =
+- new FileCodestreamWriter(tmpFile, Integer.MAX_VALUE);
+-
+- // Creates the rate allocator
+- float rate = (float)j2kwparam.getEncodingRate();
+- PostCompRateAllocator ralloc =
+- PostCompRateAllocator.createInstance(ecoder,
+- rate,
+- bwriter,
+- j2kwparam);
+-
+- // Instantiates the HeaderEncoder
+- HeaderEncoder headenc =
+- new HeaderEncoder(imgsrc, imsigned, dwt, imgtiler,
+- j2kwparam, rois,ralloc);
+-
+- ralloc.setHeaderEncoder(headenc);
+-
+- // Writes header to be able to estimate header overhead
+- headenc.encodeMainHeader();
+-
+- //Initializes rate allocator, with proper header
+- // overhead. This will also encode all the data
+- try {
+- ralloc.initialize();
+- } catch (RuntimeException e) {
+- if (WRITE_ABORTED.equals(e.getMessage())) {
+- bwriter.close();
+- tmpFile.delete();
+- processWriteAborted();
+- return;
+- } else throw e;
+- }
+-
+- // Write header (final)
+- headenc.reset();
+- headenc.encodeMainHeader();
+-
+- // Insert header into the codestream
+- bwriter.commitBitstreamHeader(headenc);
+-
+- // Now do the rate-allocation and write result
+- ralloc.runAndWrite();
+-
+- //Done for data encoding
+- bwriter.close();
+-
+- // Calculate file length
+- int fileLength = bwriter.getLength();
+-
+- // Tile-parts and packed packet headers
+- int pktspertp = j2kwparam.getPacketPerTilePart();
+- int ntiles = imgtiler.getNumTiles();
+- if (pktspertp>0 || pphTile || pphMain){
+- CodestreamManipulator cm =
+- new CodestreamManipulator(tmpFile, ntiles, pktspertp,
+- pphMain, pphTile, tempSop,
+- tempEph);
+- fileLength += cm.doCodestreamManipulation();
+- }
+-
+- // File Format
+- int nc= imgsrc.getNumComps() ;
+- int[] bpc = new int[nc];
+- for(int comp = 0; compabortRequested
+- * to allow the abortions be monitored by J2KRenderedImage
.
+- */
+- public boolean getAbortRequest() {
+- return abortRequested();
+- }
+-
+- private void checkSampleModel(SampleModel sm) {
+- int type = sm.getDataType();
+-
+- if (type < DataBuffer.TYPE_BYTE || type > DataBuffer.TYPE_INT)
+- throw new IllegalArgumentException(I18N.getString("J2KImageWriter5"));
+- if (sm.getNumBands() > 16384)
+- throw new IllegalArgumentException(I18N.getString("J2KImageWriter6"));
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterResources.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterResources.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterResources.java 2005-02-11 00:01:35.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterResources.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,57 +0,0 @@
+-/*
+- * $RCSfile: J2KImageWriterResources.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:35 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-public class J2KImageWriterResources {
+- static final Object[][] contents = {
+- };
+-
+- public J2KImageWriterResources() {}
+-
+- public Object[][] getContents() {
+- return contents;
+- }
+-}
+-
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterSpi.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterSpi.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterSpi.java 2006-03-31 14:43:39.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterSpi.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,139 +0,0 @@
+-/*
+- * $RCSfile: J2KImageWriterSpi.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.2 $
+- * $Date: 2006/03/31 19:43:39 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.awt.image.DataBuffer;
+-import java.awt.image.SampleModel;
+-
+-import javax.imageio.spi.ImageWriterSpi;
+-import javax.imageio.spi.ServiceRegistry;
+-import javax.imageio.spi.IIORegistry;
+-import javax.imageio.ImageWriter;
+-import javax.imageio.ImageTypeSpecifier;
+-import javax.imageio.IIOException;
+-
+-import java.awt.image.ColorModel;
+-import java.awt.image.IndexColorModel;
+-import java.util.Locale;
+-
+-import com.sun.media.imageioimpl.common.PackageUtil;
+-
+-import com.sun.medialib.codec.jiio.Util;
+-
+-public class J2KImageWriterSpi extends ImageWriterSpi {
+- private static String [] readerSpiNames =
+- {"com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReaderSpi"};
+- private static String[] formatNames =
+- {"jpeg 2000", "JPEG 2000", "jpeg2000", "JPEG2000"};
+- private static String[] extensions =
+- {"jp2"}; // Should add jpx or jpm
+- private static String[] mimeTypes = {"image/jp2", "image/jpeg2000"};
+- private boolean registered = false;
+-
+- public J2KImageWriterSpi() {
+- super(PackageUtil.getVendor(),
+- PackageUtil.getVersion(),
+- formatNames,
+- extensions,
+- mimeTypes,
+- "com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriter",
+- STANDARD_OUTPUT_TYPE,
+- readerSpiNames,
+- false,
+- null, null,
+- null, null,
+- true,
+- "com_sun_media_imageio_plugins_jpeg2000_image_1.0",
+- "com.sun.media.imageioimpl.plugins.jpeg2000.J2KMetadataFormat",
+- null, null);
+- }
+-
+- public String getDescription(Locale locale) {
+- String desc = PackageUtil.getSpecificationTitle() +
+- " JPEG 2000 Image Writer";
+- return desc;
+- }
+-
+- public void onRegistration(ServiceRegistry registry,
+- Class category) {
+- if (registered) {
+- return;
+- }
+-
+- registered = true;
+-
+- // Set pairwise ordering to give codecLib writer precedence.
+- Class codecLibWriterSPIClass = null;
+- try {
+- codecLibWriterSPIClass =
+- Class.forName("com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriterCodecLibSpi");
+- } catch(Throwable t) {
+- // Ignore it.
+- }
+-
+- if(codecLibWriterSPIClass != null) {
+- Object codecLibWriterSPI =
+- registry.getServiceProviderByClass(codecLibWriterSPIClass);
+- if(codecLibWriterSPI != null) {
+- registry.setOrdering(category, codecLibWriterSPI, this);
+- }
+- }
+- }
+-
+- public boolean canEncodeImage(ImageTypeSpecifier type) {
+- SampleModel sm = type.getSampleModel();
+- if (sm.getNumBands() > 16384)
+- return false;
+- if (sm.getDataType() < DataBuffer.TYPE_BYTE ||
+- sm.getDataType() > DataBuffer.TYPE_INT)
+- return false;
+- return true;
+- }
+-
+- public ImageWriter createWriterInstance(Object extension)
+- throws IIOException {
+- return new J2KImageWriter(this);
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadataFormat.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadataFormat.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadataFormat.java 2005-04-27 14:23:01.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadataFormat.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,351 +0,0 @@
+-/*
+- * $RCSfile: J2KMetadataFormat.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.2 $
+- * $Date: 2005/04/27 18:23:01 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.awt.image.ColorModel;
+-import java.awt.image.IndexColorModel;
+-
+-import java.lang.reflect.Method;
+-import java.util.ArrayList;
+-import java.util.Enumeration;
+-import java.util.Hashtable;
+-import java.util.Iterator;
+-import java.util.List;
+-import java.util.Set;
+-import javax.imageio.metadata.*;
+-import javax.imageio.ImageTypeSpecifier;
+-
+-public class J2KMetadataFormat extends IIOMetadataFormatImpl {
+- /** The table to link the child to its parent.
+- */
+- private static Hashtable parents = new Hashtable();
+-
+- static {
+- //children for the root
+- parents.put("JPEG2000SignatureBox", "com_sun_media_imageio_plugins_jpeg2000_image_1.0");
+- parents.put("JPEG2000FileTypeBox", "com_sun_media_imageio_plugins_jpeg2000_image_1.0");
+- parents.put("OtherBoxes", "com_sun_media_imageio_plugins_jpeg2000_image_1.0");
+-
+- // children for the boxes other than
+- // JPEG2000SignatureBox/JPEG2000FileTypeBox
+- parents.put("JPEG2000HeaderSuperBox", "OtherBoxes");
+- parents.put("JPEG2000CodeStreamBox", "OtherBoxes");
+-
+- parents.put("JPEG2000IntellectualPropertyRightsBox", "OtherBoxes");
+- parents.put("JPEG2000XMLBox", "OtherBoxes");
+- parents.put("JPEG2000UUIDBox", "OtherBoxes");
+- parents.put("JPEG2000UUIDInfoBox", "OtherBoxes");
+-
+- // Children of JPEG2000HeaderSuperBox
+- parents.put("JPEG2000HeaderBox", "JPEG2000HeaderSuperBox");
+- parents.put("OptionalBoxes", "JPEG2000HeaderSuperBox");
+-
+- // Optional boxes in JPEG2000HeaderSuperBox
+- parents.put("JPEG2000BitsPerComponentBox", "OptionalBoxes");
+- parents.put("JPEG2000ColorSpecificationBox", "OptionalBoxes");
+- parents.put("JPEG2000PaletteBox", "OptionalBoxes");
+- parents.put("JPEG2000ComponentMappingBox", "OptionalBoxes");
+- parents.put("JPEG2000ChannelDefinitionBox", "OptionalBoxes");
+- parents.put("JPEG2000ResolutionBox", "OptionalBoxes");
+-
+- // Children of JPEG2000ResolutionBox
+- parents.put("JPEG2000CaptureResolutionBox", "JPEG2000ResolutionBox");
+- parents.put("JPEG2000DefaultDisplayResolutionBox",
+- "JPEG2000ResolutionBox");
+-
+- // Children of JPEG2000UUIDInfoBox
+- parents.put("JPEG2000UUIDListBox", "JPEG2000UUIDInfoBox");
+- parents.put("JPEG2000DataEntryURLBox", "JPEG2000UUIDInfoBox");
+- }
+-
+- private static J2KMetadataFormat instance;
+-
+- public static synchronized J2KMetadataFormat getInstance() {
+- if (instance == null)
+- instance = new J2KMetadataFormat();
+- return instance;
+- }
+-
+- String resourceBaseName = this.getClass().getName() + "Resources";
+-
+- /** Constructs J2KMetadataFormat
. Calls the super
+- * class constructor. Sets the resource base name. Adds the elements
+- * into this format object based on the XML schema and DTD.
+- */
+- J2KMetadataFormat() {
+- super("com_sun_media_imageio_plugins_jpeg2000_image_1.0", CHILD_POLICY_ALL);
+- setResourceBaseName(resourceBaseName);
+- addElements();
+- }
+-
+- /** Adds the elements into this format object based on the XML
+- * schema and DTD.
+- */
+- private void addElements() {
+- addElement("JPEG2000SignatureBox",
+- getParent("JPEG2000SignatureBox"),
+- CHILD_POLICY_EMPTY);
+-
+- addElement("JPEG2000FileTypeBox",
+- getParent("JPEG2000FileTypeBox"),
+- CHILD_POLICY_ALL);
+- addElement("OtherBoxes",
+- getParent("OtherBoxes"),
+- CHILD_POLICY_CHOICE);
+-
+- addElement("JPEG2000HeaderSuperBox",
+- getParent("JPEG2000HeaderSuperBox"),
+- CHILD_POLICY_CHOICE);
+- addElement("JPEG2000CodeStreamBox",
+- getParent("JPEG2000CodeStreamBox"),
+- CHILD_POLICY_EMPTY);
+- addElement("JPEG2000IntellectualPropertyRightsBox",
+- getParent("JPEG2000IntellectualPropertyRightsBox"),
+- CHILD_POLICY_ALL);
+- addElement("JPEG2000XMLBox",
+- getParent("JPEG2000XMLBox"),
+- CHILD_POLICY_ALL);
+- addElement("JPEG2000UUIDBox",
+- getParent("JPEG2000UUIDBox"),
+- CHILD_POLICY_ALL);
+- addElement("JPEG2000UUIDInfoBox",
+- getParent("JPEG2000UUIDInfoBox"),
+- CHILD_POLICY_ALL);
+-
+- addElement("JPEG2000HeaderBox",
+- "JPEG2000HeaderSuperBox",
+- CHILD_POLICY_ALL);
+- addElement("OptionalBoxes",
+- "JPEG2000HeaderSuperBox",
+- CHILD_POLICY_CHOICE);
+- addElement("JPEG2000BitsPerComponentBox",
+- "OptionalBoxes",
+- CHILD_POLICY_ALL);
+- addElement("JPEG2000ColorSpecificationBox",
+- "OptionalBoxes",
+- CHILD_POLICY_ALL);
+- addElement("JPEG2000PaletteBox",
+- "OptionalBoxes",
+- CHILD_POLICY_ALL);
+- addElement("JPEG2000ComponentMappingBox",
+- "OptionalBoxes",
+- CHILD_POLICY_ALL);
+- addElement("JPEG2000ChannelDefinitionBox",
+- "OptionalBoxes",
+- CHILD_POLICY_ALL);
+- addElement("JPEG2000ResolutionBox",
+- "OptionalBoxes",
+- CHILD_POLICY_ALL);
+-
+- addElement("JPEG2000CaptureResolutionBox",
+- "JPEG2000ResolutionBox",
+- CHILD_POLICY_ALL);
+- addElement("JPEG2000DefaultDisplayResolutionBox",
+- "JPEG2000ResolutionBox",
+- CHILD_POLICY_ALL);
+-
+- addElement("JPEG2000UUIDListBox",
+- "JPEG2000UUIDInfoBox",
+- CHILD_POLICY_ALL);
+- addElement("JPEG2000DataEntryURLBox",
+- "JPEG2000UUIDInfoBox",
+- CHILD_POLICY_ALL);
+- // Adds the default attributes "Length", "Type" and "ExtraLength" into
+- // the J2K box-related data elements
+- Enumeration keys = parents.keys();
+- while (keys.hasMoreElements()) {
+- String s = (String)keys.nextElement();
+- if (s.startsWith("JPEG2000")) {
+- addAttribute(s, "Length", DATATYPE_INTEGER, true, null);
+- addAttribute(s, "Type", DATATYPE_STRING, true, Box.getTypeByName(s));
+- addAttribute(s, "ExtraLength", DATATYPE_STRING, false, null);
+-
+- // If it is a simple node, adds the data elements by using
+- // relection.
+- Class c = Box.getBoxClass(Box.getTypeInt(Box.getTypeByName(s)));
+-
+- try {
+- Method m = c.getMethod("getElementNames", (Class[])null);
+- String[] elementNames = (String[])m.invoke(null,
+- (Object[])null);
+- for (int i = 0; i < elementNames.length; i++)
+- addElement(elementNames[i], s, CHILD_POLICY_EMPTY);
+- } catch (Exception e) {
+- // no such method
+- }
+- }
+- }
+-
+- addAttribute("JPEG2000SignatureBox",
+- "Signature",
+- DATATYPE_STRING,
+- true,
+- "0D0A870A");
+-
+- addElement("BitDepth",
+- "JPEG2000BitsPerComponentBox",
+- CHILD_POLICY_EMPTY);
+-
+- addElement("NumberEntries",
+- "JPEG2000PaletteBox",
+- CHILD_POLICY_EMPTY);
+-
+- addElement("NumberColors",
+- "JPEG2000PaletteBox",
+- CHILD_POLICY_EMPTY);
+-
+- addElement("BitDepth",
+- "JPEG2000PaletteBox",
+- CHILD_POLICY_EMPTY);
+-
+- addElement("LUT",
+- "JPEG2000PaletteBox",
+- 1, 1024);
+-
+- addElement("LUTRow",
+- "LUT",
+- CHILD_POLICY_EMPTY);
+-
+- addElement("Component",
+- "JPEG2000ComponentMappingBox",
+- CHILD_POLICY_EMPTY);
+-
+- addElement("ComponentType",
+- "JPEG2000ComponentMappingBox",
+- CHILD_POLICY_EMPTY);
+-
+- addElement("ComponentAssociation",
+- "JPEG2000ComponentMappingBox",
+- CHILD_POLICY_EMPTY);
+-
+- addElement("NumberOfDefinition",
+- "JPEG2000ChannelDefinitionBox",
+- CHILD_POLICY_EMPTY);
+-
+- addElement("Definitions",
+- "JPEG2000ChannelDefinitionBox",
+- 0, 9);
+-
+- addElement("ChannelNumber",
+- "Definitions",
+- CHILD_POLICY_EMPTY);
+-
+- addElement("ChannelType",
+- "Definitions",
+- CHILD_POLICY_EMPTY);
+- addElement("ChannelAssociation",
+- "Definitions",
+- CHILD_POLICY_EMPTY);
+- addElement("CodeStream",
+- "JPEG2000CodeStreamBox",
+- CHILD_POLICY_EMPTY);
+- addElement("Content",
+- "JPEG2000IntellectualPropertyRightsBox",
+- CHILD_POLICY_EMPTY);
+- addElement("Content",
+- "JPEG2000XMLBox",
+- CHILD_POLICY_EMPTY);
+- addElement("UUID",
+- "JPEG2000UUIDBox",
+- CHILD_POLICY_EMPTY);
+- addElement("Data",
+- "JPEG2000UUIDBox",
+- CHILD_POLICY_EMPTY);
+- addElement("NumberUUID",
+- "JPEG2000UUIDListBox",
+- CHILD_POLICY_EMPTY);
+- addElement("UUID",
+- "JPEG2000UUIDListBox",
+- CHILD_POLICY_EMPTY);
+- addElement("Version",
+- "JPEG2000DataEntryURLBox",
+- CHILD_POLICY_EMPTY);
+- addElement("Flags",
+- "JPEG2000DataEntryURLBox",
+- CHILD_POLICY_EMPTY);
+- addElement("URL",
+- "JPEG2000DataEntryURLBox",
+- CHILD_POLICY_EMPTY);
+- }
+-
+- public String getParent(String elementName) {
+- return (String)parents.get(elementName);
+- }
+-
+- public boolean canNodeAppear(String elementName,
+- ImageTypeSpecifier imageType) {
+- ColorModel cm = imageType.getColorModel();
+- if (!(cm instanceof IndexColorModel))
+- if ("JPEG2000PaletteBox".equals(elementName))
+- return false;
+- if (!cm.hasAlpha())
+- if ("JPEG2000ChannelDefinitionBox".equals(elementName))
+- return false;
+-
+- if (getParent(elementName) != null)
+- return true;
+- return false;
+- }
+-
+- public boolean isLeaf(String name) {
+- Set keys = parents.keySet();
+- Iterator iterator = keys.iterator();
+- while(iterator.hasNext()) {
+- if (name.equals(parents.get(iterator.next())))
+- return false;
+- }
+-
+- return true;
+- }
+-
+- public boolean singleInstance(String name) {
+- return !(name.equals("JPEG2000IntellectualPropertyRightsBox") ||
+- name.equals("JPEG2000XMLBox") ||
+- name.equals("JPEG2000UUIDBox") ||
+- name.equals("JPEG2000UUIDInfoBox") ||
+- name.equals("JPEG2000UUIDListBox") ||
+- name.equals("JPEG2000DataEntryURLBox"));
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadataFormatResources.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadataFormatResources.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadataFormatResources.java 2005-02-11 00:01:35.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadataFormatResources.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,280 +0,0 @@
+-/*
+- * $RCSfile: J2KMetadataFormatResources.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:35 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.util.*;
+-
+-public class J2KMetadataFormatResources extends ListResourceBundle {
+- static final Object[][] contents = {
+- // Node name, followed by description
+- {"JPEG2000SignatureBox", "The JPEG 2000 signature box."},
+- {"JPEG2000FileTypeBox", "The JPEG 2000 file type box."},
+- {"OtherBoxes",
+- "All the boxes other than the signature or file type box."},
+- {"HeaderCStream",
+- "The super box conatins the header and code stream box."},
+- {"JPEG2000IntellectualPropertyRightsBox",
+- "The JPEG 2000 intellectual property rights box."},
+- {"JPEG2000XMLBox", "The JPEG 2000 XML box."},
+- {"JPEG2000UUIDBox", "The JPEG 2000 UUID box."},
+- {"JPEG2000UUIDInfoBox", "The JPEG 2000 UUID information box."},
+- {"JPEG2000HeaderSuperBox", "The JPEG 2000 header super box."},
+- {"JPEG2000CodeStreamBox", "The JPEG 2000 code stream box."},
+- {"JPEG2000HeaderBox", "The JPEG 2000 header box."},
+- {"OptionalBoxes", "The optional boxes in the header super box."},
+- {"JPEG2000BitsPerComponentBox", "The JPEG2000 bits per component box."},
+- {"JPEG2000ColorSpecificationBox",
+- "The JPEG 2000 color specification box."},
+- {"JPEG2000PaletteBox", "The JPEG 2000 palette box."},
+- {"JPEG2000ComponentMappingBox", "The JPEG 2000 component mapping box."},
+- {"JPEG2000ChannelDefinitionBox",
+- "The JPEG 2000 channel definition box."},
+- {"JPEG2000ResolutionBox", "The JPEG 2000 resolution box."},
+- {"JPEG2000CaptureResolutionBox",
+- "The JPEG 2000 capture resolution box"},
+- {"JPEG2000DefaultDisplayResolutionBox",
+- "The JPEG 2000 default display resolution box"},
+- {"JPEG2000UUIDListBox", "The JPEG 2000 UUID list box."},
+- {"JPEG2000DataEntryURLBox", "The JPEG 2000 data entry URL box."},
+-
+- // Elements in JPEG2000FileTypeBox
+- {"Brand", "The brand of JPEG 2000 file. For JP2 file, it is \"jp2 \""},
+- {"MinorVersion",
+- "The minor version of JPEG 2000 file. For JP2 file, it is 0"},
+- {"CompatibilityList",
+- "The compatibility list. For non-JP2 file, at least one is \"jp2 \""},
+-
+- // Elements of JPEG2000HeaderBox
+- {"Width", "The width of the image."},
+- {"Height", "The height of the image."},
+- {"NumComponents", "The number of image components in this image file."},
+- {"BitDepth",
+- "Bit depths for all the image components or for each of the component if it is a array."},
+- {"CompressionType", "The compression type. Always be 7 for JP2 file."},
+- {"UnknownColorspace", "Whether the color space is known or not."},
+- {"IntellectualProperty",
+- "Whether intellectual property in included in this image."},
+-
+-
+- {"Method",
+- "The method to define the color space. 1 by ECS; 2 by profile."},
+- {"Precedence", "Precedence. Be 0 for JP2 file."},
+- {"ApproximationAccuracy", "Approximation accuracy. Be 0 for JP2 file"},
+- {"EnumeratedColorSpace", "Enumerated color space. 16: sRGB. 17: Gray"},
+- {"ICCProfile", "The ICC profile used to define the color space"},
+-
+- {"NumberEntries", "The number of palette entries."},
+- {"NumberColors", "The number of color components."},
+- {"BitDepth", "The bit depths for the output components after LUT."},
+- {"LUT", "The LUT for the palette."},
+- {"LUTRow", " A row of the LUT."},
+-
+- {"Component", "A component in the component mapping box."},
+- {"ComponentType", "The type of one component: itself or lut column."},
+- {"ComponentAssociation",
+- "The LUT column used to define this component."},
+-
+- {"NumberOfDefinition",
+- "The number of definitions in channel definition box."},
+- {"Definitions", "Defines one channel."},
+- {"ChannelNumber", "The channel number."},
+- {"ChannelType", "The channel type: color, alpha, premultiplied alpha."},
+- {"ChannelAssociation",
+- "The association of this channel to the color space."},
+-
+- {"VerticalResolutionNumerator", "The vertical resolution numerator."},
+- {"VerticalResolutionDenominator",
+- "The vertical resolution denominator."},
+- {"HorizontalResolutionNumerator",
+- "The horizontal resolution numerator."},
+- {"HorizontalResolutionDenominator",
+- "The horizontal resolution denominator."},
+- {"VerticalResolutionExponent", "The vertical resolution exponent."},
+- {"HorizontalResolutionExponent", "The horizontal resolution exponent."},
+-
+- {"CodeStream", "The data of the code stream."},
+- {"Content", "The intellectual property rights or XML."},
+-
+- {"UUID", "The UUID."},
+- {"Data", "The data of the UUID."},
+- {"NumberUUID", "The number of UUID in the UUID list box."},
+-
+- {"Version", "The version. Always be 0 for JP2 file."},
+- {"Flags", "The flags. Always be 0 for JP2 file."},
+- {"URL", "The URL"},
+-
+- // Node name + "/" + AttributeName, followed by description
+- {"JPEG2000SignatureBox/Length",
+- "The length of the signature box. Always be 12."},
+- {"JPEG2000SignatureBox/Type",
+- "The type of the signature box. Always be \"jP \""},
+- {"JPEG2000SignatureBox/Signature",
+- "The content of the signature box. Always be 0D0A870A."},
+-
+- {"JPEG2000FileTypeBox/Length", "The length of the file type box."},
+- {"JPEG2000FileTypeBox/Type",
+- "The type of the file type box. Always be \"ftpy\""},
+- {"JPEG2000FileTypeBox/ExtraLength",
+- "The extra length of the file type box. Optional. Set when Length = 1"},
+-
+- {"JPEG2000HeaderSuperBox/Length",
+- "The length of the header super box."},
+- {"JPEG2000HeaderSuperBox/Type",
+- "The type of the header super box. Always be \"jp2h\""},
+- {"JPEG2000HeaderSuperBox/ExtraLength",
+- "The extra length of the header super box. Optional. Set when Length = 1"},
+-
+- {"JPEG2000HeaderBox/Length", "The length of the header box."},
+- {"JPEG2000HeaderBox/Type",
+- "The type of the header box. Always be \"ihdr\""},
+- {"JPEG2000HeaderBox/ExtraLength",
+- "The extra length of the header box. Optional. Set when Length = 1"},
+-
+- {"JPEG2000BitsPerComponentBox/Length",
+- "The length of the bits per component box."},
+- {"JPEG2000BitsPerComponentBox/Type",
+- "The type of the bits per component box. Always be \"bpcc\""},
+- {"JPEG2000BitsPerComponentBox/ExtraLength",
+- "The extra length of the bits per component box. Optional. Set when Length = 1"},
+-
+- {"JPEG2000ColorSpecificationBox/Length",
+- "The length of the bits per component box."},
+- {"JPEG2000ColorSpecificationBox/Type",
+- "The type of the bits per component box. Always be \"colr\""},
+- {"JPEG2000ColorSpecificationBox/ExtraLength",
+- "The extra length of the bits per component box. Optional. Set when Length = 1"},
+-
+- {"JPEG2000PaletteBox/Length", "The length of the palette box."},
+- {"JPEG2000PaletteBox/Type",
+- "The type of the palette box. Always be \"pclr\""},
+- {"JPEG2000PaletteBox/ExtraLength",
+- "The extra length of the palette box. Optional. Set when Length = 1"},
+-
+- {"JPEG2000ComponentMappingBox/Length",
+- "The length of the component mapping box."},
+- {"JPEG2000ComponentMappingBox/Type",
+- "The type of the component mapping box. Always be \"cmap\""},
+- {"JPEG2000ComponentMappingBox/ExtraLength",
+- "The extra length of the component mapping box. Optional. Set when Length = 1"},
+-
+- {"JPEG2000ChannelDefinitionBox/Length",
+- "The length of the channel definition box."},
+- {"JPEG2000ChannelDefinitionBox/Type",
+- "The type of the channel definition box. Always be \"cdef\""},
+- {"JPEG2000ChannelDefinitionBox/ExtraLength",
+- "The extra length of the channel definition box. Optional. Set when Length = 1"},
+-
+- {"JPEG2000ResolutionBox/Length", "The length of the resolution box."},
+- {"JPEG2000ResolutionBox/Type",
+- "The type of the resolution box. Always be \"res \""},
+- {"JPEG2000ResolutionBox/ExtraLength",
+- "The extra length of the resolution box. Optional. Set when Length = 1"},
+-
+- {"JPEG2000CaptureResolutionBox/Length",
+- "The length of the capture resolution box."},
+- {"JPEG2000CaptureResolutionBox/Type",
+- "The type of the capture resolution box. Always be \"resc\""},
+- {"JPEG2000CaptureResolutionBox/ExtraLength",
+- "The extra length of the capture resolution box. Optional. Set when Length = 1"},
+-
+- {"JPEG2000DefaultDisplayResolutionBox/Length",
+- "The length of the default display resolution box."},
+- {"JPEG2000DefaultDisplayResolutionBox/Type",
+- "The type of the default display resolution box. Always be \"resd\""},
+- {"JPEG2000DefaultDisplayResolutionBox/ExtraLength",
+- "The extra length of the default display resolution box. Optional. Set when Length = 1"},
+-
+- {"JPEG2000CodeStreamBox/Length", "The length of the code stream box."},
+- {"JPEG2000CodeStreamBox/Type",
+- "The type of the code stream box. Always be \"jp2c\""},
+- {"JPEG2000CodeStreamBox/ExtraLength",
+- "The extra length of the code stream box. Optional. Set when Length = 1"},
+-
+- {"JPEG2000IntellectualPropertyRightsBox/Length",
+- "The length of the intellectual property rights box."},
+- {"JPEG2000IntellectualPropertyRightsBox/Type",
+- "The type of the intellectual property rights box. Always be \"jp2i\""},
+- {"JPEG2000IntellectualPropertyRightsBox/ExtraLength",
+- "The extra length of the intellectual property rights box. Optional. Set when Length = 1"},
+-
+- {"JPEG2000XMLBox/Length", "The length of the XML box."},
+- {"JPEG2000XMLBox/Type", "The type of the XML box. Always be \"xml \""},
+- {"JPEG2000XMLBox/ExtraLength",
+- "The extra length of the XML box. Optional. Set when Length = 1"},
+-
+- {"JPEG2000UUIDBox/Length", "The length of the UUID box."},
+- {"JPEG2000UUIDBox/Type",
+- "The type of the UUID box. Always be \"uuid\""},
+- {"JPEG2000UUIDBox/ExtraLength",
+- "The extra length of the UUID box. Optional. Set when Length = 1"},
+-
+- {"JPEG2000UUIDInfoBox/Length", "The length of the UUID information box."},
+- {"JPEG2000UUIDInfoBox/Type",
+- "The type of the UUID information box. Always be \"uinf\""},
+- {"JPEG2000UUIDInfoBox/ExtraLength",
+- "The extra length of the UUID information box. Optional. Set when Length = 1"},
+-
+- {"JPEG2000UUIDListBox/Length", "The length of the UUID list box."},
+- {"JPEG2000UUIDListBox/Type",
+- "The type of the UUID list box. Always be \"ulst\""},
+- {"JPEG2000UUIDListBox/ExtraLength",
+- "The extra length of the UUID list box. Optional. Set when Length = 1"},
+-
+- {"JPEG2000DataEntryURLBox/Length",
+- "The length of the data entry URL box."},
+- {"JPEG2000DataEntryURLBox/Type",
+- "The type of the data entry URL box. Always be \"ulst\""},
+- {"JPEG2000DataEntryURLBox/ExtraLength",
+- "The extra length of the data entry URL box. Optional. Set when Length = 1"},
+- };
+-
+- public J2KMetadataFormatResources() {
+- }
+-
+- protected Object[][] getContents() {
+- return contents;
+- }
+-}
+-
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadata.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadata.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadata.java 2006-09-22 19:07:25.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadata.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,1051 +0,0 @@
+-/*
+- * $RCSfile: J2KMetadata.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.4 $
+- * $Date: 2006/09/22 23:07:25 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.io.InputStream;
+-
+-import javax.imageio.ImageTypeSpecifier;
+-import javax.imageio.ImageWriteParam;
+-import javax.imageio.ImageWriter;
+-import javax.imageio.IIOException;
+-import javax.imageio.stream.ImageInputStream;
+-import javax.imageio.stream.ImageOutputStream;
+-import javax.imageio.metadata.IIOMetadata;
+-import javax.imageio.metadata.IIOMetadataNode;
+-import javax.imageio.metadata.IIOMetadataFormat;
+-import javax.imageio.metadata.IIOMetadataFormatImpl;
+-import javax.imageio.metadata.IIOInvalidTreeException;
+-
+-import org.w3c.dom.Node;
+-import org.w3c.dom.NodeList;
+-import org.w3c.dom.NamedNodeMap;
+-
+-import java.util.List;
+-import java.util.ArrayList;
+-import java.util.Arrays;
+-import java.util.Hashtable;
+-import java.util.Iterator;
+-import java.util.ListIterator;
+-import java.io.IOException;
+-import java.awt.color.ICC_Profile;
+-import java.awt.color.ICC_ColorSpace;
+-import java.awt.color.ColorSpace;
+-import java.awt.image.ColorModel;
+-import java.awt.image.DataBuffer;
+-import java.awt.image.IndexColorModel;
+-import java.awt.image.SampleModel;
+-import java.awt.Point;
+-
+-import com.sun.media.imageio.plugins.jpeg2000.J2KImageReadParam;
+-import com.sun.media.imageio.plugins.jpeg2000.J2KImageWriteParam;
+-
+-import jj2000.j2k.fileformat.FileFormatBoxes;
+-import jj2000.j2k.fileformat.reader.FileFormatReader;
+-import jj2000.j2k.io.RandomAccessIO;
+-
+-/**
+- * Metadata for the J2K plug-in.
+- */
+-public class J2KMetadata extends IIOMetadata implements Cloneable {
+- static final String nativeMetadataFormatName =
+- "com_sun_media_imageio_plugins_jpeg2000_image_1.0";
+-
+- /** cache the metadata format */
+- private J2KMetadataFormat format;
+-
+- /** The boxes of JP2 file used as meta data, i. e., all the boxes
+- * except the data stream box
+- */
+- private ArrayList boxes = new ArrayList();
+-
+- /**
+- * Constructor containing code shared by other constructors.
+- */
+- public J2KMetadata() {
+- super(true, // Supports standard format
+- nativeMetadataFormatName, // and a native format
+- "com.sun.media.imageioimpl.plugins.jpeg2000.J2KMetadataFormat",
+- null, null); // No other formats
+-
+- format = (J2KMetadataFormat)getMetadataFormat(nativeMetadataFormatName);
+- }
+-
+- /*
+- * Constructs a J2KMetadata
object by reading the
+- * contents of an ImageInputStream
. Has package-only
+- * access.
+- *
+- * @param iis An ImageInputStream
from which to read
+- * the metadata.
+- * @param reader The J2KImageReader
calling this
+- * constructor, to which warnings should be sent.
+- */
+- public J2KMetadata(ImageInputStream iis,
+- J2KImageReader reader) throws IOException {
+- this();
+- RandomAccessIO in = new IISRandomAccessIO(iis);
+-
+- iis.mark();
+- // **** File Format ****
+- // If the codestream is wrapped in the jp2 fileformat, Read the
+- // file format wrapper
+- FileFormatReader ff = new FileFormatReader(in, this);
+- ff.readFileFormat();
+- iis.reset();
+- }
+-
+- /**
+- * Constructs a default stream J2KMetadata
object appropriate
+- * for the given write parameters.
+- */
+- public J2KMetadata(ImageWriteParam param, ImageWriter writer) {
+- this(null, param, writer);
+- }
+-
+- /**
+- * Constructs a default image J2KMetadata
object appropriate
+- * for the given image type and write parameters.
+- */
+- public J2KMetadata(ImageTypeSpecifier imageType,
+- ImageWriteParam param,
+- ImageWriter writer) {
+- this(imageType != null ? imageType.getColorModel() : null,
+- imageType != null ? imageType.getSampleModel() : null,
+- 0, 0,
+- param, writer);
+- }
+-
+- /**
+- * Constructs a default image J2KMetadata
object appropriate
+- * for the given image type and write parameters.
+- */
+- public J2KMetadata(ColorModel colorModel,
+- SampleModel sampleModel,
+- int width,
+- int height,
+- ImageWriteParam param,
+- ImageWriter writer) {
+- this();
+- addNode(new SignatureBox());
+- addNode(new FileTypeBox(0x6A703220, 0, new int[]{0x6A703220}));
+-
+- ImageTypeSpecifier destType = null;
+-
+- if (param != null) {
+- destType = param.getDestinationType();
+- if (colorModel == null && sampleModel == null) {
+- colorModel = destType == null ? null : destType.getColorModel();
+- sampleModel =
+- destType == null ? null : destType.getSampleModel();
+- }
+- }
+-
+- int[] bitDepths = null;
+- if(colorModel != null) {
+- bitDepths = colorModel.getComponentSize();
+- } else if(sampleModel != null) {
+- bitDepths = sampleModel.getSampleSize();
+- }
+-
+- int bitsPerComponent = 0xff;
+- if(bitDepths != null) {
+- bitsPerComponent = bitDepths[0];
+- int numComponents = bitDepths.length;
+- for(int i = 1; i < numComponents; i++) {
+- /* XXX: This statement should be removed when BPC behavior
+- is corrected as derscribed below. */
+- if(bitDepths[i] > bitsPerComponent) {
+- bitsPerComponent = bitDepths[i];
+- }
+- /* XXX: When the number of bits per component is not the
+- same for all components the BPC parameter of the Image
+- Header box should be set to 0xff and the actual number of
+- bits per component written in the Bits Per Component box.
+- if(bitDepths[i] != bitsPerComponent) {
+- bitsPerComponent = 0xff;
+- break;
+- }
+- */
+- }
+- }
+-
+- if (colorModel != null) {
+- ColorSpace cs = colorModel.getColorSpace();
+- boolean iccColor = (cs instanceof ICC_ColorSpace);
+- int type = cs.getType();
+-
+- if (type == ColorSpace.TYPE_RGB) {
+- addNode(new ColorSpecificationBox((byte)1,
+- (byte)0, (byte)0,
+- ColorSpecificationBox.ECS_sRGB,
+- null));
+- } else if (type == ColorSpace.TYPE_GRAY)
+- addNode(new ColorSpecificationBox((byte)1,
+- (byte)0, (byte)0,
+- ColorSpecificationBox.ECS_GRAY,
+- null));
+- else if (cs instanceof ICC_ColorSpace)
+- addNode(new ColorSpecificationBox((byte)2,
+- (byte)0, (byte)0,
+- 0,
+- ((ICC_ColorSpace)cs).getProfile()));
+-
+- if (colorModel.hasAlpha()) {
+- addNode(new ChannelDefinitionBox(colorModel));
+- }
+-
+- if (colorModel instanceof IndexColorModel) {
+- addNode(new PaletteBox((IndexColorModel)colorModel));
+- int numComp = colorModel.getComponentSize().length;
+- short[] channels = new short[numComp];
+- byte[] types = new byte[numComp];
+- byte[] maps = new byte[numComp];
+- for (int i = 0; i < numComp; i++) {
+- channels[i] = 0;
+- types[i] = 1;
+- maps[i] = (byte)i;
+- }
+- addNode(new ComponentMappingBox(channels, types, maps));
+- }
+- }
+-
+- if (sampleModel != null) {
+- if (width <= 0)
+- width = sampleModel.getWidth();
+- if (height <= 0)
+- height = sampleModel.getHeight();
+- int bpc = bitsPerComponent == 0xff ?
+- 0xff : ((bitsPerComponent - 1) |
+- (isOriginalSigned(sampleModel) ? 0x80 : 0));
+- addNode(new HeaderBox(height,
+- width,
+- sampleModel.getNumBands(),
+- bpc,
+- 7,
+- colorModel == null ? 1 : 0,
+- getElement("JPEG2000IntellectualPropertyRightsBox")==null ? 0 : 1));
+- }
+- }
+-
+- public Object clone() {
+- J2KMetadata theClone = null;
+-
+- try {
+- theClone = (J2KMetadata) super.clone();
+- } catch (CloneNotSupportedException e) {} // won't happen
+-
+- if (boxes != null) {
+- int numBoxes = boxes.size();
+- for(int i = 0; i < numBoxes; i++) {
+- theClone.addNode((Box)boxes.get(i));
+- }
+- }
+- return theClone;
+- }
+-
+- public Node getAsTree(String formatName) {
+- if (formatName == null) {
+- throw new IllegalArgumentException(I18N.getString("J2KMetadata0"));
+- }
+-
+- if (formatName.equals(nativeMetadataFormatName)) {
+- return getNativeTree();
+- }
+-
+- if (formatName.equals
+- (IIOMetadataFormatImpl.standardMetadataFormatName)) {
+- return getStandardTree();
+- }
+-
+- throw new IllegalArgumentException(I18N.getString("J2KMetadata1")
+- + " " + formatName);
+- }
+-
+- IIOMetadataNode getNativeTree() {
+- IIOMetadataNode root =
+- new IIOMetadataNode(nativeMetadataFormatName);
+-
+- Box signatureBox = null, fileTypeBox = null, headerBox = null;
+- int signatureIndex = -1, fileTypeIndex = -1, headerIndex = -1;
+-
+- int numBoxes = boxes.size();
+-
+- int found = 0;
+- for(int i = 0; i < numBoxes && found < 3; i++) {
+- Box box = (Box)boxes.get(i);
+- if(Box.getName(box.getType()).equals("JPEG2000SignatureBox")) {
+- signatureBox = box;
+- signatureIndex = i;
+- found++;
+- } else if(Box.getName(box.getType()).equals("JPEG2000FileTypeBox")) {
+- fileTypeBox = box;
+- fileTypeIndex = i;
+- found++;
+- } else if(Box.getName(box.getType()).equals("JPEG2000HeaderBox")) {
+- headerBox = box;
+- headerIndex = i;
+- found++;
+- }
+- }
+-
+- if(signatureBox != null) {
+- insertNodeIntoTree(root, signatureBox.getNativeNode());
+- }
+-
+- if(fileTypeBox != null) {
+- insertNodeIntoTree(root, fileTypeBox.getNativeNode());
+- }
+-
+- if(headerBox != null) {
+- insertNodeIntoTree(root, headerBox.getNativeNode());
+- }
+-
+- for(int i = 0; i < numBoxes; i++) {
+- if(i == signatureIndex ||
+- i == fileTypeIndex ||
+- i == headerIndex) continue;
+- Box box = (Box)boxes.get(i);
+- IIOMetadataNode node = box.getNativeNode();
+- insertNodeIntoTree(root, node);
+- }
+- return root;
+- }
+-
+- // Standard tree node methods
+- protected IIOMetadataNode getStandardChromaNode() {
+- HeaderBox header = (HeaderBox)getElement("JPEG2000HeaderBox");
+- PaletteBox palette = (PaletteBox)getElement("JPEG2000PaletteBox");
+- ColorSpecificationBox color =
+- (ColorSpecificationBox)getElement("JPEG2000ColorSpecificationBox");
+-
+- IIOMetadataNode node = new IIOMetadataNode("Chroma");
+- IIOMetadataNode subNode = null;
+- if (header != null) {
+- if (header.getUnknownColorspace() == 0) {
+- if (color != null && color.getMethod() == 1) {
+- subNode = new IIOMetadataNode("ColorSpaceType");
+- int ecs = color.getEnumeratedColorSpace();
+- if (ecs == FileFormatBoxes.CSB_ENUM_SRGB)
+- subNode.setAttribute("name", "RGB");
+- if (ecs == FileFormatBoxes.CSB_ENUM_GREY)
+- subNode.setAttribute("name", "GRAY");
+- node.appendChild(subNode);
+- }
+- }
+-
+- subNode = new IIOMetadataNode("NumChannels");
+- subNode.setAttribute("value", "" + header.getNumComponents());
+- node.appendChild(subNode);
+-
+- if (palette != null) {
+- subNode.setAttribute("value", "" + palette.getNumComp());
+- subNode = new IIOMetadataNode("Palette");
+- byte[][] lut = palette.getLUT();
+-
+- int size = lut[0].length;
+- int numComp = lut.length;
+-
+- for (int i = 0; i < size; i++) {
+- IIOMetadataNode subNode1 =
+- new IIOMetadataNode("PaletteEntry");
+- subNode1.setAttribute("index", ""+i);
+- subNode1.setAttribute("red", "" + (lut[0][i]&0xff));
+- subNode1.setAttribute("green", "" + (lut[1][i]&0xff));
+- subNode1.setAttribute("blue", "" + (lut[2][i]&0xff));
+- if (numComp == 4)
+- subNode1.setAttribute("alpha", "" + (lut[3][i]&0xff));
+- subNode.appendChild(subNode1);
+- }
+- node.appendChild(subNode);
+- }
+- }
+- return node;
+- }
+-
+- protected IIOMetadataNode getStandardCompressionNode() {
+- IIOMetadataNode node = new IIOMetadataNode("Compression");
+-
+- // CompressionTypeName
+- IIOMetadataNode subNode = new IIOMetadataNode("CompressionTypeName");
+- subNode.setAttribute("value", "JPEG2000");
+- node.appendChild(subNode);
+- return node;
+- }
+-
+- protected IIOMetadataNode getStandardDataNode() {
+- IIOMetadataNode node = new IIOMetadataNode("Data");
+- PaletteBox palette = (PaletteBox)getElement("JPEG2000PaletteBox");
+- boolean sampleFormat = false;
+-
+- if (palette != null) {
+- IIOMetadataNode subNode = new IIOMetadataNode("SampleFormat");
+- subNode.setAttribute("value", "Index");
+- node.appendChild(subNode);
+- sampleFormat = true;
+- }
+-
+- BitsPerComponentBox bitDepth =
+- (BitsPerComponentBox)getElement("JPEG2000BitsPerComponentBox");
+- String value = "";
+- boolean signed = false;
+- boolean gotSampleInfo = false;
+-
+- // JPEG 2000 "B" parameter represents "bitDepth - 1" in the
+- // right 7 least significant bits with the most significant
+- // bit indicating signed if set and unsigned if not.
+- if (bitDepth != null) {
+- byte[] bits = bitDepth.getBitDepth();
+- if ((bits[0] & 0x80) == 0x80)
+- signed = true;
+-
+- int numComp = bits.length;
+- for (int i = 0; i < numComp; i++) {
+- value += (bits[i] & 0x7f) + 1;
+- if(i != numComp - 1) value += " ";
+- }
+-
+- gotSampleInfo = true;
+- } else {
+- HeaderBox header = (HeaderBox)getElement("JPEG2000HeaderBox");
+- if(header != null) {
+- int bits = header.getBitDepth();
+- if ((bits & 0x80) == 0x80)
+- signed = true;
+- bits = (bits & 0x7f) + 1;
+- int numComp = header.getNumComponents();
+- for (int i = 0; i < numComp; i++) {
+- value += bits;
+- if(i != numComp - 1) value += " ";
+- }
+-
+- gotSampleInfo = true;
+- }
+- }
+-
+- IIOMetadataNode subNode = null;
+-
+- if(gotSampleInfo) {
+- subNode = new IIOMetadataNode("BitsPerSample");
+- subNode.setAttribute("value", value);
+- node.appendChild(subNode);
+- }
+-
+- subNode = new IIOMetadataNode("PlanarConfiguration");
+- subNode.setAttribute("value", "TileInterleaved");
+- node.appendChild(subNode);
+-
+- if (!sampleFormat && gotSampleInfo) {
+- subNode = new IIOMetadataNode("SampleFormat");
+- subNode.setAttribute("value",
+- signed ? "SignedIntegral": "UnsignedIntegral");
+- node.appendChild(subNode);
+- }
+-
+- return node;
+- }
+-
+- protected IIOMetadataNode getStandardDimensionNode() {
+- ResolutionBox box =
+- (ResolutionBox)getElement("JPEG2000CaptureResolutionBox");
+- if (box != null) {
+- IIOMetadataNode node = new IIOMetadataNode("Dimension");
+- float hRes = box.getHorizontalResolution();
+- float vRes = box.getVerticalResolution();
+- float ratio = vRes / hRes;
+- IIOMetadataNode subNode = new IIOMetadataNode("PixelAspectRatio");
+- subNode.setAttribute("value", "" + ratio);
+- node.appendChild(subNode);
+-
+- subNode = new IIOMetadataNode("HorizontalPixelSize");
+- subNode.setAttribute("value", "" + (1000 / hRes));
+- node.appendChild(subNode);
+-
+- subNode = new IIOMetadataNode("VerticalPixelSize");
+- subNode.setAttribute("value", "" + (1000 / vRes));
+- node.appendChild(subNode);
+-
+- return node;
+- }
+-
+- return null;
+- }
+-
+- protected IIOMetadataNode getStandardTransparencyNode() {
+- ChannelDefinitionBox channel =
+- (ChannelDefinitionBox)getElement("JPEG2000ChannelDefinitionBox");
+- if (channel != null) {
+- IIOMetadataNode node = new IIOMetadataNode("Transparency");
+-
+- boolean hasAlpha = false;
+- boolean isPremultiplied = false;
+- short[] type = channel.getTypes();
+-
+- for (int i = 0; i < type.length; i++) {
+- if (type[i] == 1)
+- hasAlpha = true;
+- if (type[i] == 2)
+- isPremultiplied = true;
+- }
+-
+- String value = "none";
+- if (isPremultiplied)
+- value = "premultiplied";
+- else if (hasAlpha)
+- value = "nonpremultiplied";
+-
+- IIOMetadataNode subNode = new IIOMetadataNode("Alpha");
+- subNode.setAttribute("value", value);
+- node.appendChild(subNode);
+-
+- return node;
+- }
+-
+- IIOMetadataNode node = new IIOMetadataNode("Transparency");
+- IIOMetadataNode subNode = new IIOMetadataNode("Alpha");
+- subNode.setAttribute("value", "none");
+- node.appendChild(subNode);
+-
+- return null;
+- }
+-
+- protected IIOMetadataNode getStandardTextNode() {
+- if (boxes == null)
+- return null;
+- IIOMetadataNode text = null;
+-
+- Iterator iterator = boxes.iterator();
+-
+- while(iterator.hasNext()) {
+- Box box = (Box)iterator.next();
+- if (box instanceof XMLBox) {
+- if (text == null)
+- text = new IIOMetadataNode("Text");
+- IIOMetadataNode subNode = new IIOMetadataNode("TextEntry");
+- String content = new String(box.getContent());
+- subNode.setAttribute("value", content);
+- text.appendChild(subNode);
+- }
+- }
+- return text;
+- }
+-
+- public boolean isReadOnly() {
+- return false;
+- }
+-
+- public void mergeTree(String formatName, Node root)
+- throws IIOInvalidTreeException {
+- if (formatName == null) {
+- throw new IllegalArgumentException(I18N.getString("J2KMetadata0"));
+- }
+-
+- if (root == null) {
+- throw new IllegalArgumentException(I18N.getString("J2KMetadata2"));
+- }
+-
+- if (formatName.equals(nativeMetadataFormatName) &&
+- root.getNodeName().equals(nativeMetadataFormatName)) {
+- mergeNativeTree(root);
+- } else if (formatName.equals
+- (IIOMetadataFormatImpl.standardMetadataFormatName)) {
+- mergeStandardTree(root);
+- } else {
+- throw new IllegalArgumentException(I18N.getString("J2KMetadata1")
+- + " " + formatName);
+- }
+- }
+-
+- public void setFromTree(String formatName, Node root)
+- throws IIOInvalidTreeException {
+- if (formatName == null) {
+- throw new IllegalArgumentException(I18N.getString("J2KMetadata0"));
+- }
+-
+- if (root == null) {
+- throw new IllegalArgumentException(I18N.getString("J2KMetadata2"));
+- }
+-
+- if (formatName.equals(nativeMetadataFormatName) &&
+- root.getNodeName().equals(nativeMetadataFormatName)) {
+- boxes = new ArrayList();
+- mergeNativeTree(root);
+- } else if (formatName.equals
+- (IIOMetadataFormatImpl.standardMetadataFormatName)) {
+- boxes = new ArrayList();
+- mergeStandardTree(root);
+- } else {
+- throw new IllegalArgumentException(I18N.getString("J2KMetadata1")
+- + " " + formatName);
+- }
+- }
+-
+- public void reset() {
+- boxes.clear();
+- }
+-
+- public void addNode(Box node) {
+- if (boxes == null)
+- boxes = new ArrayList();
+- replace(Box.getName(node.getType()), node);
+- }
+-
+- public Box getElement(String name) {
+- for (int i = boxes.size() - 1; i >= 0; i--) {
+- Box box = (Box)boxes.get(i);
+- if (name.equals(Box.getName(box.getType())))
+- return box;
+- }
+- return null;
+- }
+-
+- private void mergeNativeTree(Node root) throws IIOInvalidTreeException {
+- NodeList list = root.getChildNodes();
+- for (int i = list.getLength() - 1; i >= 0; i--) {
+- Node node = list.item(i);
+- String name = node.getNodeName();
+- if (format.getParent(name) != null) {
+- if (format.isLeaf(name)) {
+- String s = (String)Box.getAttribute(node, "Type");
+- Box box = Box.createBox(Box.getTypeInt(s), node);
+- if (format.singleInstance(name)&&getElement(name) != null) {
+- replace(name, box);
+- } else
+- boxes.add(box);
+- } else {
+- mergeNativeTree(node);
+- }
+- }
+- }
+- }
+-
+- private void mergeStandardTree(Node root) throws IIOInvalidTreeException {
+- NodeList children = root.getChildNodes();
+- int numComps = 0;
+-
+- for (int i = 0; i < children.getLength(); i++) {
+- Node node = children.item(i);
+- String name = node.getNodeName();
+- if (name.equals("Chroma")) {
+- NodeList children1 = node.getChildNodes();
+- for (int j = 0; j < children1.getLength(); j++) {
+- Node child = children1.item(j);
+- String name1 = child.getNodeName();
+-
+- if (name1.equals("NumChannels")) {
+- String s = (String)Box.getAttribute(child, "value");
+- numComps = new Integer(s).intValue();
+- }
+-
+- if (name1.equals("ColorSpaceType"))
+- createColorSpecificationBoxFromStandardNode(child);
+-
+- if (name1.equals("Palette")) {
+- createPaletteBoxFromStandardNode(child);
+- }
+- }
+- } else if (name.equals("Compression")) {
+- // Intentionally do nothing: just prevent entry into
+- // the default "else" block and an ensuing
+- // IIOInvalidTreeException; fixes 5110389.
+- } else if (name.equals("Data")) {
+- createBitsPerComponentBoxFromStandardNode(node);
+- createHeaderBoxFromStandardNode(node, numComps);
+- } else if (name.equals("Dimension")) {
+- createResolutionBoxFromStandardNode(node);
+- } else if (name.equals("Document")) {
+- createXMLBoxFromStandardNode(node);
+- } else if (name.equals("Text")) {
+- createXMLBoxFromStandardNode(node);
+- } else if (name.equals("Transparency")) {
+- createChannelDefinitionFromStandardNode(node);
+- } else {
+- throw new IIOInvalidTreeException(I18N.getString("J2KMetadata3")
+- + " " + name, node);
+- }
+- }
+- }
+-
+- private void createColorSpecificationBoxFromStandardNode(Node node) {
+- if (node.getNodeName() != "ColorSpaceType")
+- throw new IllegalArgumentException(I18N.getString("J2KMetadata4"));
+- String name = (String)Box.getAttribute(node, "name");
+- int ecs = name.equals("RGB") ? ColorSpecificationBox.ECS_sRGB :
+- (name.equals("Gray") ? ColorSpecificationBox.ECS_GRAY : 0);
+-
+- if (ecs == ColorSpecificationBox.ECS_sRGB ||
+- ecs ==ColorSpecificationBox.ECS_GRAY) {
+- replace ("JPEG2000ColorSpecificationBox",
+- new ColorSpecificationBox((byte)1, (byte)0, (byte)0,
+- ecs, null));
+- }
+- }
+-
+- private void createPaletteBoxFromStandardNode(Node node) {
+- if (node.getNodeName() != "Palette")
+- throw new IllegalArgumentException(I18N.getString("J2KMetadata5"));
+- NodeList children = node.getChildNodes();
+- int maxIndex = -1;
+- boolean hasAlpha = false;
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+- String name = child.getNodeName();
+-
+- if (name.equals("PaletteEntry")) {
+- String s = (String)Box.getAttribute(child, "index");
+- int index = new Integer(s).intValue();
+- if(index > maxIndex) {
+- maxIndex = index;
+- }
+- if(Box.getAttribute(child, "alpha") != null) {
+- hasAlpha = true;
+- }
+- }
+- }
+-
+- // Determine palette size.
+- int numBits = 32;
+- int mask = 0x80000000;
+- while(mask != 0 && (maxIndex & mask) == 0) {
+- numBits--;
+- mask >>>= 1;
+- }
+- int size = 1 << numBits;
+-
+- byte[] red = new byte[size];
+- byte[] green = new byte[size];
+- byte[] blue = new byte[size];
+- byte[] alpha = hasAlpha ? new byte[size]: null;
+-
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+- String name = child.getNodeName();
+-
+- if (name.equals("PaletteEntry")) {
+- String s = (String)Box.getAttribute(child, "index");
+- int index = new Integer(s).intValue();
+- s = (String)Box.getAttribute(child, "red");
+- red[index] = (byte)(new Integer(s).intValue());
+- s = (String)Box.getAttribute(child, "green");
+- green[index] = (byte)(new Integer(s).intValue());
+- s = (String)Box.getAttribute(child, "blue");
+- blue[index] = (byte)(new Integer(s).intValue());
+-
+- byte t = (byte)255;
+- s = (String)Box.getAttribute(child, "alpha");
+- if(s != null) {
+- t = (byte)(new Integer(s).intValue());
+- }
+-
+- if(alpha != null) {
+- alpha[index] = t;
+- }
+- }
+- }
+-
+- IndexColorModel icm;
+- if (alpha == null)
+- icm = new IndexColorModel(numBits, size, red, green, blue);
+- else
+- icm = new IndexColorModel(numBits, size, red, green, blue, alpha);
+-
+- replace("JPEG2000PaletteBox", new PaletteBox(icm));
+- }
+-
+- private void createBitsPerComponentBoxFromStandardNode(Node node) {
+- if (node.getNodeName() != "Data")
+- throw new IllegalArgumentException(I18N.getString("J2KMetadata6"));
+-
+- NodeList children = node.getChildNodes();
+-
+- byte[] bits = null;
+- boolean isSigned = false;
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+- String name = child.getNodeName();
+-
+- if (name.equals("BitsPerSample")) {
+- String s = (String)Box.getAttribute(child, "value");
+- bits = (byte[])Box.parseByteArray(s).clone();
+- } else if(name.equals("SampleFormat")) {
+- String s = (String)Box.getAttribute(child, "value");
+- isSigned = s.equals("SignedIntegral");
+- }
+- }
+-
+- if(bits != null) {
+- // JPEG 2000 "B" parameter represents "bitDepth - 1" in the
+- // right 7 least significant bits with the most significant
+- // bit indicating signed if set and unsigned if not.
+- for (int i = 0; i < bits.length; i++) {
+- bits[i] = (byte)((bits[i]&0xff) - 1);
+- if(isSigned) {
+- bits[i] |= 0x80;
+- }
+- }
+-
+- replace("JPEG2000BitsPerComponent",
+- new BitsPerComponentBox(bits));
+- }
+- }
+-
+- private void createResolutionBoxFromStandardNode(Node node) {
+- if (node.getNodeName() != "Dimension")
+- throw new IllegalArgumentException(I18N.getString("J2KMetadata7"));
+- NodeList children = node.getChildNodes();
+- float hRes = 0.0f;
+- float vRes = 0.0f;
+-
+- boolean gotH = false, gotV = false;
+-
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+- String name = child.getNodeName();
+-
+- if (name.equals("HorizontalPixelSize")) {
+- String s = (String)Box.getAttribute(child, "value");
+- hRes = new Float(s).floatValue();
+- hRes = 1000 / hRes;
+- gotH = true;
+- }
+-
+- if (name.equals("VerticalPixelSize")) {
+- String s = (String)Box.getAttribute(child, "value");
+- vRes = new Float(s).floatValue();
+- vRes = 1000 / vRes;
+- gotV = true;
+- }
+- }
+-
+- if(gotH && !gotV) {
+- vRes = hRes;
+- } else if(gotV && !gotH) {
+- hRes = vRes;
+- }
+-
+- if(gotH || gotV) {
+- replace("JPEG2000CaptureResolutionBox",
+- new ResolutionBox(0x72657363, hRes, vRes));
+- }
+- }
+-
+- private void createXMLBoxFromStandardNode(Node node) {
+- NodeList children = node.getChildNodes();
+- String value = "<" + node.getNodeName() + ">";
+-
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+- String name = child.getNodeName();
+- value += "<" + name + " ";
+-
+- NamedNodeMap map = child.getAttributes();
+-
+- for (int j = 0; j < map.getLength(); j++) {
+- Node att = map.item(j);
+- value += att.getNodeName() + "=\"" +
+- att.getNodeValue() + "\" ";
+- }
+-
+- value += " />";
+- }
+-
+- value += "" + node.getNodeName() + ">";
+-
+- boxes.add(new XMLBox(value.getBytes()));
+- }
+-
+- private void createHeaderBoxFromStandardNode(Node node, int numComps) {
+- HeaderBox header = (HeaderBox)getElement("JPEG2000HeaderBox");
+- byte unknownColor =
+- (byte)(getElement("JPEG2000ColorSpecificationBox") == null ? 1: 0);
+- if (header != null) {
+- if (numComps ==0);
+- numComps = header.getNumComponents();
+-
+- header = new HeaderBox(header.getHeight(), header.getWidth(),
+- numComps,
+- header.getBitDepth(),
+- header.getCompressionType(),
+- unknownColor,
+- header.getIntellectualProperty());
+- } else {
+- header = new HeaderBox(0, 0, numComps, 0, 0, unknownColor, 0);
+- }
+- replace("JPEG2000HeaderBox", header);
+- }
+-
+- private void createChannelDefinitionFromStandardNode(Node node) {
+- if (node.getNodeName() != "Transparency")
+- throw new IllegalArgumentException(I18N.getString("J2KMetadata8"));
+-
+- HeaderBox header = (HeaderBox)getElement("JPEG2000HeaderBox");
+- int numComps = 3;
+-
+- if (header != null) {
+- numComps = header.getNumComponents();
+- }
+-
+- NodeList children = node.getChildNodes();
+- boolean hasAlpha = false;
+- boolean isPremultiplied = false;
+-
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+- String name = child.getNodeName();
+-
+- if (name.equals("Alpha")) {
+- String value = (String)Box.getAttribute(child, "value");
+- if (value.equals("premultiplied"))
+- isPremultiplied = true;
+- if (value.equals("nonpremultiplied"))
+- hasAlpha = true;
+- }
+- }
+-
+- if (!hasAlpha)
+- return;
+-
+- int num = (short)(numComps * (isPremultiplied ? 3 : 2));
+- short[] channels = new short[num];
+- short[] types = new short[num];
+- short[] associations = new short[num];
+- ChannelDefinitionBox.fillBasedOnBands(numComps, isPremultiplied,
+- channels, types, associations);
+- replace("JPEG2000ChannelDefinitionBox",
+- new ChannelDefinitionBox(channels, types, associations));
+- }
+-
+- private void replace(String name, Box box) {
+- for (int i = boxes.size() - 1; i >= 0; i--) {
+- Box box1 = (Box)boxes.get(i);
+- if (name.equals(Box.getName(box1.getType()))) {
+- boxes.set(i, box);
+- return;
+- }
+- }
+-
+- boxes.add(box);
+- }
+-
+- private boolean insertNodeIntoTree(IIOMetadataNode root,
+- IIOMetadataNode node) {
+- String name = node.getNodeName();
+- String parent = format.getParent(name);
+- if (parent == null)
+- return false;
+-
+- IIOMetadataNode parentNode = getNodeFromTree(root, parent, name);
+- if (parentNode == null)
+- parentNode = createNodeIntoTree(root, parent);
+- parentNode.appendChild(node);
+- return true;
+- }
+-
+- private IIOMetadataNode getNodeFromTree(IIOMetadataNode root,
+- String name,
+- String childName) {
+- if (name.equals(root.getNodeName()))
+- return root;
+-
+- NodeList list = root.getChildNodes();
+- for (int i = 0; i < list.getLength(); i++) {
+- IIOMetadataNode node = (IIOMetadataNode)list.item(i);
+- if (node.getNodeName().equals(name)) {
+- if (name.equals("JPEG2000UUIDInfoBox") &&
+- checkUUIDInfoBox(node, childName))
+- continue;
+- else
+- return node;
+- }
+- node = getNodeFromTree(node, name, childName);
+- if (node != null)
+- return node;
+- }
+-
+- return null;
+- }
+-
+- private IIOMetadataNode createNodeIntoTree(IIOMetadataNode root,
+- String name) {
+- IIOMetadataNode node = getNodeFromTree(root, name, null);
+- if (node != null)
+- return node;
+-
+- node = new IIOMetadataNode(name);
+-
+- String parent = format.getParent(name);
+- IIOMetadataNode parentNode = createNodeIntoTree(root, parent);
+- parentNode.appendChild(node);
+-
+- return node;
+- }
+-
+- private boolean isOriginalSigned(SampleModel sampleModel) {
+- int type = sampleModel.getDataType();
+- if (type == DataBuffer.TYPE_BYTE || type == DataBuffer.TYPE_USHORT)
+- return false;
+- return true;
+- }
+-
+- /** Check whether the child with a name childName
exists.
+- * This method is designed because UUID info box may have many instances.
+- * So if one of its sub-box is inserted into the tree, an empty slut for
+- * this sub-box has to be find or created to avoid one UUID info box
+- * has duplicated sub-boxes. The users have to guarantee each UUID info
+- * box has all the sub-boxes.
+- */
+- private boolean checkUUIDInfoBox(Node node, String childName) {
+-
+- NodeList list = node.getChildNodes();
+- for (int i = 0; i < list.getLength(); i++) {
+- IIOMetadataNode child = (IIOMetadataNode)list.item(i);
+- String name = child.getNodeName();
+-
+- if (name.equals(childName))
+- return true;
+- }
+-
+- return false;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KReadState.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KReadState.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KReadState.java 2006-10-03 19:40:14.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KReadState.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,1042 +0,0 @@
+-/*
+- * $RCSfile: J2KReadState.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.8 $
+- * $Date: 2006/10/03 23:40:14 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import javax.imageio.IIOException;
+-import javax.imageio.ImageReader;
+-import javax.imageio.ImageReadParam;
+-import javax.imageio.ImageTypeSpecifier;
+-import javax.imageio.metadata.IIOMetadata;
+-import javax.imageio.spi.ImageReaderSpi;
+-import javax.imageio.stream.ImageInputStream;
+-
+-import java.awt.Point;
+-import java.awt.Rectangle;
+-import java.awt.Transparency;
+-import java.awt.color.ColorSpace;
+-import java.awt.image.BufferedImage;
+-import java.awt.image.DataBuffer;
+-import java.awt.image.DataBufferByte;
+-import java.awt.image.ColorModel;
+-import java.awt.image.ComponentColorModel;
+-import java.awt.image.ComponentSampleModel;
+-import java.awt.image.DirectColorModel;
+-import java.awt.image.IndexColorModel;
+-import java.awt.image.MultiPixelPackedSampleModel;
+-import java.awt.image.PixelInterleavedSampleModel;
+-import java.awt.image.Raster;
+-import java.awt.image.RenderedImage;
+-import java.awt.image.SampleModel;
+-import java.awt.image.SinglePixelPackedSampleModel;
+-import java.awt.image.WritableRaster;
+-
+-import java.io.*;
+-import java.util.ArrayList;
+-import java.util.List;
+-import java.util.Hashtable;
+-import java.util.Iterator;
+-
+-import jj2000.j2k.quantization.dequantizer.*;
+-import jj2000.j2k.wavelet.synthesis.*;
+-import jj2000.j2k.image.invcomptransf.*;
+-import jj2000.j2k.fileformat.reader.*;
+-import jj2000.j2k.codestream.reader.*;
+-import jj2000.j2k.entropy.decoder.*;
+-import jj2000.j2k.codestream.*;
+-import jj2000.j2k.decoder.*;
+-import jj2000.j2k.image.*;
+-import jj2000.j2k.util.*;
+-import jj2000.j2k.roi.*;
+-import jj2000.j2k.io.*;
+-import jj2000.j2k.*;
+-
+-import com.sun.media.imageioimpl.common.ImageUtil;
+-
+-public class J2KReadState {
+- /** The input stream we read from */
+- private ImageInputStream iis = null;
+-
+- private FileFormatReader ff;
+- private HeaderInfo hi;
+- private HeaderDecoder hd;
+- private RandomAccessIO in;
+- private BitstreamReaderAgent breader;
+- private EntropyDecoder entdec;
+- private ROIDeScaler roids;
+- private Dequantizer deq;
+- private InverseWT invWT;
+- private InvCompTransf ictransf;
+- private ImgDataConverter converter,converter2;
+- private DecoderSpecs decSpec = null;
+- private J2KImageReadParamJava j2krparam = null;
+- private int[] destinationBands = null;
+- private int[] sourceBands = null;
+-
+- private int[] levelShift = null; // level shift for each component
+- private int[] minValues = null; // The min values
+- private int[] maxValues = null; // The max values
+- private int[] fracBits = null; // fractional bits for each component
+- private DataBlkInt[] dataBlocks = null; // data-blocks to request data from src
+-
+- private int[] bandOffsets = null;
+- private int maxDepth = 0;
+- private boolean isSigned = false;
+-
+- private ColorModel colorModel = null;
+- private SampleModel sampleModel = null;
+- private int nComp = 0;
+- private int tileWidth = 0;
+- private int tileHeight = 0;
+-
+- /** Source to destination transform */
+- private int scaleX, scaleY, xOffset, yOffset;
+- private Rectangle destinationRegion = null;
+- private Point sourceOrigin;
+-
+- /** Tile grid offsets of the source, also used for destination. */
+- private int tileXOffset, tileYOffset;
+-
+- private int width;
+- private int height;
+- private int[] pixbuf = null;
+- private byte[] bytebuf = null;
+- private int[] channelMap = null;
+-
+- private boolean noTransform = true;
+-
+- /** The resolution level requested. */
+- private int resolution;
+-
+- /** The subsampling step sizes. */
+- private int stepX, stepY;
+-
+- /** Tile step sizes. */
+- private int tileStepX, tileStepY;
+-
+- private J2KMetadata metadata;
+-
+- private BufferedImage destImage;
+-
+- /** Cache the J2KImageReader
which creates this object. This
+- * variable is used to monitor the abortion.
+- */
+- private J2KImageReader reader;
+-
+- /** Constructs J2KReadState
.
+- * @param iis The input stream.
+- * @param param The reading parameters.
+- * @param metadata The J2KMetadata
to cache the metadata read
+- * from the input stream.
+- * @param reader The J2KImageReader
which holds this state.
+- * It is necessary for processing abortion.
+- * @throw IllegalArgumentException If the provided iis
,
+- * param
or metadata
is null
.
+- */
+- public J2KReadState(ImageInputStream iis,
+- J2KImageReadParamJava param,
+- J2KMetadata metadata,
+- J2KImageReader reader) {
+- if (iis == null || param == null || metadata == null)
+- throw new IllegalArgumentException(I18N.getString("J2KReadState0"));
+-
+- this.iis = iis;
+- this.j2krparam = param;
+- this.metadata = metadata;
+- this.reader = reader;
+-
+- initializeRead(0, param, metadata);
+- }
+-
+- /** Constructs J2KReadState
.
+- * @param iis The input stream.
+- * @param param The reading parameters.
+- * @param reader The J2KImageReader
which holds this state.
+- * It is necessary for processing abortion.
+- * @throw IllegalArgumentException If the provided iis
,
+- * or param
is null
.
+- */
+- public J2KReadState(ImageInputStream iis,
+- J2KImageReadParamJava param,
+- J2KImageReader reader) {
+- if (iis == null || param == null)
+- throw new IllegalArgumentException(I18N.getString("J2KReadState0"));
+-
+- this.iis = iis;
+- this.j2krparam = param;
+- this.reader = reader;
+- initializeRead(0, param, null);
+- }
+-
+- public int getWidth() throws IOException {
+- return width;
+- }
+-
+- public int getHeight() throws IOException {
+- return height;
+- }
+-
+- public HeaderDecoder getHeader() {
+- return hd;
+- }
+-
+- public Raster getTile(int tileX, int tileY,
+- WritableRaster raster) throws IOException {
+- Point nT = ictransf.getNumTiles(null);
+-
+- if (noTransform) {
+- if (tileX >= nT.x || tileY >= nT.y)
+- throw new IllegalArgumentException(I18N.getString("J2KImageReader0"));
+-
+- ictransf.setTile(tileX*tileStepX, tileY*tileStepY);
+-
+- // The offset of the active tiles is the same for all components,
+- // since we don't support different component dimensions.
+- int tOffx;
+- int tOffy;
+- int cTileWidth;
+- int cTileHeight;
+- if(raster != null &&
+- (this.resolution < hd.getDecoderSpecs().dls.getMin()) ||
+- stepX != 1 || stepY != 1) {
+- tOffx = raster.getMinX();
+- tOffy = raster.getMinY();
+- cTileWidth = Math.min(raster.getWidth(),
+- ictransf.getTileWidth());
+- cTileHeight = Math.min(raster.getHeight(),
+- ictransf.getTileHeight());
+- } else {
+- tOffx = ictransf.getCompULX(0) -
+- (ictransf.getImgULX() + ictransf.getCompSubsX(0) - 1) /
+- ictransf.getCompSubsX(0) + destinationRegion.x;
+- tOffy = ictransf.getCompULY(0)-
+- (ictransf.getImgULY() + ictransf.getCompSubsY(0) - 1) /
+- ictransf.getCompSubsY(0) + destinationRegion.y;
+- cTileWidth = ictransf.getTileWidth();
+- cTileHeight = ictransf.getTileHeight();
+- }
+-
+- if (raster == null)
+- raster = Raster.createWritableRaster(sampleModel,
+- new Point(tOffx, tOffy));
+-
+- int numBands = sampleModel.getNumBands();
+-
+- if (tOffx + cTileWidth >=
+- destinationRegion.width + destinationRegion.x)
+- cTileWidth =
+- destinationRegion.width + destinationRegion.x - tOffx;
+-
+- if (tOffy + cTileHeight >=
+- destinationRegion.height + destinationRegion.y)
+- cTileHeight =
+- destinationRegion.height + destinationRegion.y - tOffy;
+-
+- //create the line buffer for pixel data if it is not large enough
+- // or null
+- if (pixbuf == null || pixbuf.length < cTileWidth * numBands)
+- pixbuf = new int[cTileWidth * numBands];
+- boolean prog = false;
+-
+- // Deliver in lines to reduce memory usage
+- for (int l=0; l < cTileHeight;l++) {
+- if (reader.getAbortRequest())
+- break;
+-
+- // Request line data
+- for (int i = 0; i < numBands; i++) {
+- if (reader.getAbortRequest())
+- break;
+- DataBlkInt db = dataBlocks[i];
+- db.ulx = 0;
+- db.uly = l;
+- db.w = cTileWidth;
+- db.h = 1;
+- ictransf.getInternCompData(db, channelMap[sourceBands[i]]);
+- prog = prog || db.progressive;
+-
+- int[] data = db.data;
+- int k1 = db.offset + cTileWidth - 1;
+-
+- int fracBit = fracBits[i];
+- int lS = levelShift[i];
+- int min = minValues[i];
+- int max = maxValues[i];
+-
+- if (ImageUtil.isBinary(sampleModel)) {
+- // Force min max to 0 and 1.
+- min = 0;
+- max = 1;
+- if (bytebuf == null || bytebuf.length < cTileWidth * numBands)
+- bytebuf = new byte[cTileWidth * numBands];
+- for (int j = cTileWidth - 1;
+- j >= 0; j--) {
+- int tmp = (data[k1--] >> fracBit) + lS;
+- bytebuf[j] =
+- (byte)((tmp < min) ? min :
+- ((tmp > max) ? max : tmp));
+- }
+-
+- ImageUtil.setUnpackedBinaryData(bytebuf,
+- raster,
+- new Rectangle(tOffx,
+- tOffy + l,
+- cTileWidth,
+- 1));
+- } else {
+-
+- for (int j = cTileWidth - 1;
+- j >= 0; j--) {
+- int tmp = (data[k1--] >> fracBit) + lS;
+- pixbuf[j] = (tmp < min) ? min :
+- ((tmp > max) ? max : tmp);
+- }
+-
+- raster.setSamples(tOffx,
+- tOffy + l,
+- cTileWidth,
+- 1,
+- destinationBands[i],
+- pixbuf);
+- }
+- }
+- }
+- } else {
+- readSubsampledRaster(raster);
+- }
+-
+- return raster;
+- }
+-
+- public Rectangle getDestinationRegion() {
+- return destinationRegion;
+- }
+-
+- public BufferedImage readBufferedImage() throws IOException {
+- colorModel = getColorModel();
+- sampleModel = getSampleModel();
+- WritableRaster raster = null;
+- BufferedImage image = j2krparam.getDestination();
+-
+- int x = destinationRegion.x;
+- int y = destinationRegion.y;
+- destinationRegion.setLocation(j2krparam.getDestinationOffset());
+- if (image == null) {
+- // If the destination type is specified, use the color model of it.
+- ImageTypeSpecifier type = j2krparam.getDestinationType();
+- if (type != null)
+- colorModel = type.getColorModel();
+-
+- raster = Raster.createWritableRaster(
+- sampleModel.createCompatibleSampleModel(destinationRegion.x +
+- destinationRegion.width,
+- destinationRegion.y +
+- destinationRegion.height),
+- new Point(0, 0));
+- image = new BufferedImage(colorModel, raster,
+- colorModel.isAlphaPremultiplied(),
+- new Hashtable());
+- } else
+- raster = image.getWritableTile(0, 0);
+-
+- destImage = image;
+- readSubsampledRaster(raster);
+- destinationRegion.setLocation(x, y);
+- destImage = null;
+- return image;
+- }
+-
+- public Raster readAsRaster() throws IOException {
+- BufferedImage image = j2krparam.getDestination();
+- WritableRaster raster = null;
+-
+- if (image == null) {
+- raster = Raster.createWritableRaster(
+- sampleModel.createCompatibleSampleModel(destinationRegion.x +
+- destinationRegion.width,
+- destinationRegion.y +
+- destinationRegion.height),
+- new Point(0, 0));
+- } else
+- raster = image.getWritableTile(0, 0);
+-
+- readSubsampledRaster(raster);
+- return raster;
+- }
+-
+- private void initializeRead(int imageIndex, J2KImageReadParamJava param,
+- J2KMetadata metadata) {
+- try {
+- iis.mark();
+- in = new IISRandomAccessIO(iis);
+-
+- // **** File Format ****
+- // If the codestream is wrapped in the jp2 fileformat, Read the
+- // file format wrapper
+- ff = new FileFormatReader(in, metadata);
+- ff.readFileFormat();
+- in.seek(ff.getFirstCodeStreamPos());
+-
+- hi = new HeaderInfo();
+- try{
+- hd = new HeaderDecoder(in, j2krparam, hi);
+- } catch(EOFException e){
+- throw new RuntimeException(I18N.getString("J2KReadState2"));
+- } catch (IOException ioe) {
+- throw new RuntimeException(ioe);
+- }
+-
+- this.width = hd.getImgWidth();
+- this.height = hd.getImgHeight();
+-
+- Rectangle sourceRegion = param.getSourceRegion();
+- sourceOrigin = new Point();
+- sourceRegion =
+- new Rectangle(hd.getImgULX(), hd.getImgULY(),
+- this.width, this.height);
+-
+- // if the subsample rate for components are not consistent
+- boolean compConsistent = true;
+- stepX = hd.getCompSubsX(0);
+- stepY = hd.getCompSubsY(0);
+- for (int i = 1; i < nComp; i++) {
+- if (stepX != hd.getCompSubsX(i) || stepY != hd.getCompSubsY(i))
+- throw new RuntimeException(I18N.getString("J2KReadState12"));
+- }
+-
+- // Get minimum number of resolution levels available across
+- // all tile-components.
+- int minResLevels = hd.getDecoderSpecs().dls.getMin();
+-
+- // Set current resolution level.
+- this.resolution = param != null ?
+- param.getResolution() : minResLevels;
+- if(resolution < 0 || resolution > minResLevels) {
+- resolution = minResLevels;
+- }
+-
+- // Convert source region to lower resolution level.
+- if(resolution != minResLevels || stepX != 1 || stepY != 1) {
+- sourceRegion =
+- J2KImageReader.getReducedRect(sourceRegion, minResLevels,
+- resolution, stepX, stepY);
+- }
+-
+- destinationRegion = (Rectangle)sourceRegion.clone();
+-
+- J2KImageReader.computeRegionsWrapper(param,
+- false,
+- this.width,
+- this.height,
+- param.getDestination(),
+- sourceRegion,
+- destinationRegion);
+-
+- sourceOrigin = new Point(sourceRegion.x, sourceRegion.y);
+- scaleX = param.getSourceXSubsampling();
+- scaleY = param.getSourceYSubsampling();
+- xOffset = param.getSubsamplingXOffset();
+- yOffset = param.getSubsamplingYOffset();
+-
+- this.width = destinationRegion.width;
+- this.height = destinationRegion.height;
+-
+- Point tileOffset = hd.getTilingOrigin(null);
+-
+- this.tileWidth = hd.getNomTileWidth();
+- this.tileHeight = hd.getNomTileHeight();
+-
+- // Convert tile 0 to lower resolution level.
+- if(resolution != minResLevels || stepX != 1 || stepY != 1) {
+- Rectangle tileRect = new Rectangle(tileOffset);
+- tileRect.width = tileWidth;
+- tileRect.height = tileHeight;
+- tileRect =
+- J2KImageReader.getReducedRect(tileRect, minResLevels,
+- resolution, stepX, stepY);
+- tileOffset = tileRect.getLocation();
+- tileWidth = tileRect.width;
+- tileHeight = tileRect.height;
+- }
+-
+- tileXOffset = tileOffset.x;
+- tileYOffset = tileOffset.y;
+-
+-
+- // Set the tile step sizes. These values are used because it
+- // is possible that tiles will be empty. In particular at lower
+- // resolution levels when subsampling is used this may be the
+- // case. This method of calculation will work at least for
+- // Profile-0 images.
+- if(tileWidth*(1 << (minResLevels - resolution))*stepX >
+- hd.getNomTileWidth()) {
+- tileStepX =
+- (tileWidth*(1 << (minResLevels - resolution))*stepX +
+- hd.getNomTileWidth() - 1)/hd.getNomTileWidth();
+- } else {
+- tileStepX = 1;
+- }
+-
+- if(tileHeight*(1 << (minResLevels - resolution))*stepY >
+- hd.getNomTileHeight()) {
+- tileStepY =
+- (tileHeight*(1 << (minResLevels - resolution))*stepY +
+- hd.getNomTileHeight() - 1)/hd.getNomTileHeight();
+- } else {
+- tileStepY = 1;
+- }
+-
+- if (!destinationRegion.equals(sourceRegion))
+- noTransform = false;
+-
+- // **** Header decoder ****
+- // Instantiate header decoder and read main header
+- decSpec = hd.getDecoderSpecs();
+-
+- // **** Instantiate decoding chain ****
+- // Get demixed bitdepths
+- nComp = hd.getNumComps();
+-
+- int[] depth = new int[nComp];
+- for (int i=0; iJ2KImageReader
which creates this object. This
+- * variable is used to monitor the abortion.
+- */
+- private J2KImageReaderCodecLib reader;
+-
+- /** The J2KImageReadParam
to create this
+- * renderedImage
.
+- */
+- private J2KImageReadParam param = null;
+-
+- /** Caches the medialib decoder. */
+- private Decoder decoder;
+- private Size size;
+- private CompParams compParam;
+- private int xStep, yStep; // JPEG 2000 internal subsampling parameters
+-
+- /** The destination bounds. */
+- Rectangle destinationRegion;
+- Rectangle originalRegion;
+- Point sourceOrigin;
+-
+- /** The subsampling parameters. */
+- private int scaleX, scaleY, xOffset, yOffset;
+- private int[] destinationBands = null;
+- private int[] sourceBands = null;
+- private int nComp;
+- private int[] channelMap;
+-
+- /** Coordinate transform is not needed from the source (image stream)
+- * to the destination.
+- */
+- private boolean noTransform = true;
+-
+- /** The raster for medialib tiles to share. */
+- private WritableRaster rasForATile;
+-
+- private BufferedImage destImage;
+-
+- public J2KRenderedImageCodecLib(ImageInputStream iis,
+- J2KImageReaderCodecLib reader,
+- ImageReadParam param) throws IOException {
+- this.iis = iis;
+- this.reader = reader;
+-
+- // Ensure the ImageReadParam is a J2KImageReadParam
+- boolean allowZeroDestOffset = true;
+- if(param == null) {
+- // Use the default
+- param = (J2KImageReadParam)reader.getDefaultReadParam();
+- allowZeroDestOffset = false;
+- } else if(!(param instanceof J2KImageReadParam)) {
+- // Create a new one
+- param = new J2KImageReadParamJava(param);
+- allowZeroDestOffset = false;
+- }
+- this.param = (J2KImageReadParam)param;
+-
+- decoder = new Decoder(iis);
+-
+- decoder.setMode(Constants.JP2K_COMPOSITE_TILE);
+-
+- //set resolution before any calling of any calling for decode/decodeSize
+- int resolution = ((J2KImageReadParam)param).getResolution();
+- if (resolution != -1)
+- decoder.setMaxLevels(resolution);
+-
+- size = decoder.decodeSize(null);
+-
+- compParam = new CompParams();
+- for (int i = 0; i < size.csize; i++) {
+- decoder.decodeCompParams(compParam, i);
+- if(i == 0) {
+- xStep = compParam.xstep;
+- yStep = compParam.ystep;
+- } else if(compParam.xstep != xStep || compParam.ystep != yStep) {
+- // All components must have same subsampling along each axis.
+- throw new IIOException
+- ("All components must have the same subsampling factors!");
+- }
+- }
+-
+- // Set source sub-banding.
+- sourceBands = param.getSourceBands();
+- if (sourceBands == null) {
+- nComp = size.csize;
+- sourceBands = new int[nComp];
+- for (int i = 0; i < nComp; i++)
+- sourceBands[i] = i;
+- } else {
+- for(int i = 0; i < sourceBands.length; i++) {
+- if(sourceBands[i] < 0 ||
+- sourceBands[i] >= size.csize) {
+- throw new IIOException
+- ("Source band out of range!");
+- }
+- }
+- }
+-
+- // Cache number of components.
+- nComp = sourceBands.length;
+-
+- // Set destination sub-banding.
+- destinationBands = param.getDestinationBands();
+- if (destinationBands == null) {
+- destinationBands = new int[nComp];
+- for (int i = 0; i < nComp; i++)
+- destinationBands[i] = i;
+- } else {
+- for(int i = 0; i < destinationBands.length; i++) {
+- if(destinationBands[i] < 0 ||
+- destinationBands[i] >= size.csize) {
+- throw new IIOException
+- ("Destination band out of range!");
+- }
+- }
+- }
+-
+- // Check number of source and dest bands.
+- if(destinationBands.length != sourceBands.length) {
+- throw new IIOException
+- ("Number of source and destination bands must be equal!");
+- }
+-
+- this.width = (size.xosize + size.xsize + xStep - 1)/xStep;
+- this.height = (size.yosize + size.ysize + yStep - 1)/yStep;
+-
+- Rectangle sourceRegion =
+- new Rectangle(0, 0, this.width, this.height);
+-
+- originalRegion = (Rectangle)sourceRegion.clone();
+-
+- destinationRegion = (Rectangle)sourceRegion.clone();
+-
+- J2KImageReader.computeRegionsWrapper(param,
+- allowZeroDestOffset,
+- this.width, this.height,
+- param.getDestination(),
+- sourceRegion,
+- destinationRegion);
+- scaleX = param.getSourceXSubsampling();
+- scaleY = param.getSourceYSubsampling();
+- xOffset = param.getSubsamplingXOffset();
+- yOffset = param.getSubsamplingYOffset();
+-
+- sourceOrigin = new Point(sourceRegion.x, sourceRegion.y);
+- if (!destinationRegion.equals(originalRegion))
+- noTransform = false;
+-
+- this.tileWidth = (size.xtsize + xStep - 1)/xStep;
+- this.tileHeight = (size.ytsize + yStep - 1)/yStep;
+- this.tileGridXOffset =
+- (size.xtosize + xStep - 1)/xStep - (size.xosize + xStep - 1)/xStep;
+- this.tileGridYOffset =
+- (size.ytosize + yStep - 1)/yStep - (size.yosize + yStep - 1)/yStep;
+-
+- this.width = destinationRegion.width;
+- this.height = destinationRegion.height;
+- this.minX = destinationRegion.x;
+- this.minY = destinationRegion.y;
+-
+- originalSampleModel = createOriginalSampleModel();
+- sampleModel = createSampleModel();
+- colorModel = createColorModel();
+- tileGridXOffset +=
+- (XToTileX(minX) - XToTileX(tileGridXOffset)) * tileWidth;
+- tileGridYOffset +=
+- (YToTileY(minY) - YToTileY(tileGridYOffset)) * tileHeight;
+-
+- // sets the resolution and decoding rate to the medialib decoder
+- // Java decoding rate is in bit-per-pixel; the medialib rate is in
+- // percentage; so convert first.
+- double rate = ((J2KImageReadParam)param).getDecodingRate();
+- if (rate != Double.MAX_VALUE) {
+- // XXX Obtain bits per sample from elsewhere, e.g., ColorModel.
+- rate /= ImageUtil.getElementSize(sampleModel);
+- decoder.setRate(rate, 0);
+- }
+- }
+-
+- public synchronized Raster getTile(int tileX, int tileY) {
+- if (currentTile != null &&
+- currentTileGrid.x == tileX &&
+- currentTileGrid.y == tileY)
+- return currentTile;
+-
+- if (tileX < getMinTileX() || tileY < getMinTileY() ||
+- tileX > getMaxTileX() || tileY > getMaxTileY())
+- throw new IllegalArgumentException(I18N.getString("J2KReadState1"));
+-
+- int x = tileXToX(tileX);
+- int y = tileYToY(tileY);
+- currentTile = Raster.createWritableRaster(sampleModel,
+- new Point(x, y));
+-
+- try {
+- readAsRaster((WritableRaster)currentTile);
+- } catch(IOException ioe) {
+- throw new RuntimeException(ioe);
+- }
+-
+- if (currentTileGrid == null)
+- currentTileGrid = new Point(tileX, tileY);
+- else {
+- currentTileGrid.x = tileX;
+- currentTileGrid.y = tileY;
+- }
+-
+- return currentTile;
+- }
+-
+- synchronized WritableRaster readAsRaster(WritableRaster raster)
+- throws IOException {
+- int x = raster.getMinX();
+- int y = raster.getMinY();
+-
+- try {
+- if (noTransform) {
+- int E2c = (size.xosize + xStep - 1)/xStep;
+- int E1c = (size.yosize + yStep - 1)/yStep;
+-
+- int tXStart =
+- ((x + E2c)*xStep - size.xtosize)/size.xtsize;
+- int tXEnd =
+- ((x + raster.getWidth() - 1 + E2c)*xStep - size.xtosize)/
+- size.xtsize;
+- int tYStart =
+- ((y + E2c)*yStep - size.ytosize)/size.ytsize;
+- int tYEnd =
+- ((y + raster.getHeight() - 1 + E2c)*yStep - size.ytosize)/
+- size.ytsize;
+-
+- int sourceFormatTag =
+- MediaLibAccessor.findCompatibleTag(raster);
+-
+- if(tXStart == tXEnd && tYStart == tYEnd) {
+- MediaLibAccessor accessor =
+- new MediaLibAccessor(raster,
+- raster.getBounds().intersection(originalRegion),
+- sourceFormatTag, true);
+-
+- mediaLibImage[] mlImage = accessor.getMediaLibImages();
+-
+- //this image may be a subregion of the image in the stream
+- // So use the original tile number.
+- int tileNo = tXStart + tYStart*size.nxtiles;
+- decoder.decode(mlImage, tileNo);
+- accessor.copyDataToRaster(channelMap);
+- } else {
+- for(int ty = tYStart; ty <= tYEnd; ty++) {
+- for(int tx = tXStart; tx <= tXEnd; tx++) {
+- int sx = (size.xtosize + tx*size.xtsize +
+- xStep - 1)/xStep - E2c;
+- int sy = (size.ytosize + ty*size.ytsize +
+- yStep - 1)/yStep - E1c;
+- int ex = (size.xtosize + (tx + 1)*size.xtsize +
+- xStep - 1)/xStep - E2c;
+- int ey = (size.ytosize + (ty + 1)*size.ytsize +
+- yStep - 1)/yStep - E1c;
+- Rectangle subRect =
+- new Rectangle(sx, sy, ex - sx, ey - sy);
+- if(subRect.isEmpty()) {
+- continue;
+- }
+- if (rasForATile == null) {
+- rasForATile =
+- Raster.createWritableRaster
+- (originalSampleModel, null);
+- }
+- WritableRaster subRaster =
+- rasForATile.createWritableChild
+- (rasForATile.getMinX(),
+- rasForATile.getMinY(),
+- subRect.width, subRect.height,
+- subRect.x, subRect.y, null);
+- MediaLibAccessor accessor =
+- new MediaLibAccessor(subRaster,
+- subRect,
+- sourceFormatTag, true);
+-
+- mediaLibImage[] mlImage =
+- accessor.getMediaLibImages();
+-
+- int tileNo = tx + ty*size.nxtiles;
+- decoder.decode(mlImage, tileNo);
+- accessor.copyDataToRaster(channelMap);
+-
+- Rectangle rasBounds = raster.getBounds();
+- Rectangle childRect =
+- rasBounds.intersection(subRect);
+- if(childRect.isEmpty()) {
+- continue;
+- }
+-
+- Raster childRaster =
+- subRaster.createChild(childRect.x, childRect.y,
+- childRect.width,
+- childRect.height,
+- childRect.x, childRect.y,
+- null);
+- ((WritableRaster)raster).setRect(childRaster);
+- }
+- }
+- }
+- } else {
+- readSubsampledRaster(raster);
+- }
+- } catch (IOException e) {
+- throw new RuntimeException(e);
+- }
+-
+- return raster;
+- }
+-
+- private void readSubsampledRaster(WritableRaster raster)
+- throws IOException {
+-
+- int numBands = sourceBands.length;
+-
+- Rectangle destRect = raster.getBounds().intersection(destinationRegion);
+-
+- int offx = destinationRegion.x;
+- int offy = destinationRegion.y;
+-
+- int sourceSX = (destRect.x - offx) * scaleX + sourceOrigin.x;
+- int sourceSY = (destRect.y - offy) * scaleY + sourceOrigin.y;
+- int sourceEX = (destRect.width - 1) * scaleX + sourceSX;
+- int sourceEY = (destRect.height - 1)* scaleY + sourceSY;
+-
+- int E2c = (size.xosize + xStep - 1)/xStep;
+- int E1c = (size.yosize + yStep - 1)/yStep;
+-
+- int startXTile =
+- ((sourceSX + E2c)*xStep - size.xtosize)/size.xtsize;
+- int endXTile =
+- ((sourceEX + E2c)*xStep - size.xtosize)/size.xtsize;
+- int startYTile =
+- ((sourceSY + E1c)*yStep - size.ytosize)/size.ytsize;
+- int endYTile =
+- ((sourceEY + E1c)*yStep - size.ytosize)/size.ytsize;
+-
+- startXTile = clip(startXTile, 0, size.nxtiles - 1);
+- startYTile = clip(startYTile, 0, size.nytiles - 1);
+- endXTile = clip(endXTile, 0, size.nxtiles - 1);
+- endYTile = clip(endYTile, 0, size.nytiles - 1);
+-
+- int totalXTiles = endXTile - startXTile + 1;
+- int totalYTiles = endYTile - startYTile + 1;
+- int totalTiles = totalXTiles * totalYTiles;
+-
+- int[] pixbuf = null; // integer buffer for the decoded pixels.
+-
+- // Start the data delivery to the cached consumers tile by tile
+- for(int y=startYTile; y <= endYTile; y++){
+- if (reader.getAbortRequest())
+- break;
+-
+- // Loop on horizontal tiles
+- for(int x=startXTile; x <= endXTile; x++){
+- if (reader.getAbortRequest())
+- break;
+-
+- float percentage = // XXX Incorrect?
+- (x - startXTile + 1.0F + y * totalXTiles) / totalTiles;
+-
+- int startX =
+- (x * size.xtsize + size.xtosize + xStep - 1)/xStep - E2c;
+- int startY =
+- (y * size.ytsize + size.ytosize + yStep - 1)/yStep - E1c;
+- int endX =
+- ((x + 1)*size.xtsize + size.xtosize + xStep - 1)/
+- xStep - E2c;
+- int endY =
+- ((y + 1)*size.ytsize + size.ytosize + yStep - 1)/
+- yStep - E1c;
+-
+- if (rasForATile == null) {
+- rasForATile =
+- Raster.createWritableRaster(originalSampleModel,
+- new Point(startX, startY));
+- } else {
+- rasForATile =
+- rasForATile.createWritableTranslatedChild(startX, startY);
+- }
+-
+- int tw = endX - startX;
+- int th = endY - startY;
+- WritableRaster targetRas;
+- if(tw != tileWidth || th != tileHeight) {
+- targetRas = rasForATile.createWritableChild
+- (startX, startY, tw, th, startX, startY, null);
+- } else {
+- targetRas = rasForATile;
+- }
+-
+- int sourceFormatTag =
+- MediaLibAccessor.findCompatibleTag(targetRas);
+-
+- MediaLibAccessor accessor =
+- new MediaLibAccessor(targetRas,
+-// targetRas.getBounds(),
+- targetRas.getBounds().intersection(originalRegion),
+- sourceFormatTag, true);
+-
+- mediaLibImage[] mlImage = accessor.getMediaLibImages();
+- decoder.decode(mlImage, x + y * size.nxtiles);
+- accessor.copyDataToRaster(channelMap);
+-
+- int cTileHeight = th;
+- int cTileWidth = tw;
+-
+- if (startY + cTileHeight >= originalRegion.height)
+- cTileHeight = originalRegion.height - startY;
+-
+- if (startX + cTileWidth >= originalRegion.width)
+- cTileWidth = originalRegion.width - startX;
+-
+- int tx = startX;
+- int ty = startY;
+-
+- if (sourceSX > startX) {
+- cTileWidth += startX - sourceSX;
+- tx = sourceSX;
+- startX = sourceSX;
+- }
+-
+- if (sourceSY > startY) {
+- cTileHeight += startY - sourceSY;
+- ty = sourceSY;
+- startY = sourceSY;
+- }
+-
+- if (sourceEX < startX + cTileWidth - 1) {
+- cTileWidth += sourceEX - startX - cTileWidth + 1;
+- }
+-
+- if (sourceEY < startY + cTileHeight - 1) {
+- cTileHeight += sourceEY - startY - cTileHeight + 1;
+- }
+-
+- // The start X in the destination
+- int x1 = (startX + scaleX - 1 - sourceOrigin.x) / scaleX;
+- int x2 = (startX + scaleX -1 + cTileWidth - sourceOrigin.x) / scaleX;
+- int lineLength = x2 - x1;
+- // Suppress further processing if lineLength is non-positive
+- // XXX (which it should never be).
+- if(lineLength <= 0) continue;
+- x2 = (x2 - 1) * scaleX + sourceOrigin.x;
+-
+- int y1 = (startY + scaleY -1 - sourceOrigin.y) /scaleY;
+- startY = y1 * scaleY + sourceOrigin.y;
+- startX = x1 * scaleX + sourceOrigin.x;
+-
+- x1 += offx;
+- y1 += offy;
+-
+- if (pixbuf == null || pixbuf.length < lineLength)
+- pixbuf = new int[lineLength]; // line buffer for pixel data
+-
+- // Deliver in lines to reduce memory usage
+- for (int l = startY, m = y1; l < ty + cTileHeight; l += scaleY, m++) {
+- if (reader.getAbortRequest())
+- break;
+-
+- // Request line data
+- for (int i = 0; i < numBands; i++) {
+- for (int j = lineLength - 1, k1 = x2; j >= 0; j--, k1-=scaleX) {
+- pixbuf[j] = targetRas.getSample(k1, l, i);
+- }
+-
+- // Send the line data to the BufferedImage
+- raster.setSamples(x1, m, lineLength, 1, destinationBands[i], pixbuf);
+- }
+-
+- if (destImage != null)
+- reader.processImageUpdateWrapper(destImage, x1, m,
+- cTileWidth, 1, 1, 1,
+- destinationBands);
+-
+- reader.processImageProgressWrapper(percentage +
+- (l - startY + 1.0F) /
+- cTileHeight / totalTiles);
+- }
+- } // End loop on horizontal tiles
+- } // End loop on vertical tiles
+- }
+-
+- public void setDestImage(BufferedImage image) {
+- destImage = image;
+- }
+-
+- public void clearDestImage() {
+- destImage = null;
+- }
+-
+- private int getTileNum(int x, int y) {
+- int num = (y - getMinTileY()) * getNumXTiles() + x - getMinTileX();
+-
+- if (num < 0 || num >= getNumXTiles() * getNumYTiles())
+- throw new IllegalArgumentException(I18N.getString("J2KReadState1"));
+-
+- return num;
+- }
+-
+- private int clip(int value, int min, int max) {
+- if (value < min)
+- value = min;
+- if (value > max)
+- value = max;
+- return value;
+- }
+-
+- private SampleModel createSampleModel() throws IOException {
+- if (sampleModel != null)
+- return sampleModel;
+-
+- if (metadata == null)
+- readImageMetadata();
+-
+- HeaderBox header = (HeaderBox)metadata.getElement("JPEG2000HeaderBox");
+- int maxDepth = 0;
+- boolean isSigned = false;
+- if (header != null) {
+- maxDepth = header.getBitDepth();
+- isSigned = (maxDepth & 0x80) > 0;
+- maxDepth = (maxDepth & 0x7F) + 1;
+- } else {
+- CompParams compParam = new CompParams();
+- for (int i = 0; i < size.csize; i++) {
+- decoder.decodeCompParams(compParam, i);
+- maxDepth = (compParam.depth & 0x7F) + 1;
+- isSigned = (compParam.depth & 0x80) > 0 ? true : false;
+- }
+- }
+-
+- BitsPerComponentBox bits =
+- (BitsPerComponentBox)metadata.getElement("JPEG2000BitsPerComponentBox");
+-
+- if (bits != null) {
+- byte[] depths = bits.getBitDepth();
+- maxDepth = (depths[0] & 0x7F) + 1;
+- isSigned = (depths[0] & 0x80) > 0;
+- for (int i = 1; i < nComp; i++)
+- if (maxDepth > depths[sourceBands[i]])
+- maxDepth = (depths[sourceBands[i]] & 0x7F) + 1;
+- }
+-
+- int[] bandOffsets = new int[nComp];
+- for (int i = 0; i < nComp; i++)
+- bandOffsets[i] = i;
+-
+- ChannelDefinitionBox cdb=
+- (ChannelDefinitionBox)metadata.getElement("JPEG2000ChannelDefinitionBox");
+-
+- if (cdb != null &&
+- metadata.getElement("JPEG2000PaletteBox") == null) {
+- short[] assoc = cdb.getAssociation();
+- short[] types = cdb.getTypes();
+- short[] channels = cdb.getChannel();
+-
+- for (int i = 0; i < types.length; i++)
+- if (types[i] == 0)
+- bandOffsets[sourceBands[channels[i]]] = assoc[i] - 1;
+- else if (types[i] == 1 || types[i] == 2)
+- bandOffsets[sourceBands[channels[i]]] = channels[i];
+- }
+-
+- return createSampleModel(nComp, maxDepth, bandOffsets,
+- isSigned, tileWidth, tileHeight);
+- }
+-
+- private SampleModel createOriginalSampleModel() throws IOException {
+- if (metadata == null)
+- readImageMetadata();
+-
+- HeaderBox header = (HeaderBox)metadata.getElement("JPEG2000HeaderBox");
+- int maxDepth = 0;
+- boolean isSigned = false;
+- int nc = size.csize;
+- if (header != null) {
+- maxDepth = header.getBitDepth();
+- isSigned = (maxDepth & 0x80) > 0;
+- maxDepth = (maxDepth & 0x7F) + 1;
+- } else {
+- CompParams compParam = new CompParams();
+- for (int i = 0; i < size.csize; i++) {
+- decoder.decodeCompParams(compParam, i);
+- maxDepth = (compParam.depth & 0x7F) + 1;
+- isSigned = (compParam.depth & 0x80) > 0 ? true : false;
+- }
+- }
+-
+- BitsPerComponentBox bits =
+- (BitsPerComponentBox)metadata.getElement("JPEG2000BitsPerComponentBox");
+-
+- if (bits != null) {
+- byte[] depths = bits.getBitDepth();
+- maxDepth = (depths[0] & 0x7F) + 1;
+- isSigned = (depths[0] & 0x80) > 0;
+- for (int i = 1; i < nc; i++)
+- if (maxDepth > depths[i])
+- maxDepth = (depths[i] & 0x7F) + 1;
+- }
+-
+- int[] bandOffsets = new int[nc];
+- for (int i = 0; i < nc; i++)
+- bandOffsets[i] = i;
+-
+- ChannelDefinitionBox cdb=
+- (ChannelDefinitionBox)metadata.getElement("JPEG2000ChannelDefinitionBox");
+- if (cdb != null &&
+- metadata.getElement("JPEG2000PaletteBox") == null) {
+- short[] assoc = cdb.getAssociation();
+- short[] types = cdb.getTypes();
+- short[] channels = cdb.getChannel();
+-
+- channelMap = new int[nc];
+-
+- for (int i = 0; i < types.length; i++)
+- if (types[i] == 0) {
+- bandOffsets[channels[i]] = assoc[i] - 1;
+- channelMap[assoc[i] - 1] = channels[i];
+- }
+- else if (types[i] == 1 || types[i] == 2) {
+- bandOffsets[channels[i]] = channels[i];
+- channelMap[channels[i]] = channels[i];
+- }
+- }
+-
+- return createSampleModel(nc, maxDepth, bandOffsets, isSigned,
+- tileWidth, tileHeight);
+- }
+-
+- private SampleModel createSampleModel(int nc, int maxDepth,
+- int[] bandOffsets, boolean isSigned,
+- int tw, int th) {
+- SampleModel sm = null;
+- if (nc == 1 && (maxDepth == 1 || maxDepth == 2 || maxDepth == 4))
+- sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE,
+- tw, th, maxDepth);
+- else if (maxDepth <= 8)
+- sm = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE,
+- tw, th, nc, tw * nc, bandOffsets);
+- else if (maxDepth <=16)
+- sm = new PixelInterleavedSampleModel(isSigned ? DataBuffer.TYPE_SHORT : DataBuffer.TYPE_USHORT,
+- tw, th, nc, tw * nc, bandOffsets);
+- else if (maxDepth <= 32)
+- sm = new PixelInterleavedSampleModel(DataBuffer.TYPE_INT,
+- tw, th, nComp, tw * nComp,
+- bandOffsets);
+- else
+- throw new IllegalArgumentException(I18N.getString("J2KReadState11") + " " +
+- + maxDepth);
+-
+- return sm;
+- }
+-
+- private ColorModel createColorModel() throws IOException {
+- if (colorModel != null)
+- return colorModel;
+-
+- PaletteBox pBox = (PaletteBox)metadata.getElement("JPEG2000PaletteBox");
+- ChannelDefinitionBox cdef =
+- (ChannelDefinitionBox)metadata.getElement("JPEG2000ChannelDefinitionBox");
+-
+- // Check 'nComp' instance variable here in case there is an
+- // embedded palette such as in the pngsuite images pp0n2c16.png
+- // and pp0n6a08.png.
+- if (pBox != null && nComp == 1) {
+- byte[][] lut = pBox.getLUT();
+- int numComp = pBox.getNumComp();
+-
+- int[] mapping = new int[numComp];
+-
+- for (int i = 0; i < numComp; i++)
+- mapping[i] = i;
+-
+- ComponentMappingBox cmap =
+- (ComponentMappingBox)metadata.getElement("JPEG2000ComponentMappingBox");
+-
+- short[] comps = null;
+- byte[] type = null;
+- byte[] maps = null;
+-
+- if (cmap != null) {
+- comps = cmap.getComponent();
+- type = cmap.getComponentType();
+- maps = cmap.getComponentAssociation();
+- }
+-
+- if (comps != null)
+- for (int i = 0; i < numComp; i++)
+- if (type[i] == 1)
+- mapping[i] = maps[i];
+-
+- if (numComp == 3)
+- colorModel = new IndexColorModel(sampleModel.getSampleSize(0), lut[0].length,
+- lut[mapping[0]],
+- lut[mapping[1]],
+- lut[mapping[2]]);
+- else if (numComp == 4)
+- colorModel = new IndexColorModel(sampleModel.getSampleSize(0), lut[0].length,
+- lut[mapping[0]],
+- lut[mapping[1]],
+- lut[mapping[2]],
+- lut[mapping[3]]);
+- } else if (cdef != null){
+- HeaderBox header =
+- (HeaderBox)metadata.getElement("JPEG2000HeaderBox");
+- int numComp = header.getNumComponents();
+- int bitDepth = header.getBitDepth();
+-
+- boolean hasAlpha = false;
+- int alphaChannel = numComp - 1;
+-
+- short[] channels = cdef.getChannel();
+- short[] cType = cdef.getTypes();
+- short[] associations = cdef.getAssociation();
+-
+- for (int i = 0; i < channels.length; i++) {
+- if (cType[i] == 1 && channels[i] == alphaChannel)
+- hasAlpha = true;
+- }
+-
+- boolean[] isPremultiplied = new boolean[] {false};
+-
+- if (hasAlpha) {
+- isPremultiplied = new boolean[alphaChannel];
+-
+- for (int i = 0; i < alphaChannel; i++)
+- isPremultiplied[i] = false;
+-
+- for (int i = 0; i < channels.length; i++) {
+- if (cType[i] == 2)
+- isPremultiplied[associations[i] - 1] = true;
+- }
+-
+- for (int i = 1; i < alphaChannel; i++)
+- isPremultiplied[0] &= isPremultiplied[i];
+- }
+-
+- ColorSpecificationBox cBox =
+- (ColorSpecificationBox)metadata.getElement("JPEG2000ColorSpecificationBox");
+- ICC_Profile profile = null;
+- int colorSpaceType = 0;
+-
+- if (cBox != null) {
+- profile = cBox.getICCProfile();
+- colorSpaceType = cBox.getEnumeratedColorSpace();
+- }
+-
+- ColorSpace cs = null;
+- if (profile != null)
+- cs = new ICC_ColorSpace(profile);
+- else if (colorSpaceType == ColorSpecificationBox.ECS_sRGB)
+- cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
+- else if (colorSpaceType == ColorSpecificationBox.ECS_GRAY)
+- cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
+- else if (colorSpaceType == ColorSpecificationBox.ECS_YCC)
+- cs = ColorSpace.getInstance(ColorSpace.CS_PYCC);
+-
+- byte[] bitDepths = null;
+- boolean isSigned = ((bitDepth & 0x80) == 0x80) ? true : false;
+-
+- BitsPerComponentBox bitBox =
+- (BitsPerComponentBox)metadata.getElement("JPEG2000BitsPerComponentBox");
+- if (bitBox != null)
+- bitDepths = bitBox.getBitDepth();
+-
+- int[] bits = new int[numComp];
+- for (int i = 0; i < numComp; i++)
+- if (bitDepths != null)
+- bits[i] = (bitDepths[i] & 0x7F) + 1;
+- else
+- bits[i] = (bitDepth &0x7F) + 1;
+-
+- int maxBitDepth = 1 + (bitDepth & 0x7F);
+- if (bitDepths != null)
+- for (int i = 0; i < numComp; i++)
+- if (bits[i] > maxBitDepth)
+- maxBitDepth = bits[i];
+-
+- int type = -1;
+-
+- if (maxBitDepth <= 8)
+- type = DataBuffer.TYPE_BYTE;
+- else if (maxBitDepth <= 16)
+- type = isSigned ? DataBuffer.TYPE_SHORT : DataBuffer.TYPE_USHORT;
+- else if (maxBitDepth <= 32)
+- type = DataBuffer.TYPE_INT;
+-
+- if (type == -1)
+- return null;
+-
+- if (cs != null) {
+- colorModel = new ComponentColorModel(cs,
+- bits,
+- hasAlpha,
+- isPremultiplied[0],
+- hasAlpha ? Transparency.TRANSLUCENT : Transparency.OPAQUE ,
+- type);
+- }
+- }
+-
+- if (colorModel != null)
+- return colorModel;
+-
+- if(nComp <= 4) {
+- // XXX: Code essentially duplicated from FileFormatReader.getColorModel().
+- // Create the ColorModel from the SIZ marker segment parameters.
+- ColorSpace cs;
+- if(nComp > 2) {
+- cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
+- } else {
+- cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
+- }
+-
+- int[] bitsPerComponent = new int[nComp];
+- boolean isSigned = false;
+- int maxBitDepth = -1;
+- for(int i = 0; i < nComp; i++) {
+- bitsPerComponent[i] = (compParam.depth & 0x7f) + 1;
+- if(maxBitDepth < bitsPerComponent[i]) {
+- maxBitDepth = bitsPerComponent[i];
+- }
+- isSigned |= (compParam.depth & 0x80) != 0;
+- }
+-
+- boolean hasAlpha = nComp % 2 == 0;
+-
+- int type = -1;
+-
+- if (maxBitDepth <= 8) {
+- type = DataBuffer.TYPE_BYTE;
+- } else if (maxBitDepth <= 16) {
+- type = isSigned ? DataBuffer.TYPE_SHORT : DataBuffer.TYPE_USHORT;
+- } else if (maxBitDepth <= 32) {
+- type = DataBuffer.TYPE_INT;
+- }
+-
+- if (type != -1) {
+- if (nComp == 1 &&
+- (maxBitDepth == 1 || maxBitDepth == 2 ||
+- maxBitDepth == 4)) {
+- colorModel = ImageUtil.createColorModel(getSampleModel());
+- } else {
+- colorModel = new ComponentColorModel(cs,
+- bitsPerComponent,
+- hasAlpha,
+- false,
+- hasAlpha ?
+- Transparency.TRANSLUCENT :
+- Transparency.OPAQUE ,
+- type);
+- }
+-
+- return colorModel;
+- }
+- }
+-
+- return ImageUtil.createColorModel(null, getSampleModel());
+- }
+-
+- public J2KMetadata readImageMetadata() throws IOException {
+- if (metadata == null) {
+- metadata = new J2KMetadata();
+- com.sun.medialib.codec.jp2k.Box mlibBox = null;
+- com.sun.media.imageioimpl.plugins.jpeg2000.Box box = null;
+-
+- while ((mlibBox = decoder.decodeBox()) != null) {
+- box = null;
+- Class c = com.sun.media.imageioimpl.plugins.jpeg2000.Box.getBoxClass(mlibBox.type);
+- if (c != null) {
+- try {
+- Constructor cons = c.getConstructor(new Class[]{byte[].class});
+- if (cons != null) {
+- box = (Box)cons.newInstance(new Object[]{mlibBox.data});
+- }
+- } catch(NoSuchMethodException e) {
+- try {
+- Constructor cons = c.getConstructor(new Class[]{int.class, byte[].class});
+- if (cons != null) {
+- box = (com.sun.media.imageioimpl.plugins.jpeg2000.Box)
+- cons.newInstance(new Object[]{new Integer(mlibBox.type), mlibBox.data});
+- }
+- } catch (NoSuchMethodException e1) {
+- box = createUnknowBox(mlibBox);
+- } catch(InvocationTargetException e1) {
+- box = createUnknowBox(mlibBox);
+- } catch (IllegalAccessException e1) {
+- box = createUnknowBox(mlibBox);
+- } catch (InstantiationException e1) {
+- box = createUnknowBox(mlibBox);
+- }
+- } catch(InvocationTargetException e) {
+- box = createUnknowBox(mlibBox);
+- } catch (IllegalAccessException e) {
+- box = createUnknowBox(mlibBox);
+- } catch (InstantiationException e) {
+- box = createUnknowBox(mlibBox);
+- }
+- } else {
+- if (mlibBox.data != null)
+- box = createUnknowBox(mlibBox);
+- }
+- if (box != null)
+- metadata.addNode(box);
+- }
+- }
+-
+- return metadata;
+- }
+-
+- private com.sun.media.imageioimpl.plugins.jpeg2000.Box
+- createUnknowBox(com.sun.medialib.codec.jp2k.Box mlibBox) {
+- return
+- new com.sun.media.imageioimpl.plugins.jpeg2000.Box(8 + mlibBox.data.length,
+- mlibBox.type,
+- mlibBox.data);
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KRenderedImage.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KRenderedImage.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KRenderedImage.java 2006-09-27 20:57:57.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KRenderedImage.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,129 +0,0 @@
+-/*
+- * $RCSfile: J2KRenderedImage.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.2 $
+- * $Date: 2006/09/28 00:57:57 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.awt.Point;
+-import java.awt.Rectangle;
+-import java.awt.image.Raster;
+-import java.awt.image.WritableRaster;
+-import java.io.*;
+-import javax.imageio.stream.ImageInputStream;
+-import jj2000.j2k.codestream.reader.*;
+-
+-import com.sun.media.imageioimpl.common.SimpleRenderedImage;
+-
+-public class J2KRenderedImage extends SimpleRenderedImage {
+- private Raster currentTile;
+- private Point currentTileGrid;
+-
+- private J2KReadState readState;
+-
+- public J2KRenderedImage(ImageInputStream iis,
+- J2KImageReadParamJava param,
+- J2KMetadata metadata,
+- J2KImageReader reader) throws IOException {
+- this(new J2KReadState(iis, param, metadata, reader));
+- }
+-
+- public J2KRenderedImage(ImageInputStream iis,
+- J2KImageReadParamJava param,
+- J2KImageReader reader) throws IOException {
+- this(new J2KReadState(iis, param, reader));
+- }
+-
+- public J2KRenderedImage(J2KReadState readState) {
+- this.readState = readState;
+-
+- HeaderDecoder hd = readState.getHeader();
+-
+- //determnined by destination
+- Rectangle destinationRegion = readState.getDestinationRegion();
+- width = destinationRegion.width;
+- height = destinationRegion.height;
+- minX = destinationRegion.x;
+- minY = destinationRegion.y;
+-
+- Rectangle tile0Rect = readState.getTile0Rect();
+- tileWidth = tile0Rect.width;
+- tileHeight = tile0Rect.height;
+- tileGridXOffset = tile0Rect.x;
+- tileGridYOffset = tile0Rect.y;
+-
+- sampleModel = readState.getSampleModel();
+- colorModel = readState.getColorModel();
+- }
+-
+- public synchronized Raster getTile(int tileX, int tileY) {
+- if (currentTile != null &&
+- currentTileGrid.x == tileX &&
+- currentTileGrid.y == tileY)
+- return currentTile;
+-
+- if (tileX >= getNumXTiles() || tileY >= getNumYTiles())
+- throw new IllegalArgumentException(I18N.getString("J2KReadState1"));
+-
+- try {
+- int x = tileXToX(tileX);
+- int y = tileYToY(tileY);
+- currentTile =
+- Raster.createWritableRaster(sampleModel,
+- new Point(x, y));
+- currentTile = readState.getTile(tileX,
+- tileY,
+- (WritableRaster)currentTile);
+- } catch (IOException e) {
+- throw new RuntimeException(e);
+- }
+-
+- if (currentTileGrid == null)
+- currentTileGrid = new Point(tileX, tileY);
+- else {
+- currentTileGrid.x = tileX;
+- currentTileGrid.y = tileY;
+- }
+-
+- return currentTile;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/MediaLibAccessor.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/MediaLibAccessor.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/MediaLibAccessor.java 2005-02-11 00:01:36.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/MediaLibAccessor.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,1222 +0,0 @@
+-/*
+- * $RCSfile: MediaLibAccessor.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:36 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-import java.awt.Rectangle;
+-import java.awt.image.ColorModel;
+-import java.awt.image.ComponentSampleModel;
+-import java.awt.image.ComponentColorModel;
+-import java.awt.image.DataBuffer;
+-import java.awt.image.DataBufferByte;
+-import java.awt.image.DataBufferDouble;
+-import java.awt.image.DataBufferFloat;
+-import java.awt.image.DataBufferInt;
+-import java.awt.image.DataBufferShort;
+-import java.awt.image.DataBufferUShort;
+-import java.awt.image.MultiPixelPackedSampleModel;
+-import java.awt.image.Raster;
+-import java.awt.image.SampleModel;
+-import java.awt.image.WritableRaster;
+-import java.awt.image.RenderedImage;
+-import java.awt.image.renderable.ParameterBlock;
+-import java.io.FileNotFoundException;
+-import java.io.FilePermission;
+-import java.io.InputStream;
+-import java.io.IOException;
+-import java.lang.NoClassDefFoundError;
+-import java.security.AccessControlException;
+-import java.security.AccessController;
+-import java.security.PrivilegedAction;
+-
+-import com.sun.media.imageioimpl.common.ImageUtil;
+-import com.sun.medialib.codec.jiio.Util;
+-import com.sun.medialib.codec.jiio.Constants;
+-import com.sun.medialib.codec.jiio.mediaLibImage;
+-
+-/**
+- * An adapter class for presenting image data in a mediaLibImage
+- * format, even if the data isn't stored that way. MediaLibAccessor
+- * is meant to make the common case (ComponentRasters) and allow
+- * them to be accelerated via medialib. Note that unlike RasterAccessor,
+- * MediaLibAccessor does not work with all cases. In the event that
+- * MediaLibAccessor can not deal with a give collection of Rasters,
+- * findCompatibleTag will return the value MediaLibAccessor.TAG_INCOMPATIBLE.
+- * OpImages that use MediaLibAccessor should be paired with RIF's
+- * which check that findCompatibleTag returns a valid tag before
+- * actually constructing the Mlib OpImage.
+- */
+-
+-public class MediaLibAccessor {
+- /**
+- * Value indicating how far COPY_MASK info is shifted to avoid
+- * interfering with the data type info
+- */
+- private static final int COPY_MASK_SHIFT = 7;
+-
+- /* Value indicating how many bits the COPY_MASK is */
+- private static final int COPY_MASK_SIZE = 1;
+-
+- /** The bits of a FormatTag associated with how dataArrays are obtained. */
+- public static final int COPY_MASK = 0x1 << COPY_MASK_SHIFT;
+-
+- /** Flag indicating data is raster's data. */
+- public static final int UNCOPIED = 0x0 << COPY_MASK_SHIFT;
+-
+- /** Flag indicating data is a copy of the raster's data. */
+- public static final int COPIED = 0x01 << COPY_MASK_SHIFT;
+-
+- /** The bits of a FormatTag associated with pixel datatype. */
+- public static final int DATATYPE_MASK = (0x1 << COPY_MASK_SHIFT) - 1;
+-
+- /**
+- * Value indicating how far BINARY_MASK info is shifted to avoid
+- * interfering with the data type and copying info.
+- */
+- private static final int BINARY_MASK_SHIFT =
+- COPY_MASK_SHIFT+COPY_MASK_SIZE;
+-
+- /** Value indicating how many bits the BINARY_MASK is */
+- private static final int BINARY_MASK_SIZE = 1;
+-
+- /** The bits of a FormatTag associated with binary data. */
+- public static final int BINARY_MASK =
+- ((1 << BINARY_MASK_SIZE) - 1) << BINARY_MASK_SHIFT;
+-
+- /** Flag indicating data are not binary. */
+- public static final int NONBINARY = 0x0 << BINARY_MASK_SHIFT;
+-
+- /** Flag indicating data are binary. */
+- public static final int BINARY = 0x1 << BINARY_MASK_SHIFT;
+-
+- /** FormatTag indicating data in byte arrays and uncopied. */
+- public static final int
+- TAG_BYTE_UNCOPIED = DataBuffer.TYPE_BYTE | UNCOPIED;
+-
+- /** FormatTag indicating data in unsigned short arrays and uncopied. */
+- public static final int
+- TAG_USHORT_UNCOPIED = DataBuffer.TYPE_USHORT | UNCOPIED;
+-
+- /** FormatTag indicating data in short arrays and uncopied. */
+- public static final int
+- TAG_SHORT_UNCOPIED = DataBuffer.TYPE_SHORT | UNCOPIED;
+-
+- /** FormatTag indicating data in integer arrays and uncopied. */
+- public static final int
+- TAG_INT_UNCOPIED = DataBuffer.TYPE_INT | UNCOPIED;
+-
+- /** FormatTag indicating data in float arrays and uncopied. */
+- public static final int
+- TAG_FLOAT_UNCOPIED = DataBuffer.TYPE_FLOAT | UNCOPIED;
+-
+- /** FormatTag indicating data in double arrays and uncopied. */
+- public static final int
+- TAG_DOUBLE_UNCOPIED = DataBuffer.TYPE_DOUBLE | UNCOPIED;
+-
+- /** FormatTag indicating data in byte arrays and uncopied. */
+- public static final int
+- TAG_BYTE_COPIED = DataBuffer.TYPE_BYTE | COPIED;
+-
+- /** FormatTag indicating data in unsigned short arrays and copied. */
+- public static final int
+- TAG_USHORT_COPIED = DataBuffer.TYPE_USHORT | COPIED;
+-
+- /** FormatTag indicating data in short arrays and copied. */
+- public static final int
+- TAG_SHORT_COPIED = DataBuffer.TYPE_SHORT | COPIED;
+-
+- /** FormatTag indicating data in short arrays and copied. */
+- public static final int
+- TAG_INT_COPIED = DataBuffer.TYPE_INT | COPIED;
+-
+- /** FormatTag indicating data in float arrays and copied. */
+- public static final int
+- TAG_FLOAT_COPIED = DataBuffer.TYPE_FLOAT | COPIED;
+-
+- /** FormatTag indicating data in double arrays and copied. */
+- public static final int
+- TAG_DOUBLE_COPIED = DataBuffer.TYPE_DOUBLE | COPIED;
+-
+- /** The raster that is the source of pixel data. */
+- protected Raster raster;
+-
+- /** The rectangle of the raster that MediaLibAccessor addresses. */
+- protected Rectangle rect;
+-
+- /** The number of bands per pixel in the data array. */
+- protected int numBands;
+-
+- /** The offsets of each band in the src image */
+- protected int bandOffsets[];
+-
+- /** Tag indicating the data type of the data and whether its copied */
+- protected int formatTag;
+-
+- /** Area of mediaLib images that represent image data */
+- protected mediaLibImage mlimages[] = null;
+-
+- /**
+- * Whether packed data are preferred when processing binary images.
+- * This tag is ignored if the data are not binary.
+- */
+- private boolean areBinaryDataPacked = false;
+-
+- /**
+- * Returns the most efficient FormatTag that is compatible with
+- * the destination raster and all source rasters.
+- *
+- * @param srcs the source Raster
; may be null
.
+- * @param dst the destination Raster
.
+- */
+- public static int findCompatibleTag(Raster src) {
+- SampleModel dstSM = src.getSampleModel();
+- int dstDT = dstSM.getDataType();
+-
+- int defaultDataType = dstSM.getDataType();
+-
+- boolean allComponentSampleModel =
+- dstSM instanceof ComponentSampleModel;
+- boolean allBinary = ImageUtil.isBinary(dstSM);
+-
+- if(allBinary) {
+- // The copy flag is not set until the mediaLibImage is
+- // created as knowing this information requires too much
+- // processing to determine here.
+- return DataBuffer.TYPE_BYTE | BINARY;
+- }
+-
+- if (!allComponentSampleModel) {
+- if ((defaultDataType == DataBuffer.TYPE_BYTE) ||
+- (defaultDataType == DataBuffer.TYPE_USHORT) ||
+- (defaultDataType == DataBuffer.TYPE_SHORT)) {
+- defaultDataType = DataBuffer.TYPE_INT;
+- }
+- }
+-
+- int tag = defaultDataType | COPIED;
+-
+- if (!allComponentSampleModel) {
+- return tag;
+- }
+-
+- if (isPixelSequential(dstSM))
+- return dstDT | UNCOPIED;
+- return tag;
+- }
+-
+- /**
+- * Determines if the SampleModel stores data in a way that can
+- * be represented by a mediaLibImage without copying
+- */
+- public static boolean isPixelSequential(SampleModel sm) {
+- ComponentSampleModel csm = null;
+- if (sm instanceof ComponentSampleModel) {
+- csm = (ComponentSampleModel)sm;
+- } else {
+- return false;
+- }
+- int pixelStride = csm.getPixelStride();
+- int bandOffsets[] = csm.getBandOffsets();
+- int bankIndices[] = csm.getBankIndices();
+- if (pixelStride != bandOffsets.length) {
+- return false;
+- }
+-
+- //XXX: for band-selection result
+- if (pixelStride != sm.getNumBands())
+- return false;
+-
+- for (int i = 0; i < bandOffsets.length; i++) {
+- if (bandOffsets[i] >= pixelStride ||
+- bankIndices[i] != bankIndices[0]) {
+- return false;
+- }
+- for (int j = i+1; j < bandOffsets.length; j++) {
+- if (bandOffsets[i] == bandOffsets[j]) {
+- return false;
+- }
+-
+- //XXX: for BGR images
+- if (bandOffsets[i] != i)
+- return false;
+- }
+- }
+- return true;
+- }
+-
+- public static int getMediaLibDataType(int formatTag) {
+- int dataType = formatTag & DATATYPE_MASK;
+- switch (dataType) {
+- case DataBuffer.TYPE_BYTE:
+- return Constants.MLIB_BYTE;
+- case DataBuffer.TYPE_USHORT:
+- return Constants.MLIB_USHORT;
+- case DataBuffer.TYPE_SHORT:
+- return Constants.MLIB_SHORT;
+- case DataBuffer.TYPE_INT:
+- return Constants.MLIB_INT;
+- case DataBuffer.TYPE_DOUBLE:
+- return Constants.MLIB_DOUBLE;
+- case DataBuffer.TYPE_FLOAT:
+- return Constants.MLIB_FLOAT;
+- }
+- return -1;
+- }
+-
+- /**
+- * Constructs a MediaLibAccessor object out of a Raster, Rectangle
+- * and formatTag returned from MediaLibAccessor.findCompatibleTag().
+- *
+- * In the case of binary data the copy mask bits of the formatTag
+- * will be reset within the constructor according to whether the
+- * data are in fact copied. This cannot be easily determined before
+- * the data are actually copied.
+- */
+- public MediaLibAccessor(Raster raster, Rectangle rect, int formatTag,
+- boolean preferPacked) {
+- areBinaryDataPacked = preferPacked;
+-
+- this.raster = raster;
+- this.rect = new Rectangle(rect);
+- this.formatTag = formatTag;
+-
+- if(isBinary()) {
+- // Set binary-specific fields and return.
+- numBands = 1;
+- bandOffsets = new int[] {0};
+-
+- int mlibType;
+- int scanlineStride;
+- byte[] bdata;
+- mlimages = new mediaLibImage[1];
+-
+- if(areBinaryDataPacked) {
+- mlibType = Constants.MLIB_BIT;
+- scanlineStride = (rect.width+7)/8;
+- bdata = ImageUtil.getPackedBinaryData(raster, rect);
+-
+- // Update format tag depending on whether the data were copied.
+- if(bdata ==
+- ((DataBufferByte)raster.getDataBuffer()).getData()) {
+- this.formatTag |= UNCOPIED;
+- } else {
+- this.formatTag |= COPIED;
+- }
+- } else { // unpacked
+- mlibType = Constants.MLIB_BYTE;
+- scanlineStride = rect.width;
+- bdata = ImageUtil.getUnpackedBinaryData(raster, rect);
+- this.formatTag |= COPIED;
+- }
+-
+- mlimages[0] = new mediaLibImage(mlibType,
+- 1,
+- rect.width,
+- rect.height,
+- scanlineStride,
+- 0,
+- bdata);
+-
+- return;
+- }
+-
+- if ((formatTag & COPY_MASK) == UNCOPIED) {
+- ComponentSampleModel csm =
+- (ComponentSampleModel)raster.getSampleModel();
+-
+- numBands = csm.getNumBands();
+- bandOffsets = csm.getBandOffsets();
+- int dataOffset = raster.getDataBuffer().getOffset();
+- dataOffset +=
+- (rect.y-raster.getSampleModelTranslateY())*csm.getScanlineStride()+
+- (rect.x-raster.getSampleModelTranslateX())*csm.getPixelStride();
+-
+- // dataoffset should and is in terms of dataElements
+-
+- // scanline stride should be in terms of dataElements
+- int scanlineStride = csm.getScanlineStride();
+-
+- switch (formatTag & DATATYPE_MASK) {
+- case DataBuffer.TYPE_BYTE:
+- DataBufferByte dbb = (DataBufferByte)raster.getDataBuffer();
+- mlimages = new mediaLibImage[1];
+- mlimages[0] =
+- new mediaLibImage(Constants.MLIB_BYTE,
+- numBands,
+- rect.width,
+- rect.height,
+- scanlineStride,
+- dataOffset,
+- dbb.getData());
+- break;
+-
+- case DataBuffer.TYPE_USHORT:
+- DataBufferUShort dbus =
+- (DataBufferUShort)raster.getDataBuffer();
+- mlimages = new mediaLibImage[1];
+- mlimages[0] =
+- new mediaLibImage(Constants.MLIB_USHORT,
+- numBands,
+- rect.width,
+- rect.height,
+- scanlineStride,
+- dataOffset,
+- dbus.getData());
+- break;
+- case DataBuffer.TYPE_SHORT:
+- DataBufferShort dbs = (DataBufferShort)raster.getDataBuffer();
+- mlimages = new mediaLibImage[1];
+- mlimages[0] =
+- new mediaLibImage(Constants.MLIB_SHORT,
+- numBands,
+- rect.width,
+- rect.height,
+- scanlineStride,
+- dataOffset,
+- dbs.getData());
+- break;
+- case DataBuffer.TYPE_INT:
+- DataBufferInt dbi = (DataBufferInt)raster.getDataBuffer();
+- mlimages = new mediaLibImage[1];
+- mlimages[0] =
+- new mediaLibImage(Constants.MLIB_INT,
+- numBands,
+- rect.width,
+- rect.height,
+- scanlineStride,
+- dataOffset,
+- dbi.getData());
+- break;
+- case DataBuffer.TYPE_FLOAT:
+- DataBufferFloat dbf = (DataBufferFloat)raster.getDataBuffer();
+- mlimages = new mediaLibImage[1];
+- mlimages[0] =
+- new mediaLibImage(Constants.MLIB_FLOAT,
+- numBands,
+- rect.width,
+- rect.height,
+- scanlineStride,
+- dataOffset,
+- dbf.getData());
+- break;
+- case DataBuffer.TYPE_DOUBLE:
+- DataBufferDouble dbd = (DataBufferDouble)raster.getDataBuffer();
+- mlimages = new mediaLibImage[1];
+- mlimages[0] =
+- new mediaLibImage(Constants.MLIB_DOUBLE,
+- numBands,
+- rect.width,
+- rect.height,
+- scanlineStride,
+- dataOffset,
+- dbd.getData());
+- break;
+- default:
+- throw new IllegalArgumentException((formatTag & DATATYPE_MASK) +
+- "MediaLibAccessor does not recognize this datatype.");
+- }
+- } else {
+- // Copying the data because we can't deal with it
+- numBands = raster.getNumBands();
+- bandOffsets = new int[numBands];
+- for (int i = 0; i < numBands; i++) {
+- bandOffsets[i] = i;
+- }
+- int scanlineStride = rect.width*numBands;
+-
+- switch (formatTag & DATATYPE_MASK) {
+- case DataBuffer.TYPE_BYTE:
+- byte bdata[] = new byte[rect.width*rect.height*numBands];
+- mlimages = new mediaLibImage[1];
+- mlimages[0] =
+- new mediaLibImage(Constants.MLIB_BYTE,
+- numBands,
+- rect.width,
+- rect.height,
+- scanlineStride,
+- 0,
+- bdata);
+- break;
+- case DataBuffer.TYPE_USHORT:
+- short usdata[] = new short[rect.width*rect.height*numBands];
+- mlimages = new mediaLibImage[1];
+- mlimages[0] =
+- new mediaLibImage(Constants.MLIB_USHORT,
+- numBands,
+- rect.width,
+- rect.height,
+- scanlineStride,
+- 0,
+- usdata);
+- break;
+- case DataBuffer.TYPE_SHORT:
+- short sdata[] = new short[rect.width*rect.height*numBands];
+- mlimages = new mediaLibImage[1];
+- mlimages[0] =
+- new mediaLibImage(Constants.MLIB_SHORT,
+- numBands,
+- rect.width,
+- rect.height,
+- scanlineStride,
+- 0,
+- sdata);
+- break;
+- case DataBuffer.TYPE_INT:
+- int idata[] = new int[rect.width*rect.height*numBands];
+- mlimages = new mediaLibImage[1];
+- mlimages[0] =
+- new mediaLibImage(Constants.MLIB_INT,
+- numBands,
+- rect.width,
+- rect.height,
+- scanlineStride,
+- 0,
+- idata);
+- break;
+- case DataBuffer.TYPE_FLOAT:
+- float fdata[] = new float[rect.width*rect.height*numBands];
+- mlimages = new mediaLibImage[1];
+- mlimages[0] =
+- new mediaLibImage(Constants.MLIB_FLOAT,
+- numBands,
+- rect.width,
+- rect.height,
+- scanlineStride,
+- 0,
+- fdata);
+- break;
+- case DataBuffer.TYPE_DOUBLE:
+- double ddata[] = new double[rect.width*rect.height*numBands];
+- mlimages = new mediaLibImage[1];
+- mlimages[0] =
+- new mediaLibImage(Constants.MLIB_DOUBLE,
+- numBands,
+- rect.width,
+- rect.height,
+- scanlineStride,
+- 0,
+- ddata);
+- break;
+- default:
+- throw new IllegalArgumentException((formatTag & DATATYPE_MASK) +
+- "MediaLibAccessor does not recognize this datatype.");
+- }
+- copyDataFromRaster();
+- }
+- }
+-
+- /**
+- * Returns true
if the MediaLibAccessor
+- * represents binary data.
+- */
+- public boolean isBinary() {
+- return ((formatTag & BINARY_MASK) == BINARY);
+- }
+-
+- /**
+- * Returns an array of mediaLibImages which represents the input raster.
+- * An array is returned instead of a single mediaLibImage because
+- * in some cases, an input Raster can't be represented by one
+- * mediaLibImage (unless copying is done) but can be represented
+- * by several mediaLibImages without copying.
+- */
+- public mediaLibImage[] getMediaLibImages() {
+- return mlimages;
+- }
+-
+- /**
+- * Returns the data type of the RasterAccessor object. Note that
+- * this datatype is not necessarily the same data type as the
+- * underlying raster.
+- */
+- public int getDataType() {
+- return formatTag & DATATYPE_MASK;
+- }
+-
+- /**
+- * Returns true if the MediaLibAccessors's data is copied from it's
+- * raster.
+- */
+- public boolean isDataCopy() {
+- return ((formatTag & COPY_MASK) == COPIED);
+- }
+-
+- /** Returns the bandOffsets. */
+- public int[] getBandOffsets() {
+- return bandOffsets;
+- }
+-
+- /**
+- * Returns parameters in the appropriate order if MediaLibAccessor
+- * has reordered the bands or is attempting to make a
+- * BandSequential image look like multiple PixelSequentialImages
+- */
+- public int[] getIntParameters(int band, int params[]) {
+- int returnParams[] = new int[numBands];
+- for (int i = 0; i < numBands; i++) {
+- returnParams[i] = params[bandOffsets[i+band]];
+- }
+- return returnParams;
+- }
+-
+- /**
+- * Returns parameters in the appropriate order if MediaLibAccessor
+- * has reordered the bands or is attempting to make a
+- * BandSequential image look like multiple PixelSequentialImages
+- */
+- public int[][] getIntArrayParameters(int band, int[][] params) {
+- int returnParams[][] = new int[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- returnParams[i] = params[bandOffsets[i+band]];
+- }
+- return returnParams;
+- }
+-
+- /**
+- * Returns parameters in the appropriate order if MediaLibAccessor
+- * has reordered the bands or is attempting to make a
+- * BandSequential image look like multiple PixelSequentialImages
+- */
+- public double[] getDoubleParameters(int band, double params[]) {
+- double returnParams[] = new double[numBands];
+- for (int i = 0; i < numBands; i++) {
+- returnParams[i] = params[bandOffsets[i+band]];
+- }
+- return returnParams;
+- }
+-
+-
+- /**
+- * Copy data from Raster to MediaLib image
+- */
+- private void copyDataFromRaster() {
+- // Writeback should only be necessary on destRasters which
+- // should be writable so this cast should succeed.
+-
+- if (raster.getSampleModel() instanceof ComponentSampleModel) {
+- ComponentSampleModel csm =
+- (ComponentSampleModel)raster.getSampleModel();
+- int rasScanlineStride = csm.getScanlineStride();
+- int rasPixelStride = csm.getPixelStride();
+-
+- int subRasterOffset =
+- (rect.y-raster.getSampleModelTranslateY())*rasScanlineStride+
+- (rect.x-raster.getSampleModelTranslateX())*rasPixelStride;
+-
+- int rasBankIndices[] = csm.getBankIndices();
+- int rasBandOffsets[] = csm.getBandOffsets();
+- int rasDataOffsets[] = raster.getDataBuffer().getOffsets();
+-
+- if (rasDataOffsets.length == 1) {
+- for (int i = 0; i < numBands; i++) {
+- rasBandOffsets[i] += rasDataOffsets[0] +
+- subRasterOffset;
+- }
+- } else if (rasDataOffsets.length == rasBandOffsets.length) {
+- for (int i = 0; i < numBands; i++) {
+- rasBandOffsets[i] += rasDataOffsets[i] +
+- subRasterOffset;
+- }
+- }
+-
+- Object mlibDataArray = null;
+- switch (getDataType()) {
+- case DataBuffer.TYPE_BYTE:
+- byte bArray[][] = new byte[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- bArray[i] = mlimages[0].getByteData();
+- }
+- mlibDataArray = bArray;
+- break;
+- case DataBuffer.TYPE_USHORT:
+- short usArray[][] = new short[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- usArray[i] = mlimages[0].getUShortData();
+- }
+- mlibDataArray = usArray;
+- break;
+- case DataBuffer.TYPE_SHORT:
+- short sArray[][] = new short[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- sArray[i] = mlimages[0].getShortData();
+- }
+- mlibDataArray = sArray;
+- break;
+- case DataBuffer.TYPE_INT:
+- int iArray[][] = new int[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- iArray[i] = mlimages[0].getIntData();
+- }
+- mlibDataArray = iArray;
+- break;
+- case DataBuffer.TYPE_FLOAT:
+- float fArray[][] = new float[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- fArray[i] = mlimages[0].getFloatData();
+- }
+- mlibDataArray = fArray;
+- break;
+- case DataBuffer.TYPE_DOUBLE:
+- double dArray[][] = new double[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- dArray[i] = mlimages[0].getDoubleData();
+- }
+- mlibDataArray = dArray;
+- break;
+- }
+-
+-
+-
+- Object rasDataArray = null;
+- switch (csm.getDataType()) {
+- case DataBuffer.TYPE_BYTE: {
+- DataBufferByte dbb =
+- (DataBufferByte)raster.getDataBuffer();
+- byte rasByteDataArray[][] = new byte[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- rasByteDataArray[i] =
+- dbb.getData(rasBankIndices[i]);
+- }
+- rasDataArray = rasByteDataArray;
+- }
+- break;
+- case DataBuffer.TYPE_USHORT: {
+- DataBufferUShort dbus =
+- (DataBufferUShort)raster.getDataBuffer();
+- short rasUShortDataArray[][] = new short[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- rasUShortDataArray[i] =
+- dbus.getData(rasBankIndices[i]);
+- }
+- rasDataArray = rasUShortDataArray;
+- }
+- break;
+- case DataBuffer.TYPE_SHORT: {
+- DataBufferShort dbs =
+- (DataBufferShort)raster.getDataBuffer();
+- short rasShortDataArray[][] = new short[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- rasShortDataArray[i] =
+- dbs.getData(rasBankIndices[i]);
+- }
+- rasDataArray = rasShortDataArray;
+- }
+- break;
+- case DataBuffer.TYPE_INT: {
+- DataBufferInt dbi =
+- (DataBufferInt)raster.getDataBuffer();
+- int rasIntDataArray[][] = new int[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- rasIntDataArray[i] =
+- dbi.getData(rasBankIndices[i]);
+- }
+- rasDataArray = rasIntDataArray;
+- }
+- break;
+- case DataBuffer.TYPE_FLOAT: {
+- DataBufferFloat dbf =
+- (DataBufferFloat)raster.getDataBuffer();
+- float rasFloatDataArray[][] = new float[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- rasFloatDataArray[i] =
+- dbf.getData(rasBankIndices[i]);
+- }
+- rasDataArray = rasFloatDataArray;
+- }
+- break;
+- case DataBuffer.TYPE_DOUBLE: {
+- DataBufferDouble dbd =
+- (DataBufferDouble)raster.getDataBuffer();
+- double rasDoubleDataArray[][] = new double[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- rasDoubleDataArray[i] =
+- dbd.getData(rasBankIndices[i]);
+- }
+- rasDataArray = rasDoubleDataArray;
+- }
+- break;
+- }
+-
+-
+- // dst = mlib && src = ras
+- Util.Reformat(
+- mlibDataArray,
+- rasDataArray,
+- numBands,
+- rect.width,rect.height,
+- getMediaLibDataType(this.getDataType()),
+- bandOffsets,
+- rect.width*numBands,
+- numBands,
+- getMediaLibDataType(csm.getDataType()),
+- rasBandOffsets,
+- rasScanlineStride,
+- rasPixelStride);
+- } else {
+- // If COPIED and the raster doesn't have ComponentSampleModel
+- // data is moved with getPixel/setPixel (even byte/short)
+- switch (getDataType()) {
+- case DataBuffer.TYPE_INT:
+- raster.getPixels(rect.x,rect.y,
+- rect.width,rect.height,
+- mlimages[0].getIntData());
+- break;
+- case DataBuffer.TYPE_FLOAT:
+- raster.getPixels(rect.x,rect.y,
+- rect.width,rect.height,
+- mlimages[0].getFloatData());
+- break;
+- case DataBuffer.TYPE_DOUBLE:
+- raster.getPixels(rect.x,rect.y,
+- rect.width,rect.height,
+- mlimages[0].getDoubleData());
+- break;
+- }
+- }
+- }
+-
+-
+- /**
+- * Copies data back into the MediaLibAccessor's raster. Note that
+- * the data is casted from the intermediate data format to
+- * the raster's format. If clamping is needed, the call
+- * clampDataArrays() method needs to be called before
+- * calling the copyDataToRaster() method.
+- */
+- public void copyDataToRaster(int[] channelMap) {
+- if (isDataCopy()) {
+-
+- if(isBinary()) {
+- if(areBinaryDataPacked) {
+- ImageUtil.setPackedBinaryData(mlimages[0].getBitData(),
+- (WritableRaster)raster,
+- rect);
+- } else { // unpacked
+- ImageUtil.setUnpackedBinaryData(mlimages[0].getByteData(),
+- (WritableRaster)raster,
+- rect);
+- }
+- return;
+- }
+-
+- // Writeback should only be necessary on destRasters which
+- // should be writable so this cast should succeed.
+- WritableRaster wr = (WritableRaster)raster;
+-
+- if (wr.getSampleModel() instanceof ComponentSampleModel) {
+- ComponentSampleModel csm =
+- (ComponentSampleModel)wr.getSampleModel();
+- int rasScanlineStride = csm.getScanlineStride();
+- int rasPixelStride = csm.getPixelStride();
+-
+- int subRasterOffset =
+- (rect.y-raster.getSampleModelTranslateY())*rasScanlineStride+
+- (rect.x-raster.getSampleModelTranslateX())*rasPixelStride;
+-
+- int rasBankIndices[] = csm.getBankIndices();
+- int rasBandOffsets[] = csm.getBandOffsets();
+- int rasDataOffsets[] = raster.getDataBuffer().getOffsets();
+-
+- if (rasDataOffsets.length == 1) {
+- for (int i = 0; i < numBands; i++) {
+- rasBandOffsets[i] += rasDataOffsets[0] +
+- subRasterOffset;
+- }
+- } else if (rasDataOffsets.length == rasBandOffsets.length) {
+- for (int i = 0; i < numBands; i++) {
+- rasBandOffsets[i] += rasDataOffsets[i] +
+- subRasterOffset;
+- }
+- }
+-
+- Object mlibDataArray = null;
+- switch (getDataType()) {
+- case DataBuffer.TYPE_BYTE:
+- byte bArray[][] = new byte[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- bArray[i] = mlimages[0].getByteData();
+- }
+- mlibDataArray = bArray;
+- break;
+- case DataBuffer.TYPE_USHORT:
+- short usArray[][] = new short[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- usArray[i] = mlimages[0].getUShortData();
+- }
+- mlibDataArray = usArray;
+- break;
+- case DataBuffer.TYPE_SHORT:
+- short sArray[][] = new short[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- sArray[i] = mlimages[0].getShortData();
+- }
+- mlibDataArray = sArray;
+- break;
+- case DataBuffer.TYPE_INT:
+- int iArray[][] = new int[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- iArray[i] = mlimages[0].getIntData();
+- }
+- mlibDataArray = iArray;
+- break;
+- case DataBuffer.TYPE_FLOAT:
+- float fArray[][] = new float[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- fArray[i] = mlimages[0].getFloatData();
+- }
+- mlibDataArray = fArray;
+- break;
+- case DataBuffer.TYPE_DOUBLE:
+- double dArray[][] = new double[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- dArray[i] = mlimages[0].getDoubleData();
+- }
+- mlibDataArray = dArray;
+- break;
+- }
+-
+-
+- byte tmpDataArray[] = null;
+- Object rasDataArray = null;
+- switch (csm.getDataType()) {
+- case DataBuffer.TYPE_BYTE: {
+- DataBufferByte dbb =
+- (DataBufferByte)raster.getDataBuffer();
+- byte rasByteDataArray[][] = new byte[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- rasByteDataArray[i] =
+- dbb.getData(rasBankIndices[i]);
+- }
+- tmpDataArray = rasByteDataArray[0];
+- rasDataArray = rasByteDataArray;
+- }
+- break;
+- case DataBuffer.TYPE_USHORT: {
+- DataBufferUShort dbus =
+- (DataBufferUShort)raster.getDataBuffer();
+- short rasUShortDataArray[][] = new short[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- rasUShortDataArray[i] =
+- dbus.getData(rasBankIndices[i]);
+- }
+- rasDataArray = rasUShortDataArray;
+- }
+- break;
+- case DataBuffer.TYPE_SHORT: {
+- DataBufferShort dbs =
+- (DataBufferShort)raster.getDataBuffer();
+- short rasShortDataArray[][] = new short[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- rasShortDataArray[i] =
+- dbs.getData(rasBankIndices[i]);
+- }
+- rasDataArray = rasShortDataArray;
+- }
+- break;
+- case DataBuffer.TYPE_INT: {
+- DataBufferInt dbi =
+- (DataBufferInt)raster.getDataBuffer();
+- int rasIntDataArray[][] = new int[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- rasIntDataArray[i] =
+- dbi.getData(rasBankIndices[i]);
+- }
+- rasDataArray = rasIntDataArray;
+- }
+- break;
+- case DataBuffer.TYPE_FLOAT: {
+- DataBufferFloat dbf =
+- (DataBufferFloat)raster.getDataBuffer();
+- float rasFloatDataArray[][] = new float[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- rasFloatDataArray[i] =
+- dbf.getData(rasBankIndices[i]);
+- }
+- rasDataArray = rasFloatDataArray;
+- }
+- break;
+- case DataBuffer.TYPE_DOUBLE: {
+- DataBufferDouble dbd =
+- (DataBufferDouble)raster.getDataBuffer();
+- double rasDoubleDataArray[][] = new double[numBands][];
+- for (int i = 0; i < numBands; i++) {
+- rasDoubleDataArray[i] =
+- dbd.getData(rasBankIndices[i]);
+- }
+- rasDataArray = rasDoubleDataArray;
+- }
+- break;
+- }
+-
+- int[] bandOffsetCopy = (int[])bandOffsets.clone();
+- if (channelMap != null) {
+- for (int i = 0; i < bandOffsetCopy.length; i++)
+- bandOffsetCopy[i] = channelMap[bandOffsetCopy[i]];
+- }
+-
+- // src = mlib && dst = ras
+- Util.Reformat(
+- rasDataArray,
+- mlibDataArray,
+- numBands,
+- rect.width,rect.height,
+- getMediaLibDataType(csm.getDataType()),
+- rasBandOffsets,
+- rasScanlineStride,
+- rasPixelStride,
+- getMediaLibDataType(this.getDataType()),
+- bandOffsetCopy,
+- rect.width*numBands,
+- numBands);
+- } else {
+- // If COPIED and the raster doesn't have ComponentSampleModel
+- // data is moved with getPixel/setPixel (even byte/short)
+- switch (getDataType()) {
+- case DataBuffer.TYPE_INT:
+- wr.setPixels(rect.x,rect.y,
+- rect.width,rect.height,
+- mlimages[0].getIntData());
+- break;
+- case DataBuffer.TYPE_FLOAT:
+- wr.setPixels(rect.x,rect.y,
+- rect.width,rect.height,
+- mlimages[0].getFloatData());
+- break;
+- case DataBuffer.TYPE_DOUBLE:
+- wr.setPixels(rect.x,rect.y,
+- rect.width,rect.height,
+- mlimages[0].getDoubleData());
+- break;
+- }
+- }
+- }
+- }
+-
+- /**
+- * Clamps data array values to a range that the underlying raster
+- * can deal with. For example, if the underlying raster stores
+- * data as bytes, but the samples ares unpacked into integer arrays by
+- * the RasterAccessor object for an operation, the operation will
+- * need to call clampDataArrays() so that the data in the int
+- * arrays is restricted to the range 0..255 before a setPixels()
+- * call is made on the underlying raster. Note that some
+- * operations (for example, lookup) can guarantee that their
+- * results don't need clamping so they can call
+- * RasterAccessor.copyDataToRaster() without first calling this
+- * function.
+- */
+- public void clampDataArrays () {
+- if (!isDataCopy()) {
+- return;
+- }
+-
+- // additonal medialib check: If it's a componentSampleModel
+- // we get a free cast when we call medialibWrapper.Reformat
+- // to copy the data to the source. So we don't need to cast
+- // here.
+- if (raster.getSampleModel() instanceof ComponentSampleModel) {
+- return;
+- }
+-
+- int bits[] = raster.getSampleModel().getSampleSize();
+-
+- // Do we even need a clamp? We do if there's any band
+- // of the source image stored in that's less than 32 bits
+- // and is stored in a byte, short or int format. (The automatic
+- // cast's between floats/doubles and 32-bit ints in setPixel()
+- // generall do what we want.)
+-
+- boolean needClamp = false;
+- boolean uniformBitSize = true;
+- for (int i = 0; i < bits.length; i++) {
+- int bitSize = bits[0];
+- if (bits[i] < 32) {
+- needClamp = true;
+- }
+- if (bits[i] != bitSize) {
+- uniformBitSize = false;
+- }
+- }
+-
+- if (!needClamp) {
+- return;
+- }
+-
+- int dataType = raster.getDataBuffer().getDataType();
+- double hiVals[] = new double[bits.length];
+- double loVals[] = new double[bits.length];
+-
+- if (dataType == DataBuffer.TYPE_USHORT &&
+- uniformBitSize && bits[0] == 16) {
+- for (int i = 0; i < bits.length; i++) {
+- hiVals[i] = (double)0xFFFF;
+- loVals[i] = (double)0;
+- }
+- } else if (dataType == DataBuffer.TYPE_SHORT &&
+- uniformBitSize && bits[0] == 16) {
+- for (int i = 0; i < bits.length; i++) {
+- hiVals[i] = (double)Short.MAX_VALUE;
+- loVals[i] = (double)Short.MIN_VALUE;
+- }
+- } else if (dataType == DataBuffer.TYPE_INT &&
+- uniformBitSize && bits[0] == 32) {
+- for (int i = 0; i < bits.length; i++) {
+- hiVals[i] = (double)Integer.MAX_VALUE;
+- loVals[i] = (double)Integer.MIN_VALUE;
+- }
+- } else {
+- for (int i = 0; i < bits.length; i++) {
+- hiVals[i] = (double)((1 << bits[i]) - 1);
+- loVals[i] = (double)0;
+- }
+- }
+- clampDataArray(hiVals,loVals);
+- }
+-
+- private void clampDataArray(double hiVals[], double loVals[]) {
+- switch (getDataType()) {
+- case DataBuffer.TYPE_INT:
+- clampIntArrays(toIntArray(hiVals),toIntArray(loVals));
+- break;
+- case DataBuffer.TYPE_FLOAT:
+- clampFloatArrays(toFloatArray(hiVals),toFloatArray(loVals));
+- break;
+- case DataBuffer.TYPE_DOUBLE:
+- clampDoubleArrays(hiVals,loVals);
+- break;
+- }
+- }
+-
+- private int[] toIntArray(double vals[]) {
+- int returnVals[] = new int[vals.length];
+- for (int i = 0; i < vals.length; i++) {
+- returnVals[i] = (int)vals[i];
+- }
+- return returnVals;
+- }
+-
+- private float[] toFloatArray(double vals[]) {
+- float returnVals[] = new float[vals.length];
+- for (int i = 0; i < vals.length; i++) {
+- returnVals[i] = (float)vals[i];
+- }
+- return returnVals;
+- }
+-
+- private void clampIntArrays(int hiVals[], int loVals[]) {
+- int width = rect.width;
+- int height = rect.height;
+- int scanlineStride = numBands*width;
+- for (int k = 0; k < numBands; k++) {
+- int data[] = mlimages[0].getIntData();
+- int scanlineOffset = k;
+- int hiVal = hiVals[k];
+- int loVal = loVals[k];
+- for (int j = 0; j < height; j++) {
+- int pixelOffset = scanlineOffset;
+- for (int i = 0; i < width; i++) {
+- int tmp = data[pixelOffset];
+- if (tmp < loVal) {
+- data[pixelOffset] = loVal;
+- } else if (tmp > hiVal) {
+- data[pixelOffset] = hiVal;
+- }
+- pixelOffset += numBands;
+- }
+- scanlineOffset += scanlineStride;
+- }
+- }
+- }
+-
+- private void clampFloatArrays(float hiVals[], float loVals[]) {
+- int width = rect.width;
+- int height = rect.height;
+- int scanlineStride = numBands*width;
+- for (int k = 0; k < numBands; k++) {
+- float data[] = mlimages[0].getFloatData();
+- int scanlineOffset = k;
+- float hiVal = hiVals[k];
+- float loVal = loVals[k];
+- for (int j = 0; j < height; j++) {
+- int pixelOffset = scanlineOffset;
+- for (int i = 0; i < width; i++) {
+- float tmp = data[pixelOffset];
+- if (tmp < loVal) {
+- data[pixelOffset] = loVal;
+- } else if (tmp > hiVal) {
+- data[pixelOffset] = hiVal;
+- }
+- pixelOffset += numBands;
+- }
+- scanlineOffset += scanlineStride;
+- }
+- }
+- }
+-
+- private void clampDoubleArrays(double hiVals[], double loVals[]) {
+- int width = rect.width;
+- int height = rect.height;
+- int scanlineStride = numBands*width;
+- for (int k = 0; k < numBands; k++) {
+- double data[] = mlimages[0].getDoubleData();
+- int scanlineOffset = k;
+- double hiVal = hiVals[k];
+- double loVal = loVals[k];
+- for (int j = 0; j < height; j++) {
+- int pixelOffset = scanlineOffset;
+- for (int i = 0; i < width; i++) {
+- double tmp = data[pixelOffset];
+- if (tmp < loVal) {
+- data[pixelOffset] = loVal;
+- } else if (tmp > hiVal) {
+- data[pixelOffset] = hiVal;
+- }
+- pixelOffset += numBands;
+- }
+- scanlineOffset += scanlineStride;
+- }
+- }
+- }
+-
+-}
+-
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/PaletteBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/PaletteBox.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/PaletteBox.java 2005-02-11 00:01:36.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/PaletteBox.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,267 +0,0 @@
+-/*
+- * $RCSfile: PaletteBox.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:36 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.awt.image.IndexColorModel;
+-import javax.imageio.metadata.IIOInvalidTreeException;
+-import javax.imageio.metadata.IIOMetadataNode;
+-import org.w3c.dom.Node;
+-import org.w3c.dom.NodeList;
+-
+-import com.sun.media.imageioimpl.common.ImageUtil;
+-
+-/** This class is designed to represent a palette box for JPEG 2000 JP2 file
+- * format. A palette box has a length, and a fixed type of "pclr".
+- *
+- * Its content contains the number of palette entry, the number of color
+- * components, the bit depths of the output components, the LUT.
+- *
+- * Currently, only 8-bit color index is supported.
+- */
+-public class PaletteBox extends Box {
+- /** The value of the data elements.
+- */
+- private int numEntries;
+- private int numComps;
+- private byte[] bitDepth;
+- private byte[][] lut;
+-
+- /** Compute the length of this box. */
+- private static int computeLength(IndexColorModel icm) {
+- int size = icm.getMapSize();
+- int[] comp = icm.getComponentSize();
+- return 11 + comp.length + size * comp.length;
+- }
+-
+- /** Gets the size of the components or the bit depth for all the color
+- * coomponents.
+- */
+- private static byte[] getCompSize(IndexColorModel icm) {
+- int[] comp = icm.getComponentSize();
+- int size = comp.length;
+- byte[] buf = new byte[size];
+- for (int i = 0; i < size; i++)
+- buf[i] = (byte)(comp[i] - 1);
+- return buf;
+- }
+-
+- /** Gets the LUT from the IndexColorModel
as an two-dimensional
+- * byte array.
+- */
+- private static byte[][] getLUT(IndexColorModel icm) {
+- int[] comp = icm.getComponentSize();
+- int size = icm.getMapSize();
+- byte[][] lut = new byte[comp.length][size];
+- icm.getReds(lut[0]);
+- icm.getGreens(lut[1]);
+- icm.getBlues(lut[2]);
+- if (comp.length == 4)
+- icm.getAlphas(lut[3]);
+- return lut;
+- }
+-
+- /** Constructs a PlatteBox
from an
+- * IndexColorModel
.
+- */
+- public PaletteBox(IndexColorModel icm) {
+- this(computeLength(icm), getCompSize(icm), getLUT(icm));
+- }
+-
+- /** Constructs a PlatteBox
from an
+- * org.w3c.dom.Node
.
+- */
+- public PaletteBox(Node node) throws IIOInvalidTreeException {
+- super(node);
+- byte[][] tlut = null;
+- int index = 0;
+-
+- NodeList children = node.getChildNodes();
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+- String name = child.getNodeName();
+-
+- if ("NumberEntries".equals(name)) {
+- numEntries = Box.getIntElementValue(child);
+- }
+-
+- if ("NumberColors".equals(name)) {
+- numComps = Box.getIntElementValue(child);
+- }
+-
+- if ("BitDepth".equals(name)) {
+- bitDepth = Box.getByteArrayElementValue(child);
+- }
+-
+- if ("LUT".equals(name)) {
+- tlut = new byte[numEntries][];
+-
+- NodeList children1 = child.getChildNodes();
+-
+- for (int j = 0; j PlatteBox
from the provided byte array.
+- */
+- public PaletteBox(byte[] data) {
+- super(8 + data.length, 0x70636C72, data);
+- }
+-
+- /** Return the number of palette entries. */
+- public int getNumEntries() {
+- return numEntries;
+- }
+-
+- /** Return the number of color components. */
+- public int getNumComp() {
+- return numComps;
+- }
+-
+- /** Return the bit depths for all the color components. */
+- public byte[] getBitDepths() {
+- return bitDepth;
+- }
+-
+- /** Return the LUT. */
+- public byte[][] getLUT() {
+- return lut;
+- }
+-
+- /** creates an IIOMetadataNode
from this palette box.
+- * The format of this node is defined in the XML dtd and xsd
+- * for the JP2 image file.
+- */
+- public IIOMetadataNode getNativeNode() {
+- IIOMetadataNode node = new IIOMetadataNode(Box.getName(getType()));
+- setDefaultAttributes(node);
+-
+- IIOMetadataNode child = new IIOMetadataNode("NumberEntries");
+- child.setUserObject(new Integer(numEntries));
+- child.setNodeValue("" + numEntries);
+- node.appendChild(child);
+-
+- child = new IIOMetadataNode("NumberColors");
+- child.setUserObject(new Integer(numComps));
+- child.setNodeValue("" + numComps);
+- node.appendChild(child);
+-
+- child = new IIOMetadataNode("BitDepth");
+- child.setUserObject(bitDepth);
+- child.setNodeValue(ImageUtil.convertObjectToString(bitDepth));
+- node.appendChild(child);
+-
+- child = new IIOMetadataNode("LUT");
+- for (int i = 0; i < numEntries; i++) {
+- IIOMetadataNode child1 = new IIOMetadataNode("LUTRow");
+- byte[] row = new byte[numComps];
+- for (int j = 0; j < numComps; j++)
+- row[j] = lut[j][i];
+-
+- child1.setUserObject(row);
+- child1.setNodeValue(ImageUtil.convertObjectToString(row));
+- child.appendChild(child1);
+- }
+- node.appendChild(child);
+-
+- return node;
+- }
+-
+- protected void parse(byte[] data) {
+- if (data == null)
+- return;
+- numEntries = (short)(((data[0] & 0xFF) << 8) | (data[1] & 0xFF));
+-
+- numComps = data[2];
+- bitDepth = new byte[numComps];
+- System.arraycopy(data, 3, bitDepth, 0, numComps);
+-
+- lut = new byte[numComps][numEntries];
+- for (int i = 0, k = 3 + numComps; i < numEntries; i++)
+- for (int j = 0; j < numComps; j++)
+- lut[j][i] = data[k++];
+- }
+-
+- protected void compose() {
+- if (data != null)
+- return;
+- data = new byte[3 + numComps + numEntries * numComps];
+- data[0] = (byte)(numEntries >> 8);
+- data[1] = (byte)(numEntries & 0xFF);
+-
+- data[2] = (byte)numComps;
+- System.arraycopy(bitDepth, 0, data, 3, numComps);
+-
+- for (int i = 0, k = 3 + numComps; i < numEntries; i++)
+- for (int j = 0; j < numComps; j++)
+- data[k++] = lut[j][i];
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/properties zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/properties
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/properties 2005-02-11 00:01:38.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/properties 1969-12-31 19:00:00.000000000 -0500
+@@ -1,59 +0,0 @@
+-#
+-# $RCSfile: properties,v $
+-#
+-# Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
+-#
+-# Use is subject to license terms.
+-#
+-# $Revision: 1.1 $
+-# $Date: 2005/02/11 05:01:38 $
+-# $State: Exp $
+-#
+-# Internationalization file for com.sun.media.imageioimpl.plugins.jpeg2000
+-
+-Box0=A simple box should have a static methos getElementNames.
+-Box1=Length should be 1 when set extra length.
+-Box2=Content length should be length - 8 or extraLength - 16.
+-J2KImageReader0=The source region is null.
+-J2KImageReader1=The destination region is null.
+-J2KImageReader2=The destination region is empty.
+-J2KImageReader3=The destination or source region is empty.
+-J2KImageReader4=Only support to decode the first image in JP2 stream.
+-J2KImageReader5=The provided ImageReadParam isn't a J2KImageReadParam.
+-J2KImageReader6=The input source has not been set.
+-J2KImageReader7=seekForwardOnly == true!
+-J2KImageWriteParamJava0=Packet per tile part cannot be negative.
+-J2KImageWriter0=The provided output is not an ImageOutputStream.
+-J2KImageWriter1=Packet headers cannot be in both main and tile headers.
+-J2KImageWriter2=Cannot set lossless and encoding rate at the same time.
+-J2KImageWriter3=The image origin coordinates should not be negative.
+-J2KImageWriter4=Invalid tile grid settings.
+-J2KImageWriter5=Only byte/short/ushort/int types are supported.
+-J2KImageWriter6=Only up to 16384 bands are supported.
+-J2KImageWriter7=output == null!
+-J2KImageWriter8=image == null!
+-J2KImageWriterMedialib0=The source region is empty.
+-J2KImageWriterMedialib1=output == null!
+-J2KImageWriterMedialib2=image == null!
+-J2KMetadata0=The provided metadata format is null.
+-J2KMetadata1=The provided metadata format isn't recognized.
+-J2KMetadata2=The tree to be merged is null.
+-J2KMetadata3=Invalid node
+-J2KMetadata4=Input node should be ColorSpaceType.
+-J2KMetadata5=Input node should be Palette.
+-J2KMetadata6=Input node should be Data.
+-J2KMetadata7=Input node should be Dimension.
+-J2KMetadata8=Input node should be Transparency.
+-J2KReadState0=Null ImageInputStream/ImageReadParam/Metadata is provided.
+-J2KReadState1=The provided tile grid position is out of range.
+-J2KReadState2=Codestream too short or bad header.
+-J2KReadState3=Error while reading bit stream header or parsing packets
+-J2KReadState4=Could not instantiate bit stream reader
+-J2KReadState5=Could not instantiate entropy decoder
+-J2KReadState6=Could not instantiate roi de-scaler
+-J2KReadState7=Could not instantiate dequantizer
+-J2KReadState8=Could not instantiate inverse wavelet transform
+-J2KReadState9=An error has occured during decoding.
+-J2KReadState10=An uncaught runtime exception has occurred
+-J2KReadState11=Cannot supported for this depth :
+-J2KReadState12=Cannot decode a code stream with different component subsample rates.
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/RenderedImageSrc.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/RenderedImageSrc.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/RenderedImageSrc.java 2006-09-22 19:07:25.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/RenderedImageSrc.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,1035 +0,0 @@
+-/*
+- * $RCSfile: RenderedImageSrc.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.2 $
+- * $Date: 2006/09/22 23:07:25 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import java.awt.Point;
+-import java.awt.Rectangle;
+-import java.awt.RenderingHints;
+-import java.awt.image.ColorModel;
+-import java.awt.image.ComponentSampleModel;
+-import java.awt.image.DataBuffer;
+-import java.awt.image.DataBufferByte;
+-import java.awt.image.RenderedImage;
+-import java.awt.image.Raster;
+-import java.awt.image.MultiPixelPackedSampleModel;
+-import java.awt.image.SampleModel;
+-import java.awt.image.WritableRaster;
+-import java.awt.image.renderable.ParameterBlock;
+-
+-import jj2000.j2k.image.*;
+-import jj2000.j2k.*;
+-import java.io.*;
+-
+-import com.sun.media.imageioimpl.common.ImageUtil;
+-
+-public class RenderedImageSrc implements BlkImgDataSrc {
+- /** The width of the image */
+- private int w;
+-
+- /** The height of the image */
+- private int h;
+-
+- /** The tile width for encoding */
+- int tileWidth;
+-
+- /** The tile height for encoding */
+- int tileHeight;
+-
+- /** The tile grid offset for encoding */
+- int tileXOffset, tileYOffset;
+-
+- /** The source -> destination transformation */
+- int scaleX, scaleY, xOffset, yOffset;
+-
+- /** The source bands to be encoded. */
+- int[] sourceBands = null;
+-
+- /** The destination upper-left corner */
+- int minX, minY;
+-
+- /** The number of components in the image */
+- private int nc;
+-
+- /** The number of bits that determine the nominal dynamic range */
+- // XXX: Should be an int[] of length 'nc'.
+- private int rb;
+-
+- /** Buffer for the 3 components of each pixel(in the current block) */
+- private int[][] barr = null;
+-
+- /** Data block used only to store coordinates of the buffered blocks */
+- private DataBlkInt dbi = new DataBlkInt();
+-
+- /** The line buffer. */
+- private byte buf[];
+-
+- /** Temporary DataBlkInt object (needed when encoder uses floating-point
+- filters). This avoid allocating new DataBlk at each time */
+- private DataBlkInt intBlk;
+-
+- private RenderedImage src;
+- private J2KImageWriteParamJava param;
+-
+- /** The input source raster. */
+- private Raster raster;
+-
+- /** The raster for a destination tile */
+- private Raster aTile;
+-
+- private Point co = new Point();
+-
+- private int dcOffset = 0;
+-
+- private boolean isBinary = false;
+-
+- private Rectangle destinationRegion;
+- private Rectangle sourceRegion;
+-
+- private ColorModel cm;
+- private SampleModel sm;
+-
+- private boolean noTransform = true;
+- private boolean noSubband = true;
+-
+- /** Used to process abortion. */
+- private J2KImageWriter writer;
+-
+- /** Indicates a raster
rather than a RenderedImage
+- * to be encoded.
+- */
+- private boolean inputIsRaster = false;
+-
+- /**
+- * Creates RenderedImageSrc
for encoding a Raster
.
+- *
+- * @param raster The Raster
to be encoded.
+- * @param param The J2KImageWriteParamJava
used in encoding.
+- * @param writer The J2KImageWriter
performs the encoding.
+- *
+- * @param IOException If an error occurs while opening the file.
+- */
+- public RenderedImageSrc(Raster raster,
+- J2KImageWriteParamJava param,
+- J2KImageWriter writer) {
+- this.raster = raster;
+- this.param = param;
+- this.writer = writer;
+- this.inputIsRaster = true;
+-
+- sourceRegion = param.getSourceRegion();
+-
+- if (sourceRegion == null)
+- sourceRegion = new Rectangle(raster.getMinX(), raster.getMinY(),
+- raster.getWidth(), raster.getHeight());
+- else
+- sourceRegion = sourceRegion.intersection(raster.getBounds());
+-
+- if (sourceRegion.isEmpty())
+- throw new RuntimeException(I18N.getString("J2KImageWriterCodecLib0"));
+-
+- sm = raster.getSampleModel();
+- getFromParam();
+- setSampleModelAndMore();
+- setTile(0, 0);
+- }
+-
+- /**
+- * Creates RenderedImageSrc
for encoding a
+- * RenderedImage
.
+- *
+- * @param src The RenderedImage
to be encoded.
+- * @param param The J2KImageWriteParamJava
used in encoding.
+- * @param writer The J2KImageWriter
performs the encoding.
+- *
+- * @param IOException If an error occurs while opening the file.
+- * */
+- public RenderedImageSrc(RenderedImage src,
+- J2KImageWriteParamJava param,
+- J2KImageWriter writer) {
+- this.src = src;
+- this.param = param;
+- this.writer = writer;
+-
+- sourceRegion = param.getSourceRegion();
+-
+- if (sourceRegion == null)
+- sourceRegion = new Rectangle(src.getMinX(), src.getMinY(),
+- src.getWidth(), src.getHeight());
+- else
+- sourceRegion = sourceRegion.intersection(new Rectangle(src.getMinX(),
+- src.getMinY(),
+- src.getWidth(),
+- src.getHeight()));
+- if (sourceRegion.isEmpty())
+- throw new RuntimeException(I18N.getString("J2KImageWriterCodecLib0"));
+-
+- sm = src.getSampleModel();
+- cm = src.getColorModel();
+- getFromParam();
+- setSampleModelAndMore();
+- }
+-
+- private void getFromParam() {
+- try {
+- tileWidth = param.getTileWidth();
+- tileHeight = param.getTileHeight();
+- tileXOffset = param.getTileGridXOffset();
+- tileYOffset = param.getTileGridYOffset();
+- } catch(IllegalStateException e) {
+- param.setTilingMode(param.MODE_EXPLICIT);
+- if (inputIsRaster) {
+- param.setTiling(raster.getWidth(), raster.getHeight(),
+- raster.getMinX(), raster.getMinY());
+- } else {
+- param.setTiling(src.getWidth(), src.getHeight(),
+- src.getMinX(), src.getMinY());
+- }
+- tileWidth = param.getTileWidth();
+- tileHeight = param.getTileHeight();
+- tileXOffset = param.getTileGridXOffset();
+- tileYOffset = param.getTileGridYOffset();
+- }
+-
+- scaleX = param.getSourceXSubsampling();
+- scaleY = param.getSourceYSubsampling();
+- xOffset = param.getSubsamplingXOffset();
+- yOffset = param.getSubsamplingYOffset();
+-
+- sourceRegion.translate(xOffset, yOffset);
+- sourceRegion.width -= xOffset;
+- sourceRegion.height -= yOffset;
+-
+- xOffset = sourceRegion.x % scaleX;
+- yOffset = sourceRegion.y % scaleY;
+-
+- minX = sourceRegion.x / scaleX;
+- minY = sourceRegion.y / scaleY;
+-
+- w = (sourceRegion.width + scaleX - 1) / scaleX;
+- h = (sourceRegion.height + scaleY - 1) / scaleY;
+-
+- tileXOffset += (minX - tileXOffset)/tileWidth * tileWidth;
+- tileYOffset += (minY - tileYOffset)/tileHeight * tileHeight;
+-
+- destinationRegion = new Rectangle(minX, minY, w, h);
+-
+- if (!destinationRegion.equals(sourceRegion) ||
+- tileWidth != sm.getWidth() ||
+- tileHeight != sm.getHeight() ||
+- (!inputIsRaster &&
+- (tileXOffset != src.getTileGridXOffset() ||
+- tileYOffset != src.getTileGridYOffset())) ||
+- (inputIsRaster &&
+- (tileXOffset != raster.getMinX() ||
+- tileYOffset != raster.getMinY())))
+- noTransform = false;
+-
+- }
+-
+- private void setSampleModelAndMore() {
+- nc = sm.getNumBands();
+- sourceBands = param.getSourceBands();
+- if (sourceBands != null) {
+- sm = sm.createSubsetSampleModel(sourceBands);
+- noSubband = false;
+- } else {
+- sourceBands = new int[nc];
+- for (int i = 0; i < nc; i++)
+- sourceBands[i] = i;
+- }
+-
+- sm = sm.createCompatibleSampleModel(tileWidth, tileHeight);
+- nc = sm.getNumBands();
+- isBinary = ImageUtil.isBinary(sm);
+-
+- if(cm != null) {
+- // XXX: rb should be set to getComponentSize();
+- rb = cm.getComponentSize(0);
+- for (int i = 1; i < cm.getNumComponents(); i++)
+- if (rb < cm.getComponentSize(i))
+- rb = cm.getComponentSize(i);
+- } else {
+- // XXX: rb should be set to getSampleSize();
+- rb = sm.getSampleSize(0);
+- for (int i = 1; i < sm.getNumBands(); i++)
+- if (rb < sm.getSampleSize(i))
+- rb = sm.getSampleSize(i);
+- }
+-
+- if (!isOrigSigned(0) && rb > 1)
+- // XXX: if rb is an int[] this will have to change.
+- dcOffset = 1 << rb - 1;
+- }
+-
+-
+- public int getTilePartULX() {
+- return tileXOffset;
+- }
+-
+- public int getTilePartULY() {
+- return tileYOffset;
+- }
+-
+- /**
+- * Returns the width of the current tile in pixels.
+- *
+- * @return The total image width in pixels.
+- * */
+- public int getTileWidth() {
+- int width = tileWidth;
+- int maxX = getImgULX() + getImgWidth();
+- int x = co.x * tileWidth + tileXOffset;
+- if (x + tileWidth >= maxX)
+- width = maxX - x;
+- return width;
+- }
+-
+- /**
+- * Returns the overall height of the current tile in pixels.
+- *
+- * @return The total image height in pixels. */
+- public int getTileHeight() {
+- int height = tileHeight;
+- int maxY = getImgULY() + getImgHeight();
+- int y = co.y * tileHeight + tileYOffset;
+- if (y + tileHeight >= maxY)
+- height = maxY - y;
+-
+- return height;
+- }
+-
+- public int getNomTileWidth() {
+- return tileWidth;
+- }
+-
+- public int getNomTileHeight() {
+- return tileHeight;
+- }
+-
+- /**
+- * Returns the overall width of the image in pixels. This is the image's
+- * width without accounting for any component subsampling or tiling. The
+- * value of w is returned.
+- *
+- * @return The total image's width in pixels.
+- * */
+- public int getImgWidth() {
+- return w;
+- }
+-
+- /**
+- * Returns the overall height of the image in pixels. This is the image's
+- * height without accounting for any component subsampling or tiling. The
+- * value of h is returned.
+- *
+- * @return The total image's height in pixels.
+- * */
+- public int getImgHeight() {
+- return h;
+- }
+-
+- /**
+- * Returns the number of components in the image. The value of nc
+- * is returned.
+- *
+- * @return The number of components in the image.
+- * */
+- public int getNumComps() {
+- return nc;
+- }
+-
+- public int getTileGridXOffset() {
+- return param.getTileGridXOffset();
+- }
+-
+- public int getTileGridYOffset() {
+- return param.getTileGridYOffset();
+- }
+-
+- public int getTileCompHeight(int t, int c) {
+- return tileHeight;
+- }
+-
+- public int getTileCompWidth(int t, int c) {
+- return tileWidth;
+- }
+-
+- /**
+- * Returns the component subsampling factor in the horizontal direction,
+- * for the specified component. This is, approximately, the ratio of
+- * dimensions between the reference grid and the component itself, see the
+- * 'ImgData' interface desription for details.
+- *
+- * @param c The index of the component (between 0 and C-1)
+- *
+- * @return The horizontal subsampling factor of component 'c'
+- *
+- * @see ImgData
+- * */
+- public int getCompSubsX(int c) {
+- return 1;
+- }
+-
+- /**
+- * Returns the component subsampling factor in the vertical direction, for
+- * the specified component. This is, approximately, the ratio of
+- * dimensions between the reference grid and the component itself, see the
+- * 'ImgData' interface desription for details.
+- *
+- * @param c The index of the component (between 0 and C-1)
+- *
+- * @return The vertical subsampling factor of component 'c'
+- *
+- * @see ImgData
+- * */
+- public int getCompSubsY(int c) {
+- return 1;
+- }
+-
+- /**
+- * Returns the width in pixels of the specified component in the current
+- * tile. This default implementation assumes no tiling and no component
+- * subsampling (i.e., all components, or components, have the same
+- * dimensions in pixels).
+- *
+- * @param c The index of the component, from 0 to C-1.
+- *
+- * @return The width in pixels of component n in the current
+- * tile.
+- * */
+- public int getCompWidth(int n) {
+- return w;
+- }
+-
+- /**
+- * Returns the height in pixels of the specified component in the current
+- * tile. This default implementation assumes no tiling and no component
+- * subsampling (i.e., all components, or components, have the same
+- * dimensions in pixels).
+- *
+- * @param c The index of the component, from 0 to C-1.
+- *
+- * @return The height in pixels of component c in the current
+- * tile.
+- * */
+- public int getCompHeight(int c) {
+- return h;
+- }
+-
+- /**
+- * Returns the width in pixels of the specified component in the overall
+- * image. This default implementation assumes no component, or component,
+- * subsampling (i.e. all components have the same dimensions in pixels).
+- *
+- * @param c The index of the component, from 0 to C-1.
+- *
+- * @return The width in pixels of component c in the overall
+- * image.
+- * */
+- public int getCompImgWidth(int c) {
+- return w;
+- }
+-
+- /**
+- * Returns the height in pixels of the specified component in the overall
+- * image. This default implementation assumes no component, or component,
+- * subsampling (i.e. all components have the same dimensions in pixels).
+- *
+- * @param c The index of the component, from 0 to C-1.
+- *
+- * @return The height in pixels of component c in the overall
+- * image.
+- * */
+- public int getCompImgHeight(int c) {
+- return h;
+- }
+-
+- /**
+- * Changes the current tile, given the new coordinates.
+- *
+- * @param x The horizontal coordinate of the tile.
+- *
+- * @param y The vertical coordinate of the new tile.
+- * */
+- public void setTile(int x, int y) {
+- if (x >= getNumXTiles()) {
+- y += x/ getNumXTiles();
+- x = x % getNumXTiles();
+- }
+- co.x = x;
+- co.y = y;
+- aTile = null;
+- }
+-
+- /**
+- * Advances to the next tile, in standard scan-line order (by rows then
+- * columns).
+- * */
+- public void nextTile() {
+- co.x++;
+- if (co.x >= getNumXTiles()) {
+- co.x = 0;
+- co.y++;
+- }
+- setTile(co.x, co.y);
+- }
+-
+- /**
+- * Returns the coordinates of the current tile. This default
+- * implementation assumes no-tiling, so (0,0) is returned.
+- *
+- * @param co If not null this object is used to return the information. If
+- * null a new one is created and returned.
+- *
+- * @return The current tile's coordinates.
+- * */
+- public Point getTile(Point co) {
+- if (co != null)
+- return co;
+- else
+- return new Point(0, 0);
+- }
+-
+- /**
+- * Returns the index of the current tile, relative to a standard scan-line
+- * order.
+- *
+- * @return The current tile's index (starts at 0).
+- * */
+- public int getTileIdx() {
+- return getNumXTiles() * co.y + co.x;
+- }
+-
+- /**
+- * Returns the horizontal and vertical offset of the upper-left corner of
+- * the current tile, in the specified component, relative to the canvas
+- * origin, in the component coordinates (not in the reference grid
+- * coordinates). These are the coordinates of the current tile's (not
+- * active tile) upper-left corner relative to the canvas.
+- *
+- * @param co If not null the object is used to return the values, if null
+- * a new one is created and returned.
+- *
+- * @param c The index of the component (between 0 and C-1)
+- *
+- * @return The horizontal and vertical offsets of the upper-left corner of
+- * the current tile, for the specified component, relative to the canvas
+- * origin, in the component coordinates.
+- * */
+- public Point getTileOff(Point p, int c) {
+- if (p != null) {
+- p.x = co.x * tileWidth + tileXOffset;
+- p.y = co.y * tileHeight + tileYOffset;
+- return co;
+- } else
+- return new Point(co.x * tileWidth + tileXOffset,
+- co.y * tileHeight + tileYOffset);
+- }
+-
+- /**
+- * Returns the horizontal coordinate of the upper-left corner of the
+- * active tile, with respect to the canvas origin, in the component
+- * coordinates, for the specified component.
+- *
+- * @param c The index of the component (between 0 and C-1)
+- *
+- * @return The horizontal coordinate of the upper-left corner of the
+- * active tile, with respect to the canvas origin, for component 'c', in
+- * the component coordinates.
+- * */
+- public int getCompULX(int c) {
+- return raster.getMinX();
+- }
+-
+- /**
+- * Returns the vertical coordinate of the upper-left corner of the active
+- * tile, with respect to the canvas origin, in the component coordinates,
+- * for the specified component.
+- *
+- * @param c The index of the component (between 0 and C-1)
+- *
+- * @return The vertical coordinate of the upper-left corner of the active
+- * tile, with respect to the canvas origin, for component 'c', in the
+- * component coordinates.
+- * */
+- public int getCompULY(int c) {
+- return raster.getMinY();
+- }
+-
+- /**
+- * Returns the horizontal coordinate of the image origin, the top-left
+- * corner, in the canvas system, on the reference grid.
+- *
+- * @return The horizontal coordinate of the image origin in the canvas
+- * system, on the reference grid.
+- * */
+- public int getImgULX() {
+- return destinationRegion.x;
+- }
+-
+- /**
+- * Returns the vertical coordinate of the image origin, the top-left
+- * corner, in the canvas system, on the reference grid.
+- *
+- * @return The vertical coordinate of the image origin in the canvas
+- * system, on the reference grid.
+- * */
+- public int getImgULY() {
+- return destinationRegion.y;
+- }
+-
+- /**
+- * Returns the number of tiles in the horizontal and vertical
+- * directions.
+- *
+- * @param co If not null this object is used to return the information. If
+- * null a new one is created and returned.
+- *
+- * @return The number of tiles in the horizontal (Point.x) and vertical
+- * (Point.y) directions.
+- * */
+- public Point getNumTiles(Point co) {
+- if (co != null) {
+- co.x = getNumXTiles();
+- co.y = getNumYTiles();
+- return co;
+- }
+- else {
+- return new Point(getNumXTiles(), getNumYTiles());
+- }
+- }
+-
+- /**
+- * Returns the total number of tiles in the image. This default
+- * implementation assumes no tiling, so 1 is always returned.
+- *
+- * @return The total number of tiles in the image.
+- * */
+- public int getNumTiles() {
+- return getNumXTiles() * getNumYTiles();
+- }
+-
+- /**
+- * Returns the number of bits corresponding to the nominal range of the
+- * data in the specified component. This is the value rb (range bits) that
+- * was specified in the constructor, which normally is 8 for non bilevel
+- * data, and 1 for bilevel data.
+- *
+- * If this number is b then the nominal range is between +- * -2^(b-1) and 2^(b-1)-1, since unsigned data is level shifted to have a +- * nominal avergae of 0. +- * +- * @param c The index of the component. +- * +- * @return The number of bits corresponding to the nominal range of the +- * data. For floating-point data this value is not applicable and the +- * return value is undefined. +- * */ +- public int getNomRangeBits(int c) { +- // Check component index +- // XXX: Should be component-dependent. +- return rb; +- } +- +- /** +- * Returns the position of the fixed point in the specified component +- * (i.e. the number of fractional bits), which is always 0 for this +- * ImgReader. +- * +- * @param c The index of the component. +- * +- * @return The position of the fixed-point (i.e. the number of fractional +- * bits). Always 0 for this ImgReader. +- * */ +- public int getFixedPoint(int c) { +- // Check component index +- return 0; +- } +- +- +- /** +- * Returns, in the blk argument, the block of image data containing the +- * specifed rectangular area, in the specified component. The data is +- * returned, as a reference to the internal data, if any, instead of as a +- * copy, therefore the returned data should not be modified. +- * +- *
After being read the coefficients are level shifted by subtracting +- * 2^(nominal bit range - 1) +- * +- *
The rectangular area to return is specified by the 'ulx', 'uly', 'w' +- * and 'h' members of the 'blk' argument, relative to the current +- * tile. These members are not modified by this method. The 'offset' and +- * 'scanw' of the returned data can be arbitrary. See the 'DataBlk' class. +- * +- *
If the data array in blk is null, then a new one +- * is created if necessary. The implementation of this interface may +- * choose to return the same array or a new one, depending on what is more +- * efficient. Therefore, the data array in blk prior to the +- * method call should not be considered to contain the returned data, a +- * new array may have been created. Instead, get the array from +- * blk after the method has returned. +- * +- *
The returned data always has its 'progressive' attribute unset +- * (i.e. false). +- * +- *
When an I/O exception is encountered the JJ2KExceptionHandler is +- * used. The exception is passed to its handleException method. The action +- * that is taken depends on the action that has been registered in +- * JJ2KExceptionHandler. See JJ2KExceptionHandler for details. +- * +- *
This method implements buffering for the 3 components: When the +- * first one is asked, all the 3 components are read and stored until they +- * are needed. +- * +- * @param blk Its coordinates and dimensions specify the area to +- * return. Some fields in this object are modified to return the data. +- * +- * @param c The index of the component from which to get the data. Only 0, +- * 1 and 3 are valid. +- * +- * @return The requested DataBlk +- * +- * @see #getCompData +- * +- * @see JJ2KExceptionHandler +- */ +- public final DataBlk getInternCompData(DataBlk blk, int c) { +- if (writer != null && writer.getAbortRequest()) +- throw new RuntimeException(J2KImageWriter.WRITE_ABORTED); +- +- if (barr == null) +- barr = new int[nc][]; +- +- // Check type of block provided as an argument +- if(blk.getDataType()!=DataBlk.TYPE_INT){ +- if(intBlk==null) +- intBlk = new DataBlkInt(blk.ulx,blk.uly,blk.w,blk.h); +- else{ +- intBlk.ulx = blk.ulx; +- intBlk.uly = blk.uly; +- intBlk.w = blk.w; +- intBlk.h = blk.h; +- } +- blk = intBlk; +- } +- +- float percentage = +- (getTileIdx() + (blk.uly + 1.0F) / blk.h) / getNumTiles(); +- writer.processImageProgressWrapper(percentage * 100.0F); +- +- // If asking a component for the first time for this block, read the 3 +- // components +- if ((barr[c] == null) || +- (dbi.ulx > blk.ulx) || (dbi.uly > blk.uly) || +- (dbi.ulx+dbi.w < blk.ulx+blk.w) || +- (dbi.uly+dbi.h < blk.uly+blk.h)) { +- int k,j,i,mi; +- +- // Reset data arrays if needed +- if (barr[c] == null || barr[c].length < blk.w*blk.h) { +- barr[c] = new int[blk.w*blk.h]; +- } +- blk.setData(barr[c]); +- +- for (i = (c + 1) % nc; i != c; i = (i + 1) % nc) +- if (barr[i] == null || barr[i].length < blk.w*blk.h) { +- barr[i] = new int[blk.w*blk.h]; +- } +- +- // set attributes of the DataBlk used for buffering +- dbi.ulx = blk.ulx; +- dbi.uly = blk.uly; +- dbi.w = blk.w; +- dbi.h = blk.h; +- +- // get data from the image +- if (aTile == null) { +- aTile = getTile(co.x, co.y); +- Rectangle temp = aTile.getBounds(); +- aTile = aTile.createTranslatedChild(temp.x-minX, +- temp.y-minY); +- } +- +- for (i = 0; i < nc ; i++) { +- aTile.getSamples(blk.ulx, blk.uly, blk.w, blk.h, i, barr[i]); +- for (k = 0; k < barr[i].length; k++) +- barr[i][k] -= dcOffset; +- } +- //getByteData(raster, new Rectangle(blk.ulx, blk.uly, blk.w, blk.h), barr); +- +- // Set buffer attributes +- blk.setData(barr[c]); +- blk.offset = 0; +- blk.scanw = blk.w; +- } else { //Asking for the 2nd or 3rd block component +- blk.setData(barr[c]); +- blk.offset = (blk.ulx-dbi.ulx)*dbi.w+blk.ulx-dbi.ulx; +- blk.scanw = dbi.scanw; +- } +- +- // Turn off the progressive attribute +- blk.progressive = false; +- return blk; +- } +- +- /** +- * Returns, in the blk argument, a block of image data containing the +- * specifed rectangular area, in the specified component. The data is +- * returned, as a copy of the internal data, therefore the returned data +- * can be modified "in place". +- * +- *
After being read the coefficients are level shifted by subtracting +- * 2^(nominal bit range - 1) +- * +- *
The rectangular area to return is specified by the 'ulx', 'uly', 'w' +- * and 'h' members of the 'blk' argument, relative to the current +- * tile. These members are not modified by this method. The 'offset' of +- * the returned data is 0, and the 'scanw' is the same as the block's +- * width. See the 'DataBlk' class. +- * +- *
If the data array in 'blk' is 'null', then a new one is created. If +- * the data array is not 'null' then it is reused, and it must be large +- * enough to contain the block's data. Otherwise an 'ArrayStoreException' +- * or an 'IndexOutOfBoundsException' is thrown by the Java system. +- * +- *
The returned data has its 'progressive' attribute unset +- * (i.e. false). +- * +- *
When an I/O exception is encountered the JJ2KExceptionHandler is
+- * used. The exception is passed to its handleException method. The action
+- * that is taken depends on the action that has been registered in
+- * JJ2KExceptionHandler. See JJ2KExceptionHandler for details.
+- *
+- * @param blk Its coordinates and dimensions specify the area to
+- * return. If it contains a non-null data array, then it must have the
+- * correct dimensions. If it contains a null data array a new one is
+- * created. The fields in this object are modified to return the data.
+- *
+- * @param c The index of the component from which to get the data. Only
+- * 0,1 and 2 are valid.
+- *
+- * @return The requested DataBlk
+- *
+- * @see #getInternCompData
+- *
+- * @see JJ2KExceptionHandler
+- * */
+- public final DataBlk getCompData(DataBlk blk, int c) {
+- // NOTE: can not directly call getInterCompData since that returns
+- // internally buffered data.
+- int ulx,uly,w,h;
+-
+- // Check type of block provided as an argument
+- if(blk.getDataType()!=DataBlk.TYPE_INT){
+- DataBlkInt tmp = new DataBlkInt(blk.ulx,blk.uly,blk.w,blk.h);
+- blk = tmp;
+- }
+-
+- int bakarr[] = (int[])blk.getData();
+- // Save requested block size
+- ulx = blk.ulx;
+- uly = blk.uly;
+- w = blk.w;
+- h = blk.h;
+- // Force internal data buffer to be different from external
+- blk.setData(null);
+- getInternCompData(blk,c);
+- // Copy the data
+- if (bakarr == null) {
+- bakarr = new int[w*h];
+- }
+- if (blk.offset == 0 && blk.scanw == w) {
+- // Requested and returned block buffer are the same size
+- System.arraycopy(blk.getData(),0,bakarr,0,w*h);
+- }
+- else { // Requested and returned block are different
+- for (int i=h-1; i>=0; i--) { // copy line by line
+- System.arraycopy(blk.getData(),blk.offset+i*blk.scanw,
+- bakarr,i*w,w);
+- }
+- }
+- blk.setData(bakarr);
+- blk.offset = 0;
+- blk.scanw = blk.w;
+- return blk;
+- }
+-
+- /**
+- * Returns true if the data read was originally signed in the specified
+- * component, false if not. This method always returns false since PPM
+- * data is always unsigned.
+- *
+- * @param c The index of the component, from 0 to N-1.
+- *
+- * @return always false, since PPM data is always unsigned.
+- * */
+- public boolean isOrigSigned(int c) {
+- if (isBinary) return true;
+-
+- // Check component index
+- SampleModel sm = null;
+- if (inputIsRaster)
+- sm = raster.getSampleModel();
+- else
+- sm = src.getSampleModel();
+-
+- if (sm.getDataType() == DataBuffer.TYPE_USHORT ||
+- sm.getDataType() == DataBuffer.TYPE_BYTE)
+- return false;
+- return true;
+- }
+-
+- private int getNumXTiles() {
+- int x = destinationRegion.x;
+- int tx = tileXOffset;
+- int tw = tileWidth;
+- return ToTile(x + destinationRegion.width - 1, tx, tw) - ToTile(x, tx, tw) + 1;
+- }
+-
+- private int getNumYTiles() {
+- int y = destinationRegion.y;
+- int ty = tileYOffset;
+- int th = tileHeight;
+- return ToTile(y + destinationRegion.height - 1, ty, th) - ToTile(y, ty, th) + 1;
+- }
+-
+- private static int ToTile(int pos, int tileOffset, int tileSize) {
+- pos -= tileOffset;
+- if (pos < 0) {
+- pos += 1 - tileSize; // force round to -infinity (ceiling)
+- }
+- return pos/tileSize;
+- }
+-
+- private Raster getTile(int tileX, int tileY) {
+- int sx = tileXOffset + tileX * tileWidth;
+- int sy = tileYOffset + tileY * tileHeight;
+- tileX += tileXOffset / tileWidth;
+- tileY += tileYOffset / tileHeight;
+-
+- if (inputIsRaster) {
+- if (noTransform) {
+- return raster.createChild(sx, sy, getTileWidth(), getTileHeight(),
+- sx, sy, sourceBands);
+- }
+-
+- WritableRaster ras =
+- Raster.createWritableRaster(sm, new Point(sx, sy));
+-
+- int x = mapToSourceX(sx);
+- int y = mapToSourceY(sy);
+-
+- int minY = raster.getMinY();
+- int maxY = raster.getMinY() + raster.getHeight();
+-
+- int cTileWidth = getTileWidth();
+- for (int j = 0; j < getTileHeight(); j++, sy++, y += scaleY) {
+- if (y < minY || y >= maxY)
+- continue;
+- Raster source = raster.createChild(x, y, (cTileWidth - 1) * scaleX + 1, 1,
+- x, y, null);
+- int tempX = sx;
+- for (int i = 0, offset = x; i < cTileWidth; i++, tempX++, offset += scaleX) {
+- for (int k = 0; k < nc; k++) {
+- int p = source.getSample(offset, y, sourceBands[k]);
+- ras.setSample(tempX, sy, k, p);
+- }
+- }
+- }
+-
+- return ras;
+-
+- } else {
+- if (noTransform) {
+- Raster ras = src.getTile(tileX, tileY);
+- if (noSubband)
+- return ras;
+- else {
+- return ras.createChild(sx, sy, tileWidth, tileHeight,
+- sx, sy, sourceBands);
+- }
+- }
+-
+- WritableRaster ras = Raster.createWritableRaster(sm, new Point(sx, sy));
+-
+- int x = mapToSourceX(sx);
+- int y = mapToSourceY(sy);
+-
+- int minY = src.getMinY();
+- int maxY = src.getMinY() + src.getHeight();
+- int length = tileWidth * scaleX;
+-
+- if (x + length >= src.getWidth())
+- length = src.getWidth() - x;
+- int dLength = (length + scaleX -1 ) / scaleX;
+-
+- for (int j = 0; j < tileHeight; j++, sy++, y += scaleY) {
+- if (y < minY || y >= maxY)
+- continue;
+-
+- Raster source = src.getData(new Rectangle(x, y, length, 1));
+-
+- int tempX = sx;
+- for (int i = 0, offset = x; i < dLength; i++, tempX++, offset += scaleX) {
+-
+- for (int k = 0; k < nc; k++) {
+- int p = source.getSample(offset, y, sourceBands[k]);
+-
+- ras.setSample(tempX, sy, k, p);
+- }
+- }
+- }
+- return ras;
+- }
+- }
+-
+- private int mapToSourceX(int x) {
+- return x * scaleX + xOffset;
+- }
+-
+- private int mapToSourceY(int y) {
+- return y * scaleY + yOffset;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ResolutionBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ResolutionBox.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ResolutionBox.java 2005-02-11 00:01:37.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ResolutionBox.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,229 +0,0 @@
+-/*
+- * $RCSfile: ResolutionBox.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:37 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import javax.imageio.metadata.IIOInvalidTreeException;
+-import javax.imageio.metadata.IIOMetadataNode;
+-import org.w3c.dom.Node;
+-import org.w3c.dom.NodeList;
+-
+-/** This class is defined to represent a Resolution Box of JPEG JP2
+- * file format. A Data Entry URL Box has a length, and a fixed type
+- * of "resc" (capture resolution) or "resd" (default display resolution).
+- *
+- * Its contens includes the resolution numerators, denominator, and the
+- * exponents for both horizontal and vertical directions.
+- */
+-public class ResolutionBox extends Box {
+- /** The data elements in this box. */
+- private short numV;
+- private short numH;
+- private short denomV;
+- private short denomH;
+- private byte expV;
+- private byte expH;
+-
+- /** The cached horizontal/vertical resolutions. */
+- private float hRes;
+- private float vRes;
+-
+- /** Constructs a ResolutionBox
from the provided type and
+- * content data array.
+- */
+- public ResolutionBox(int type, byte[] data) {
+- super(18, type, data);
+- }
+-
+- /** Constructs a ResolutionBox
from the provided type and
+- * horizontal/vertical resolutions.
+- */
+- public ResolutionBox(int type, float hRes, float vRes) {
+- super(18, type, null);
+- this.hRes = hRes;
+- this.vRes = vRes;
+- denomH = denomV = 1;
+-
+- expV = 0;
+- if (vRes >= 32768) {
+- int temp = (int)vRes;
+- while (temp >= 32768) {
+- expV++;
+- temp /= 10;
+- }
+- numV = (short)(temp & 0xFFFF);
+- } else {
+- numV = (short)vRes;
+- }
+-
+- expH = 0;
+- if (hRes >= 32768) {
+- int temp = (int)hRes;
+- while (temp >= 32768) {
+- expH++;
+- temp /= 10;
+- }
+- numH = (short)(temp & 0xFFFF);
+- } else {
+- numH = (short)hRes;
+- }
+- }
+-
+- /** Constructs a ResolutionBox
based on the provided
+- * org.w3c.dom.Node
.
+- */
+- public ResolutionBox(Node node) throws IIOInvalidTreeException {
+- super(node);
+- NodeList children = node.getChildNodes();
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+- String name = child.getNodeName();
+-
+- if ("VerticalResolutionNumerator".equals(name)) {
+- numV = Box.getShortElementValue(child);
+- }
+-
+- if ("VerticalResolutionDenominator".equals(name)) {
+- denomV = Box.getShortElementValue(child);
+- }
+-
+- if ("HorizontalResolutionNumerator".equals(name)) {
+- numH = Box.getShortElementValue(child);
+- }
+-
+- if ("HorizontalResolutionDenominator".equals(name)) {
+- denomH = Box.getShortElementValue(child);
+- }
+-
+- if ("VerticalResolutionExponent".equals(name)) {
+- expV = Box.getByteElementValue(child);
+- }
+-
+- if ("HorizontalResolutionExponent".equals(name)) {
+- expH = Box.getByteElementValue(child);
+- }
+- }
+- }
+-
+- /** Return the horizontal resolution. */
+- public float getHorizontalResolution() {
+- return hRes;
+- }
+-
+- /** Return the vertical resolution. */
+- public float getVerticalResolution() {
+- return vRes;
+- }
+-
+- /** Parse the data elements from the provided content data array. */
+- protected void parse(byte[] data) {
+- numV = (short)(((data[0] & 0xFF) << 8) | (data[1] & 0xFF));
+- denomV = (short)(((data[2] & 0xFF) << 8) | (data[3] & 0xFF));
+- numH = (short)(((data[4] & 0xFF) << 8) | (data[5] & 0xFF));
+- denomH = (short)(((data[6] & 0xFF) << 8) | (data[7] & 0xFF));
+- expV = data[8];
+- expH = data[9];
+- vRes = (float)((numV & 0xFFFF) * Math.pow(10, expV) / (denomV & 0xFFFF));
+- hRes = (float)((numH & 0xFFFF)* Math.pow(10, expH) / (denomH & 0xFFFF));
+- }
+-
+- /** Creates an IIOMetadataNode
from this resolution
+- * box. The format of this node is defined in the XML dtd and xsd
+- * for the JP2 image file.
+- */
+- public IIOMetadataNode getNativeNode() {
+- IIOMetadataNode node = new IIOMetadataNode(Box.getName(getType()));
+- setDefaultAttributes(node);
+-
+- IIOMetadataNode child = new IIOMetadataNode("VerticalResolutionNumerator");
+- child.setUserObject(new Short(numV));
+- child.setNodeValue("" + numV);
+- node.appendChild(child);
+-
+- child = new IIOMetadataNode("VerticalResolutionDenominator");
+- child.setUserObject(new Short(denomV));
+- child.setNodeValue("" + denomV);
+- node.appendChild(child);
+-
+- child = new IIOMetadataNode("HorizontalResolutionNumerator");
+- child.setUserObject(new Short(numH));
+- child.setNodeValue("" + numH);
+- node.appendChild(child);
+-
+- child = new IIOMetadataNode("HorizontalResolutionDenominator");
+- child.setUserObject(new Short(denomH));
+- child.setNodeValue("" + denomH);
+- node.appendChild(child);
+-
+- child = new IIOMetadataNode("VerticalResolutionExponent");
+- child.setUserObject(new Byte(expV));
+- child.setNodeValue("" + expV);
+- node.appendChild(child);
+-
+- child = new IIOMetadataNode("HorizontalResolutionExponent");
+- child.setUserObject(new Byte(expH));
+- child.setNodeValue("" + expH);
+- node.appendChild(child);
+-
+- return node;
+- }
+-
+- protected void compose() {
+- if (data != null)
+- return;
+- data = new byte[10];
+- data[0] = (byte)(numV >> 8);
+- data[1] = (byte)(numV & 0xFF);
+- data[2] = (byte)(denomV >> 8);
+- data[3] = (byte)(denomV & 0xFF);
+-
+- data[4] = (byte)(numH >> 8);
+- data[5] = (byte)(numH & 0xFF);
+- data[6] = (byte)(denomH >> 8);
+- data[7] = (byte)(denomH & 0xFF);
+-
+- data[8] = expV;
+- data[9] = expH;
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/SignatureBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/SignatureBox.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/SignatureBox.java 2005-02-11 00:01:37.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/SignatureBox.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,93 +0,0 @@
+-/*
+- * $RCSfile: SignatureBox.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:37 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-import org.w3c.dom.Node;
+-import javax.imageio.metadata.IIOInvalidTreeException;
+-import javax.imageio.metadata.IIOMetadataNode;
+-
+-/** This class is defined to represent a Signature Box of JPEG JP2
+- * file format. This type of box has a fixed length of 12, a type of "jP "
+- * and a four byte content of 0x0D0A870A, which is used to detects of the
+- * common file transmission errors which substitutes SignatureBox
. */
+- public SignatureBox() {
+- super(12, 0x6A502020, null);
+- }
+-
+- /** Constructs a SignatureBox
based on the provided
+- * org.w3c.dom.Node
.
+- */
+- public SignatureBox(Node node) throws IIOInvalidTreeException {
+- super(node);
+- }
+-
+- /** Constructs a SignatureBox
based on the provided
+- * byte array.
+- */
+- public SignatureBox(byte[] data) throws IIOInvalidTreeException {
+- super(12, 0x6A502020, data);
+- }
+-
+- /** Creates an IIOMetadataNode
from this signature
+- * box. The format of this node is defined in the XML dtd and xsd
+- * for the JP2 image file.
+- */
+- public IIOMetadataNode getNativeNode() {
+- IIOMetadataNode node = new IIOMetadataNode(Box.getName(getType()));
+- setDefaultAttributes(node);
+- node.setAttribute("Signature", Integer.toString(0x0D0A870A));
+- return node;
+- }
+-
+- protected void compose() {
+- if (data != null)
+- return;
+- data = new byte[]{(byte)0x0D, (byte)0x0A, (byte)0x87, (byte)0x0A};
+- }
+-}
+-
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/UUIDBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/UUIDBox.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/UUIDBox.java 2005-02-11 00:01:37.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/UUIDBox.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,130 +0,0 @@
+-/*
+- * $RCSfile: UUIDBox.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:37 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import javax.imageio.metadata.IIOInvalidTreeException;
+-import javax.imageio.metadata.IIOMetadataNode;
+-import org.w3c.dom.Node;
+-import org.w3c.dom.NodeList;
+-
+-/** This class is defined to represent a UUID Box of JPEG JP2
+- * file format. This type of box has a length, a type of "uuid". Its
+- * content is a 16-byte UUID followed with a various-length data.
+- */
+-public class UUIDBox extends Box {
+- /** Cache the element names for this box's xml definition */
+- private static String[] elementNames = {"UUID", "Data"};
+-
+- /** This method will be called by the getNativeNodeForSimpleBox of the
+- * class Box to get the element names.
+- */
+- public static String[] getElementNames() {
+- return elementNames;
+- }
+-
+- /** The data elements in this UUID box. */
+- private byte[] uuid;
+- private byte[] udata;
+-
+- /** Constructs a UUIDBox
from its content data array. */
+- public UUIDBox(byte[] data) {
+- super(8 + data.length, 0x75756964, data);
+- }
+-
+- /** Constructs a UUIDBox
based on the provided
+- * org.w3c.dom.Node
.
+- */
+- public UUIDBox(Node node) throws IIOInvalidTreeException {
+- super(node);
+- NodeList children = node.getChildNodes();
+-
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+- String name = child.getNodeName();
+-
+- if ("UUID".equals(name)) {
+- uuid = Box.getByteArrayElementValue(child);
+- }
+-
+- if ("Data".equals(name)) {
+- udata = Box.getByteArrayElementValue(child);
+- }
+- }
+- }
+-
+- /** Parses the data elements from the provided data array. */
+- protected void parse(byte[] data) {
+- uuid = new byte[16];
+- System.arraycopy(data, 0, uuid, 0, 16);
+- udata = new byte[data.length - 16];
+- System.arraycopy(data, 16, udata, 0, udata.length);
+- }
+-
+- /** Returns the UUID of this box. */
+- public byte[] getUUID() {
+- return uuid;
+- }
+-
+- /** Returns the UUID data of this box. */
+- public byte[] getData() {
+- return udata;
+- }
+-
+- /** Creates an IIOMetadataNode
from this UUID
+- * box. The format of this node is defined in the XML dtd and xsd
+- * for the JP2 image file.
+- */
+- public IIOMetadataNode getNativeNode() {
+- return getNativeNodeForSimpleBox();
+- }
+-
+- protected void compose() {
+- if (data != null)
+- return;
+- data = new byte[16 + udata.length];
+- System.arraycopy(uuid, 0, data, 0, 16);
+- System.arraycopy(udata, 0, data, 16, udata.length);
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/UUIDListBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/UUIDListBox.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/UUIDListBox.java 2006-10-10 19:48:57.000000000 -0400
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/UUIDListBox.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,157 +0,0 @@
+-/*
+- * $RCSfile: UUIDListBox.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.2 $
+- * $Date: 2006/10/10 23:48:57 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import javax.imageio.metadata.IIOInvalidTreeException;
+-import javax.imageio.metadata.IIOMetadataNode;
+-import org.w3c.dom.Node;
+-import org.w3c.dom.NodeList;
+-
+-import com.sun.media.imageioimpl.common.ImageUtil;
+-
+-/** This class is defined to represent a UUID list Box of JPEG JP2
+- * file format. This type of box has a length, a type of "ulst". Its
+- * contents include the number of UUID entry and a list of 16-byte UUIDs.
+- */
+-public class UUIDListBox extends Box {
+- /** The data elements of this box. */
+- private short num;
+- private byte[][] uuids;
+-
+- /** Constructs a UUIDListBox
from the provided uuid number
+- * and uuids. The provided uuids should have a size of 16; otherwise,
+- * Exception
may thrown in later the process. The provided
+- * number should consistent with the size of the uuid array.
+- */
+- public UUIDListBox(short num, byte[][] uuids) {
+- super(10 + (uuids.length << 4), 0x756c7374, null);
+- this.num = num;
+- this.uuids = uuids;
+- }
+-
+- /** Constructs a UUIDListBox
from the provided content
+- * data array.
+- */
+- public UUIDListBox(byte[] data) {
+- super(8 + data.length, 0x756c7374, data);
+- }
+-
+- /** Constructs a UUIDListBox
based on the provided
+- * org.w3c.dom.Node
.
+- */
+- public UUIDListBox(Node node) throws IIOInvalidTreeException {
+- super(node);
+- NodeList children = node.getChildNodes();
+- int index = 0;
+-
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+-
+- if ("NumberUUID".equals(child.getNodeName())) {
+- num = (short)Box.getShortElementValue(child);
+- uuids = new byte[num][];
+- }
+-
+- }
+-
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+-
+- if ("UUID".equals(child.getNodeName()) && index < num) {
+- uuids[index++] = Box.getByteArrayElementValue(child);
+- }
+- }
+- }
+-
+- /** Parses the data elements from the provided content data array. */
+- protected void parse(byte[] data) {
+- num = (short)(((data[0] & 0xFF) << 8) | (data[1] & 0xFF));
+-
+- uuids = new byte[num][];
+- int pos = 2;
+- for (int i = 0; i < num; i++) {
+- uuids[i] = new byte[16];
+- System.arraycopy(data, pos, uuids[i], 0, 16);
+- pos += 16;
+- }
+- }
+-
+- /** Creates an IIOMetadataNode
from this UUID list
+- * box. The format of this node is defined in the XML dtd and xsd
+- * for the JP2 image file.
+- */
+- public IIOMetadataNode getNativeNode() {
+- IIOMetadataNode node = new IIOMetadataNode(Box.getName(getType()));
+- setDefaultAttributes(node);
+-
+- IIOMetadataNode child = new IIOMetadataNode("NumberUUID");
+- child.setUserObject(new Short(num));
+- child.setNodeValue("" + num);
+- node.appendChild(child);
+-
+- for (int i = 0; i < num; i++) {
+- child = new IIOMetadataNode("UUID");
+- child.setUserObject(uuids[i]);
+- child.setNodeValue(ImageUtil.convertObjectToString(uuids[i]));
+- node.appendChild(child);
+- }
+-
+- return node;
+- }
+-
+- protected void compose() {
+- if (data != null)
+- return;
+- data = new byte[2 + num * 16];
+-
+- data[0] = (byte)(num >> 8);
+- data[1] = (byte)(num & 0xFF);
+-
+- for (int i = 0, pos = 2; i < num; i++) {
+- System.arraycopy(uuids[i], 0, data, pos, 16);
+- pos += 16;
+- }
+- }
+-}
+diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/XMLBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/XMLBox.java
+--- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/XMLBox.java 2005-02-11 00:01:37.000000000 -0500
++++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/XMLBox.java 1969-12-31 19:00:00.000000000 -0500
+@@ -1,116 +0,0 @@
+-/*
+- * $RCSfile: XMLBox.java,v $
+- *
+- *
+- * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
+- *
+- * Redistribution and use in source and binary forms, with or without
+- * modification, are permitted provided that the following conditions
+- * are met:
+- *
+- * - Redistribution of source code must retain the above copyright
+- * notice, this list of conditions and the following disclaimer.
+- *
+- * - Redistribution in binary form must reproduce the above copyright
+- * notice, this list of conditions and the following disclaimer in
+- * the documentation and/or other materials provided with the
+- * distribution.
+- *
+- * Neither the name of Sun Microsystems, Inc. or the names of
+- * contributors may be used to endorse or promote products derived
+- * from this software without specific prior written permission.
+- *
+- * This software is provided "AS IS," without a warranty of any
+- * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+- * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+- * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+- * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+- * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+- * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+- * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+- * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+- * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+- * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+- * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+- * POSSIBILITY OF SUCH DAMAGES.
+- *
+- * You acknowledge that this software is not designed or intended for
+- * use in the design, construction, operation or maintenance of any
+- * nuclear facility.
+- *
+- * $Revision: 1.1 $
+- * $Date: 2005/02/11 05:01:37 $
+- * $State: Exp $
+- */
+-package com.sun.media.imageioimpl.plugins.jpeg2000;
+-
+-import javax.imageio.metadata.IIOInvalidTreeException;
+-import javax.imageio.metadata.IIOMetadataNode;
+-import org.w3c.dom.Node;
+-import org.w3c.dom.NodeList;
+-
+-/** This class is defined to represent a XML box of JPEG JP2
+- * file format. This type of box has a length, a type of "xml ". Its
+- * content is a text string of a XML instance.
+- */
+-public class XMLBox extends Box {
+- /** Cache the element names for this box's xml definition */
+- private static String[] elementNames = {"Content"};
+-
+- /** This method will be called by the getNativeNodeForSimpleBox of the
+- * class Box to get the element names.
+- */
+- public static String[] getElementNames() {
+- return elementNames;
+- }
+-
+- /** Create a Box from its content. */
+- public XMLBox(byte[] data) {
+- super(8 + data.length, 0x786D6C20, data);
+- }
+-
+- /** Constructs a UUIDListBox
based on the provided
+- * org.w3c.dom.Node
.
+- */
+- public XMLBox(Node node) throws IIOInvalidTreeException {
+- super(node);
+- NodeList children = node.getChildNodes();
+-
+- for (int i = 0; i < children.getLength(); i++) {
+- Node child = children.item(i);
+- String name = child.getNodeName();
+-
+- if ("Content".equals(name)) {
+- String value = child.getNodeValue();
+- if (value != null)
+- data = value.getBytes();
+- else if (child instanceof IIOMetadataNode) {
+- value = (String)((IIOMetadataNode)child).getUserObject();
+- if (value != null)
+- data = value.getBytes();
+- }
+- }
+- }
+- }
+-
+- /** Creates an IIOMetadataNode
from this XML
+- * box. The format of this node is defined in the XML dtd and xsd
+- * for the JP2 image file.
+- */
+- public IIOMetadataNode getNativeNode() {
+- try {
+- IIOMetadataNode node = new IIOMetadataNode(Box.getName(getType()));
+- setDefaultAttributes(node);
+- IIOMetadataNode child = new IIOMetadataNode("Content");
+- String value = null;
+- if (data != null)
+- value = new String(data);
+- child.setUserObject(value);
+- child.setNodeValue(value);
+- node.appendChild(child);
+- return node;
+- } catch (Exception e) {
+- throw new IllegalArgumentException(I18N.getString("Box0"));
+- }
+- }
+-}
diff --git a/SPECS/jai-imageio-core.spec b/SPECS/jai-imageio-core.spec
new file mode 100644
index 0000000..af26d24
--- /dev/null
+++ b/SPECS/jai-imageio-core.spec
@@ -0,0 +1,194 @@
+%global pkg_name jai-imageio-core
+%{?scl:%scl_package %{pkg_name}}
+%{?java_common_find_provides_and_requires}
+
+%global cvs_ver 20100217
+
+Name: %{?scl_prefix}%{pkg_name}
+Version: 1.2
+Release: 0.14.%{cvs_ver}cvs.14%{?dist}
+Summary: Core Java Advanced Imaging Image I/O Tools API
+
+License: BSD
+URL: https://jai-imageio.dev.java.net/
+Source0: jai-imageio-core-cvs%{cvs_ver}-CLEANED.tar.xz
+Source1: README-RHSCL.txt
+
+# jai-imageio-core contains code under a restrictive licence that we
+# cannot ship. This script will download and generate a tarball from
+# CVS. Unfortunately, a login is required to download from CVS and
+# there are no source tarballs.
+#
+# Register at:
+# https://www.dev.java.net/servlets/Join
+#
+# Then, run:
+# ./generate-tarball.sh USERNAME DATE
+Source2: generate-tarball.sh
+
+BuildRequires: %{?scl_prefix}ant
+BuildRequires: %{?scl_prefix}javapackages-tools
+BuildRequires: recode
+Requires: %{?scl_prefix}javapackages-tools
+
+
+Patch0: jai-imageio-core-remove-imageio-services.patch
+Patch1: jai-imageio-core-remove-codeclib-plugins.patch
+Patch2: jai-imageio-core-remove-jai-operations.patch
+Patch3: jai-imageio-core-remove-jpeg2000-plugin.patch
+Patch4: jai-imageio-core-no-sun-classes.patch
+
+BuildArch: noarch
+
+%description
+This package contains the core Java Advanced Imaging Image I/O Tools API,
+minus JPEG 2000, JAI Image I/O operations, and the C-based codecLib.
+
+
+%package javadoc
+Summary: Javadocs for %{pkg_name}
+
+
+%description javadoc
+This package contains the API documentation for %{pkg_name}.
+
+
+%prep
+%setup -q -n jai-imageio-core-cvs%{cvs_ver}-CLEANED
+%{?scl:scl enable %{scl_maven} %{scl} - <<"EOF"}
+set -e -x
+
+find -name '*.class' -exec rm -f '{}' \;
+find -name '*.jar' -exec rm -f '{}' \;
+
+# remove unbuildable items
+%patch0 -p1
+%patch1 -p1
+%patch2 -p1
+%patch3 -p1
+
+# remove use of sun.*
+# https://jai-imageio-core.dev.java.net/issues/show_bug.cgi?id=186
+%patch4 -p0
+
+# fix latin-1 documentation
+recode latin1..utf-8 COPYRIGHT.txt
+
+# install our documentation
+cp -av %{SOURCE1} .
+%{?scl:EOF}
+
+
+%build
+%{?scl:scl enable %{scl_maven} %{scl} - <<"EOF"}
+set -e -x
+# note: BUILD_TARGET is pretty much ignored, but we need it
+# to know where the built files will be located
+ant -DBUILD_TARGET=linux-i586 jar-opt docs-jcp
+%{?scl:EOF}
+
+
+%install
+%{?scl:scl enable %{scl_maven} %{scl} - <<"EOF"}
+set -e -x
+mkdir -p $RPM_BUILD_ROOT%{_javadir}
+mkdir -p $RPM_BUILD_ROOT%{_javadocdir}/%{name}
+
+cp -av build/linux-i586/opt/lib/ext/jai_imageio.jar $RPM_BUILD_ROOT%{_javadir}/jai_imageio.jar
+
+cp -av build/linux-i586/javadocs/docs-jcp/* $RPM_BUILD_ROOT%{_javadocdir}/%{name}
+%{?scl:EOF}
+
+%files
+%doc LICENSE.txt COPYRIGHT.txt README-RHSCL.txt
+%{_javadir}/*.jar
+
+%files javadoc
+%doc LICENSE.txt COPYRIGHT.txt
+%{_javadocdir}/%{name}
+
+
+%changelog
+* Tue Jan 13 2015 Michael Simacek