com.sun.image.codec.jpeg.JPEGDecodeParam.COLOR_ID_YCbCr;
break;
}
// Get the JDK encoding parameters.
Raster tile00 = im.getTile(im.getMinTileX(), im.getMinTileY());
jpegEncodeParam =
com.sun.image.codec.jpeg.JPEGCodec.getDefaultJPEGEncodeParam(
tile00, jpegColorID);
// Modify per values passed in.
JPEGImageEncoder.modifyEncodeParam(jep, jpegEncodeParam, numBands);
// JPEGTables field.
if(jep.getWriteImageOnly()) {
// Write an abbreviated tables-only stream to JPEGTables field.
jpegEncodeParam.setImageInfoValid(false);
jpegEncodeParam.setTableInfoValid(true);
ByteArrayOutputStream tableStream =
new ByteArrayOutputStream();
jpegEncoder =
com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder(
tableStream,
jpegEncodeParam);
jpegEncoder.encode(tile00);
byte[] tableData = tableStream.toByteArray();
fields.add(new TIFFField(TIFF_JPEG_TABLES,
TIFFField.TIFF_UNDEFINED,
tableData.length,
tableData));
// Reset encoder so it's recreated below.
jpegEncoder = null;
}
}
if(imageType == TIFF_YCBCR) {
// YCbCrSubSampling: 2 is the default so we must write 1 as
// we do not (yet) do any subsampling.
int subsampleH = 1;
int subsampleV = 1;
// If JPEG, update values.
if(compression == COMP_JPEG_TTN2) {
// Determine maximum subsampling.
subsampleH = jep.getHorizontalSubsampling(0);
subsampleV = jep.getVerticalSubsampling(0);
for(int i = 1; i < numBands; i++) {
int subH = jep.getHorizontalSubsampling(i);
if(subH > subsampleH) {
subsampleH = subH;
}
int subV = jep.getVerticalSubsampling(i);
if(subV > subsampleV) {
subsampleV = subV;
}
}
}
fields.add(new TIFFField(TIFF_YCBCR_SUBSAMPLING,
TIFFField.TIFF_SHORT, 2,
new char[] {(char)subsampleH,
(char)subsampleV}));
// YCbCr positioning.
fields.add(new TIFFField(TIFF_YCBCR_POSITIONING,
TIFFField.TIFF_SHORT, 1,
new char[] {compression == COMP_JPEG_TTN2 ?
(char)1 : (char)2}));
// Reference black/white.
long[][] refbw;
if(compression == COMP_JPEG_TTN2) {
refbw =
new long[][] { // no headroon/footroom
{0, 1}, {255, 1}, {128, 1}, {255, 1}, {128, 1}, {255, 1}
};
} else {
refbw =
new long[][] { // CCIR 601.1 headroom/footroom (presumptive)
{15, 1}, {235, 1}, {128, 1}, {240, 1}, {128, 1}, {240, 1}
};
}
fields.add(new TIFFField(TIFF_REF_BLACK_WHITE,
TIFFField.TIFF_RATIONAL, 6,
refbw));
}
// ---- No more automatically generated fields should be added
// after this point. ----
// Add extra fields specified via the encoding parameters.
TIFFField[] extraFields = encodeParam.getExtraFields();
if(extraFields != null) {
ArrayList extantTags = new ArrayList(fields.size());
Iterator fieldIter = fields.iterator();
while(fieldIter.hasNext()) {
TIFFField fld = (TIFFField)fieldIter.next();
extantTags.add(new Integer(fld.getTag()));
}
int numExtraFields = extraFields.length;
for(int i = 0; i < numExtraFields; i++) {
TIFFField fld = extraFields[i];
Integer tagValue = new Integer(fld.getTag());
if(!extantTags.contains(tagValue)) {
fields.add(fld);
extantTags.add(tagValue);
}
}
}
// ---- No more fields of any type should be added after this. ----
// Determine the size of the IFD which is written after the header
// of the stream or after the data of the previous image in a
// multi-page stream.
int dirSize = getDirectorySize(fields);
// The first data segment is written after the field overflow
// following the IFD so initialize the first offset accordingly.
tileOffsets[0] = ifdOffset + dirSize;
// Branch here depending on whether data are being comrpressed.
// If not, then the IFD is written immediately.
// If so then there are three possibilities:
// A) the OutputStream is a SeekableOutputStream (outCache null);
// B) the OutputStream is not a SeekableOutputStream and a file cache
// is used (outCache non-null, tempFile non-null);
// C) the OutputStream is not a SeekableOutputStream and a memory cache
// is used (outCache non-null, tempFile null).
OutputStream outCache = null;
byte[] compressBuf = null;
File tempFile = null;
int nextIFDOffset = 0;
boolean skipByte = false;
Deflater deflater = null;
int deflateLevel = Deflater.DEFAULT_COMPRESSION;
boolean jpegRGBToYCbCr = false;
if(compression == COMP_NONE) {
// Determine the number of bytes of padding necessary between
// the end of the IFD and the first data segment such that the
// alignment of the data conforms to the specification (required
// for uncompressed data only).
int numBytesPadding = 0;
if(sampleSize[0] == 16 && tileOffsets[0] % 2 != 0) {
numBytesPadding = 1;
tileOffsets[0]++;
} else if(sampleSize[0] == 32 && tileOffsets[0] % 4 != 0) {
numBytesPadding = (int)(4 - tileOffsets[0] % 4);
tileOffsets[0] += numBytesPadding;
}
// Update the data offsets (which TIFFField stores by reference).
for (int i = 1; i < numTiles; i++) {
tileOffsets[i] = tileOffsets[i-1] + tileByteCounts[i-1];
}
if(!isLast) {
// Determine the offset of the next IFD.
nextIFDOffset = (int)(tileOffsets[0] + totalBytesOfData);
// IFD offsets must be on a word boundary.
if(nextIFDOffset % 2 != 0) {
nextIFDOffset++;
skipByte = true;
}
}
// Write the IFD and field overflow before the image data.
writeDirectory(ifdOffset, fields, nextIFDOffset);
// Write any padding bytes needed between the end of the IFD
// and the start of the actual image data.
if(numBytesPadding != 0) {
for(int padding = 0; padding < numBytesPadding; padding++) {
output.write((byte)0);
}
}
} else {
// If compressing, the cannot be written yet as the size of the
// data segments is unknown.
if((output instanceof SeekableOutputStream)) {
// Simply seek to the first data segment position.
((SeekableOutputStream)output).seek(tileOffsets[0]);
} else {
// Cache the original OutputStream.
outCache = output;
try {
// Attempt to create a temporary file.
tempFile = File.createTempFile("jai-SOS-", ".tmp");
tempFile.deleteOnExit();
RandomAccessFile raFile =
new RandomAccessFile(tempFile, "rw");
output = new SeekableOutputStream(raFile);
// XXX Be sure that this file is deleted no matter how
// this method is exited!
} catch(Exception e) {
tempFile = null;
// Allocate memory for the entire image data (!).
output = new ByteArrayOutputStream((int)totalBytesOfData);
}
}
int bufSize = 0;
switch(compression) {
case COMP_GROUP3_1D:
// This initial buffer size is based on an alternating 1-0
// pattern generating the most bits when converted to code
// words: 9 bits out for each pair of bits in. So the number
// of bit pairs is determined, multiplied by 9, converted to
// bytes, and a ceil() is taken to account for fill bits at the
// end of each line. The "2" addend accounts for the case
// of the pattern beginning with black. The buffer is intended
// to hold only a single row.
bufSize = (int)Math.ceil((((tileWidth + 1)/2)*9 + 2)/8.0);
break;
case COMP_GROUP3_2D:
case COMP_GROUP4:
// Calculate the maximum row as the G3-1D size plus the EOL,
// multiply this by the number of rows in the tile, and add
// 6 EOLs for the RTC (return to control).
bufSize = (int)Math.ceil((((tileWidth + 1)/2)*9 + 2)/8.0);
bufSize = tileHeight*(bufSize + 2) + 12;
break;
case COMP_PACKBITS:
bufSize = (int)(bytesPerTile +
((bytesPerRow+127)/128)*tileHeight);
break;
case COMP_JPEG_TTN2:
bufSize = 0;
// Set color conversion flag.
if(imageType == TIFF_YCBCR &&
colorModel != null &&
colorModel.getColorSpace().getType() ==
ColorSpace.TYPE_RGB) {
jpegRGBToYCbCr = true;
}
break;
case COMP_DEFLATE:
bufSize = (int)bytesPerTile;
deflater = new Deflater(encodeParam.getDeflateLevel());
break;
default:
bufSize = 0;
}
if(bufSize != 0) {
compressBuf = new byte[bufSize];
}
}
// ---- Writing of actual image data ----
// Buffer for up to tileHeight rows of pixels
int[] pixels = null;
float[] fpixels = null;
// Whether to test for contiguous data.
boolean checkContiguous =
((sampleSize[0] == 1 &&
sampleModel instanceof MultiPixelPackedSampleModel &&
dataType == DataBuffer.TYPE_BYTE) ||
(sampleSize[0] == 8 &&
sampleModel instanceof ComponentSampleModel));
// Also create a buffer to hold tileHeight lines of the
// data to be written to the file, so we can use array writes.
byte[] bpixels = null;
if(compression != COMP_JPEG_TTN2) {
if(dataType == DataBuffer.TYPE_BYTE) {
bpixels = new byte[tileHeight * tileWidth * numBands];
} else if(dataTypeIsShort) {
bpixels = new byte[2 * tileHeight * tileWidth * numBands];
} else if(dataType == DataBuffer.TYPE_INT ||
dataType == DataBuffer.TYPE_FLOAT) {
bpixels = new byte[4 * tileHeight * tileWidth * numBands];
}
}
// Process tileHeight rows at a time
int lastRow = minY + height;
int lastCol = minX + width;
int tileNum = 0;
for (int row = minY; row < lastRow; row += tileHeight) {
int rows = isTiled ?
tileHeight : Math.min(tileHeight, lastRow - row);
int size = rows * tileWidth * numBands;
for(int col = minX; col < lastCol; col += tileWidth) {
// Grab the pixels
Raster src =
im.getData(new Rectangle(col, row, tileWidth, rows));
boolean useDataBuffer = false;
if(compression != COMP_JPEG_TTN2) { // JPEG access Raster
if(checkContiguous) {
if(sampleSize[0] == 8) { // 8-bit
ComponentSampleModel csm =
(ComponentSampleModel)src.getSampleModel();
int[] bankIndices = csm.getBankIndices();
int[] bandOffsets = csm.getBandOffsets();
int pixelStride = csm.getPixelStride();
int lineStride = csm.getScanlineStride();
if(pixelStride != numBands ||
lineStride != bytesPerRow) {
useDataBuffer = false;
} else {
useDataBuffer = true;
for(int i = 0;
useDataBuffer && i < numBands;
i++) {
if(bankIndices[i] != 0 ||
bandOffsets[i] != i) {
useDataBuffer = false;
}
}
}
} else { // 1-bit
MultiPixelPackedSampleModel mpp =
(MultiPixelPackedSampleModel)src.getSampleModel();
if(mpp.getNumBands() == 1 &&
mpp.getDataBitOffset() == 0 &&
mpp.getPixelBitStride() == 1) {
useDataBuffer = true;
}
}
}
if(!useDataBuffer) {
if(dataType == DataBuffer.TYPE_FLOAT) {
fpixels = src.getPixels(col, row, tileWidth, rows,
fpixels);
} else {
pixels = src.getPixels(col, row, tileWidth, rows,
pixels);
}
}
}
int index;
int pixel = 0;;
int k = 0;
switch(sampleSize[0]) {
case 1:
if(useDataBuffer) {
byte[] btmp =
((DataBufferByte)src.getDataBuffer()).getData();
MultiPixelPackedSampleModel mpp =
(MultiPixelPackedSampleModel)src.getSampleModel();
int lineStride = mpp.getScanlineStride();
int inOffset =
mpp.getOffset(col -
src.getSampleModelTranslateX(),
row -
src.getSampleModelTranslateY());
if(lineStride == (int)bytesPerRow) {
System.arraycopy(btmp, inOffset,
bpixels, 0,
(int)bytesPerRow*rows);
} else {
int outOffset = 0;
for(int j = 0; j < rows; j++) {
System.arraycopy(btmp, inOffset,
bpixels, outOffset,
(int)bytesPerRow);
inOffset += lineStride;
outOffset += (int)bytesPerRow;
}
}
} else {
index = 0;
// For each of the rows in a strip
for (int i=0; i<rows; i++) {
// Write number of pixels exactly divisible by 8
for (int j=0; j<tileWidth/8; j++) {
pixel =
(pixels[index++] << 7) |
(pixels[index++] << 6) |
(pixels[index++] << 5) |
(pixels[index++] << 4) |
(pixels[index++] << 3) |
(pixels[index++] << 2) |
(pixels[index++] << 1) |
pixels[index++];
bpixels[k++] = (byte)pixel;
}
// Write the pixels remaining after division by 8
if (tileWidth%8 > 0) {
pixel = 0;
for (int j=0; j<tileWidth%8; j++) {
pixel |= (pixels[index++] << (7 - j));
}
bpixels[k++] = (byte)pixel;
}
}
}
if(compression == COMP_NONE) {
output.write(bpixels, 0, rows * ((tileWidth+7)/8));
} else if(compression == COMP_GROUP3_1D) {
int rowStride = (tileWidth + 7)/8;
int rowOffset = 0;
int numCompressedBytes = 0;
for(int tileRow = 0; tileRow < rows; tileRow++) {
int numCompressedBytesInRow =
faxEncoder.encodeRLE(bpixels,
rowOffset, 0, tileWidth,
compressBuf);
output.write(compressBuf,
0, numCompressedBytesInRow);
rowOffset += rowStride;
numCompressedBytes += numCompressedBytesInRow;
}
tileByteCounts[tileNum++] = numCompressedBytes;
} else if(compression == COMP_GROUP3_2D) {
int numCompressedBytes =
faxEncoder.encodeT4(!T4encode2D,// 1D == !2D
T4PadEOLs,
bpixels,
(tileWidth+7)/8,
0,
tileWidth,
rows,
compressBuf);
tileByteCounts[tileNum++] = numCompressedBytes;
output.write(compressBuf, 0, numCompressedBytes);
} else if(compression == COMP_GROUP4) {
int numCompressedBytes =
faxEncoder.encodeT6(bpixels,
(tileWidth+7)/8,
0,
tileWidth,
rows,
compressBuf);
tileByteCounts[tileNum++] = numCompressedBytes;
output.write(compressBuf, 0, numCompressedBytes);
} else if(compression == COMP_PACKBITS) {
int numCompressedBytes =
compressPackBits(bpixels, rows,
(int)bytesPerRow,
compressBuf);
tileByteCounts[tileNum++] = numCompressedBytes;
output.write(compressBuf, 0, numCompressedBytes);
} else if(compression == COMP_DEFLATE) {
int numCompressedBytes =
deflate(deflater, bpixels, compressBuf);
tileByteCounts[tileNum++] = numCompressedBytes;
output.write(compressBuf, 0, numCompressedBytes);
}
break;
case 4:
index = 0;
// For each of the rows in a strip
for (int i=0; i<rows; i++) {
// Write the number of pixels that will fit into an
// even number of nibbles.
for (int j=0; j<tileWidth/2; j++) {
pixel = (pixels[index++] << 4) | pixels[index++];
bpixels[k++] = (byte)pixel;
}
// Last pixel for odd-length lines
if ((tileWidth % 2) == 1) {
pixel = pixels[index++] << 4;
bpixels[k++] = (byte)pixel;
}
}
if(compression == COMP_NONE) {
output.write(bpixels, 0, rows * ((tileWidth+1)/2));
} else if(compression == COMP_PACKBITS) {
int numCompressedBytes =
compressPackBits(bpixels, rows,
(int)bytesPerRow,
compressBuf);
tileByteCounts[tileNum++] = numCompressedBytes;
output.write(compressBuf, 0, numCompressedBytes);
} else if(compression == COMP_DEFLATE) {
int numCompressedBytes =
deflate(deflater, bpixels, compressBuf);
tileByteCounts[tileNum++] = numCompressedBytes;
output.write(compressBuf, 0, numCompressedBytes);
}
break;
case 8:
if(compression != COMP_JPEG_TTN2) {
if(useDataBuffer) {
byte[] btmp =
((DataBufferByte)src.getDataBuffer()).getData();
ComponentSampleModel csm =
(ComponentSampleModel)src.getSampleModel();
int inOffset =
csm.getOffset(col -
src.getSampleModelTranslateX(),
row -
src.getSampleModelTranslateY());
int lineStride = csm.getScanlineStride();
if(lineStride == (int)bytesPerRow) {
System.arraycopy(btmp,
inOffset,
bpixels, 0,
(int)bytesPerRow*rows);
} else {
int outOffset = 0;
for(int j = 0; j < rows; j++) {
System.arraycopy(btmp, inOffset,
bpixels, outOffset,
(int)bytesPerRow);
inOffset += lineStride;
outOffset += (int)bytesPerRow;
}
}
} else {
for (int i = 0; i < size; i++) {
bpixels[i] = (byte)pixels[i];
}
}
}
if(compression == COMP_NONE) {
output.write(bpixels, 0, size);
} else if(compression == COMP_PACKBITS) {
int numCompressedBytes =
compressPackBits(bpixels, rows,
(int)bytesPerRow,
compressBuf);
tileByteCounts[tileNum++] = numCompressedBytes;
output.write(compressBuf, 0, numCompressedBytes);
} else if(compression == COMP_JPEG_TTN2) {
long startPos = getOffset(output);
// Recreate encoder and parameters if the encoder
// is null (first data segment) or if its size
// doesn't match the current data segment.
if(jpegEncoder == null ||
jpegEncodeParam.getWidth() != src.getWidth() ||
jpegEncodeParam.getHeight() != src.getHeight()) {
jpegEncodeParam =
com.sun.image.codec.jpeg.JPEGCodec.
getDefaultJPEGEncodeParam(src, jpegColorID);
JPEGImageEncoder.modifyEncodeParam(jep,
jpegEncodeParam,
numBands);
jpegEncoder =
com.sun.image.codec.jpeg.JPEGCodec.
createJPEGEncoder(output,
jpegEncodeParam);
}
if(jpegRGBToYCbCr) {
WritableRaster wRas = null;
if(src instanceof WritableRaster) {
wRas = (WritableRaster)src;
} else {
wRas = src.createCompatibleWritableRaster();
wRas.setRect(src);
}
if (wRas.getMinX() != 0 || wRas.getMinY() != 0) {
wRas =
wRas.createWritableTranslatedChild(0, 0);
}
BufferedImage bi =
new BufferedImage(colorModel, wRas,
false, null);
jpegEncoder.encode(bi);
} else {
jpegEncoder.encode(src.createTranslatedChild(0,
0));
}
long endPos = getOffset(output);
tileByteCounts[tileNum++] = (int)(endPos - startPos);