use of java.awt.image.DataBufferByte in project jdk8u_jdk by JetBrains.
the class WBMPImageReader method read.
public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException {
if (iis == null) {
throw new IllegalStateException(I18N.getString("WBMPImageReader1"));
}
checkIndex(imageIndex);
clearAbortRequest();
processImageStarted(imageIndex);
if (param == null)
param = getDefaultReadParam();
//read header
readHeader();
Rectangle sourceRegion = new Rectangle(0, 0, 0, 0);
Rectangle destinationRegion = new Rectangle(0, 0, 0, 0);
computeRegions(param, this.width, this.height, param.getDestination(), sourceRegion, destinationRegion);
int scaleX = param.getSourceXSubsampling();
int scaleY = param.getSourceYSubsampling();
int xOffset = param.getSubsamplingXOffset();
int yOffset = param.getSubsamplingYOffset();
// If the destination is provided, then use it. Otherwise, create new one
BufferedImage bi = param.getDestination();
if (bi == null)
bi = new BufferedImage(destinationRegion.x + destinationRegion.width, destinationRegion.y + destinationRegion.height, BufferedImage.TYPE_BYTE_BINARY);
boolean noTransform = destinationRegion.equals(new Rectangle(0, 0, width, height)) && destinationRegion.equals(new Rectangle(0, 0, bi.getWidth(), bi.getHeight()));
// Get the image data.
WritableRaster tile = bi.getWritableTile(0, 0);
// Get the SampleModel.
MultiPixelPackedSampleModel sm = (MultiPixelPackedSampleModel) bi.getSampleModel();
if (noTransform) {
if (abortRequested()) {
processReadAborted();
return bi;
}
// If noTransform is necessary, read the data.
iis.read(((DataBufferByte) tile.getDataBuffer()).getData(), 0, height * sm.getScanlineStride());
processImageUpdate(bi, 0, 0, width, height, 1, 1, new int[] { 0 });
processImageProgress(100.0F);
} else {
int len = (this.width + 7) / 8;
byte[] buf = new byte[len];
byte[] data = ((DataBufferByte) tile.getDataBuffer()).getData();
int lineStride = sm.getScanlineStride();
iis.skipBytes(len * sourceRegion.y);
int skipLength = len * (scaleY - 1);
// cache the values to avoid duplicated computation
int[] srcOff = new int[destinationRegion.width];
int[] destOff = new int[destinationRegion.width];
int[] srcPos = new int[destinationRegion.width];
int[] destPos = new int[destinationRegion.width];
for (int i = destinationRegion.x, x = sourceRegion.x, j = 0; i < destinationRegion.x + destinationRegion.width; i++, j++, x += scaleX) {
srcPos[j] = x >> 3;
srcOff[j] = 7 - (x & 7);
destPos[j] = i >> 3;
destOff[j] = 7 - (i & 7);
}
for (int j = 0, y = sourceRegion.y, k = destinationRegion.y * lineStride; j < destinationRegion.height; j++, y += scaleY) {
if (abortRequested())
break;
iis.read(buf, 0, len);
for (int i = 0; i < destinationRegion.width; i++) {
//get the bit and assign to the data buffer of the raster
int v = (buf[srcPos[i]] >> srcOff[i]) & 1;
data[k + destPos[i]] |= v << destOff[i];
}
k += lineStride;
iis.skipBytes(skipLength);
processImageUpdate(bi, 0, j, destinationRegion.width, 1, 1, 1, new int[] { 0 });
processImageProgress(100.0F * j / destinationRegion.height);
}
}
if (abortRequested())
processReadAborted();
else
processImageComplete();
return bi;
}
use of java.awt.image.DataBufferByte in project jdk8u_jdk by JetBrains.
the class WBMPImageWriter method write.
public void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException {
if (stream == null) {
throw new IllegalStateException(I18N.getString("WBMPImageWriter3"));
}
if (image == null) {
throw new IllegalArgumentException(I18N.getString("WBMPImageWriter4"));
}
clearAbortRequest();
processImageStarted(0);
if (param == null)
param = getDefaultWriteParam();
RenderedImage input = null;
Raster inputRaster = null;
boolean writeRaster = image.hasRaster();
Rectangle sourceRegion = param.getSourceRegion();
SampleModel sampleModel = null;
if (writeRaster) {
inputRaster = image.getRaster();
sampleModel = inputRaster.getSampleModel();
} else {
input = image.getRenderedImage();
sampleModel = input.getSampleModel();
inputRaster = input.getData();
}
checkSampleModel(sampleModel);
if (sourceRegion == null)
sourceRegion = inputRaster.getBounds();
else
sourceRegion = sourceRegion.intersection(inputRaster.getBounds());
if (sourceRegion.isEmpty())
throw new RuntimeException(I18N.getString("WBMPImageWriter1"));
int scaleX = param.getSourceXSubsampling();
int scaleY = param.getSourceYSubsampling();
int xOffset = param.getSubsamplingXOffset();
int yOffset = param.getSubsamplingYOffset();
sourceRegion.translate(xOffset, yOffset);
sourceRegion.width -= xOffset;
sourceRegion.height -= yOffset;
int minX = sourceRegion.x / scaleX;
int minY = sourceRegion.y / scaleY;
int w = (sourceRegion.width + scaleX - 1) / scaleX;
int h = (sourceRegion.height + scaleY - 1) / scaleY;
Rectangle destinationRegion = new Rectangle(minX, minY, w, h);
sampleModel = sampleModel.createCompatibleSampleModel(w, h);
SampleModel destSM = sampleModel;
// If the data are not formatted nominally then reformat.
if (sampleModel.getDataType() != DataBuffer.TYPE_BYTE || !(sampleModel instanceof MultiPixelPackedSampleModel) || ((MultiPixelPackedSampleModel) sampleModel).getDataBitOffset() != 0) {
destSM = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, w, h, 1, w + 7 >> 3, 0);
}
if (!destinationRegion.equals(sourceRegion)) {
if (scaleX == 1 && scaleY == 1)
inputRaster = inputRaster.createChild(inputRaster.getMinX(), inputRaster.getMinY(), w, h, minX, minY, null);
else {
WritableRaster ras = Raster.createWritableRaster(destSM, new Point(minX, minY));
byte[] data = ((DataBufferByte) ras.getDataBuffer()).getData();
for (int j = minY, y = sourceRegion.y, k = 0; j < minY + h; j++, y += scaleY) {
for (int i = 0, x = sourceRegion.x; i < w; i++, x += scaleX) {
int v = inputRaster.getSample(x, y, 0);
data[k + (i >> 3)] |= v << (7 - (i & 7));
}
k += w + 7 >> 3;
}
inputRaster = ras;
}
}
// If the data are not formatted nominally then reformat.
if (!destSM.equals(inputRaster.getSampleModel())) {
WritableRaster raster = Raster.createWritableRaster(destSM, new Point(inputRaster.getMinX(), inputRaster.getMinY()));
raster.setRect(inputRaster);
inputRaster = raster;
}
// Check whether the image is white-is-zero.
boolean isWhiteZero = false;
if (!writeRaster && input.getColorModel() instanceof IndexColorModel) {
IndexColorModel icm = (IndexColorModel) input.getColorModel();
isWhiteZero = icm.getRed(0) > icm.getRed(1);
}
// Get the line stride, bytes per row, and data array.
int lineStride = ((MultiPixelPackedSampleModel) destSM).getScanlineStride();
int bytesPerRow = (w + 7) / 8;
byte[] bdata = ((DataBufferByte) inputRaster.getDataBuffer()).getData();
// Write WBMP header.
// TypeField
stream.write(0);
// FixHeaderField
stream.write(0);
// width
stream.write(intToMultiByte(w));
// height
stream.write(intToMultiByte(h));
// Write the data.
if (!isWhiteZero && lineStride == bytesPerRow) {
// Write the entire image.
stream.write(bdata, 0, h * bytesPerRow);
processImageProgress(100.0F);
} else {
// Write the image row-by-row.
int offset = 0;
if (!isWhiteZero) {
// Black-is-zero
for (int row = 0; row < h; row++) {
if (abortRequested())
break;
stream.write(bdata, offset, bytesPerRow);
offset += lineStride;
processImageProgress(100.0F * row / h);
}
} else {
// White-is-zero: need to invert data.
byte[] inverted = new byte[bytesPerRow];
for (int row = 0; row < h; row++) {
if (abortRequested())
break;
for (int col = 0; col < bytesPerRow; col++) {
inverted[col] = (byte) (~(bdata[col + offset]));
}
stream.write(inverted, 0, bytesPerRow);
offset += lineStride;
processImageProgress(100.0F * row / h);
}
}
}
if (abortRequested())
processWriteAborted();
else {
processImageComplete();
stream.flushBefore(stream.getStreamPosition());
}
}
use of java.awt.image.DataBufferByte in project jdk8u_jdk by JetBrains.
the class JPEGImageWriter method writeOnThread.
private void writeOnThread(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException {
if (ios == null) {
throw new IllegalStateException("Output has not been set!");
}
if (image == null) {
throw new IllegalArgumentException("image is null!");
}
// if streamMetadata is not null, issue a warning
if (streamMetadata != null) {
warningOccurred(WARNING_STREAM_METADATA_IGNORED);
}
// Obtain the raster and image, if there is one
boolean rasterOnly = image.hasRaster();
RenderedImage rimage = null;
if (rasterOnly) {
srcRas = image.getRaster();
} else {
rimage = image.getRenderedImage();
if (rimage instanceof BufferedImage) {
// Use the Raster directly.
srcRas = ((BufferedImage) rimage).getRaster();
} else if (rimage.getNumXTiles() == 1 && rimage.getNumYTiles() == 1) {
// Get the unique tile.
srcRas = rimage.getTile(rimage.getMinTileX(), rimage.getMinTileY());
// as the tile dimensions might differ.
if (srcRas.getWidth() != rimage.getWidth() || srcRas.getHeight() != rimage.getHeight()) {
srcRas = srcRas.createChild(srcRas.getMinX(), srcRas.getMinY(), rimage.getWidth(), rimage.getHeight(), srcRas.getMinX(), srcRas.getMinY(), null);
}
} else {
// Image is tiled so get a contiguous raster by copying.
srcRas = rimage.getData();
}
}
// Now determine if we are using a band subset
// By default, we are using all source bands
int numSrcBands = srcRas.getNumBands();
indexed = false;
indexCM = null;
ColorModel cm = null;
ColorSpace cs = null;
isAlphaPremultiplied = false;
srcCM = null;
if (!rasterOnly) {
cm = rimage.getColorModel();
if (cm != null) {
cs = cm.getColorSpace();
if (cm instanceof IndexColorModel) {
indexed = true;
indexCM = (IndexColorModel) cm;
numSrcBands = cm.getNumComponents();
}
if (cm.isAlphaPremultiplied()) {
isAlphaPremultiplied = true;
srcCM = cm;
}
}
}
srcBands = JPEG.bandOffsets[numSrcBands - 1];
int numBandsUsed = numSrcBands;
if (param != null) {
int[] sBands = param.getSourceBands();
if (sBands != null) {
if (indexed) {
warningOccurred(WARNING_NO_BANDS_ON_INDEXED);
} else {
srcBands = sBands;
numBandsUsed = srcBands.length;
if (numBandsUsed > numSrcBands) {
throw new IIOException("ImageWriteParam specifies too many source bands");
}
}
}
}
boolean usingBandSubset = (numBandsUsed != numSrcBands);
boolean fullImage = ((!rasterOnly) && (!usingBandSubset));
int[] bandSizes = null;
if (!indexed) {
bandSizes = srcRas.getSampleModel().getSampleSize();
// If this is a subset, we must adjust bandSizes
if (usingBandSubset) {
int[] temp = new int[numBandsUsed];
for (int i = 0; i < numBandsUsed; i++) {
temp[i] = bandSizes[srcBands[i]];
}
bandSizes = temp;
}
} else {
int[] tempSize = srcRas.getSampleModel().getSampleSize();
bandSizes = new int[numSrcBands];
for (int i = 0; i < numSrcBands; i++) {
// All the same
bandSizes[i] = tempSize[0];
}
}
for (int i = 0; i < bandSizes.length; i++) {
// per sample.
if (bandSizes[i] <= 0 || bandSizes[i] > 8) {
throw new IIOException("Illegal band size: should be 0 < size <= 8");
}
// to 8-bit.
if (indexed) {
bandSizes[i] = 8;
}
}
if (debug) {
System.out.println("numSrcBands is " + numSrcBands);
System.out.println("numBandsUsed is " + numBandsUsed);
System.out.println("usingBandSubset is " + usingBandSubset);
System.out.println("fullImage is " + fullImage);
System.out.print("Band sizes:");
for (int i = 0; i < bandSizes.length; i++) {
System.out.print(" " + bandSizes[i]);
}
System.out.println();
}
// Destination type, if there is one
ImageTypeSpecifier destType = null;
if (param != null) {
destType = param.getDestinationType();
// Ignore dest type if we are writing a complete image
if ((fullImage) && (destType != null)) {
warningOccurred(WARNING_DEST_IGNORED);
destType = null;
}
}
// Examine the param
sourceXOffset = srcRas.getMinX();
sourceYOffset = srcRas.getMinY();
int imageWidth = srcRas.getWidth();
int imageHeight = srcRas.getHeight();
sourceWidth = imageWidth;
sourceHeight = imageHeight;
int periodX = 1;
int periodY = 1;
int gridX = 0;
int gridY = 0;
JPEGQTable[] qTables = null;
JPEGHuffmanTable[] DCHuffmanTables = null;
JPEGHuffmanTable[] ACHuffmanTables = null;
boolean optimizeHuffman = false;
JPEGImageWriteParam jparam = null;
int progressiveMode = ImageWriteParam.MODE_DISABLED;
if (param != null) {
Rectangle sourceRegion = param.getSourceRegion();
if (sourceRegion != null) {
Rectangle imageBounds = new Rectangle(sourceXOffset, sourceYOffset, sourceWidth, sourceHeight);
sourceRegion = sourceRegion.intersection(imageBounds);
sourceXOffset = sourceRegion.x;
sourceYOffset = sourceRegion.y;
sourceWidth = sourceRegion.width;
sourceHeight = sourceRegion.height;
}
if (sourceWidth + sourceXOffset > imageWidth) {
sourceWidth = imageWidth - sourceXOffset;
}
if (sourceHeight + sourceYOffset > imageHeight) {
sourceHeight = imageHeight - sourceYOffset;
}
periodX = param.getSourceXSubsampling();
periodY = param.getSourceYSubsampling();
gridX = param.getSubsamplingXOffset();
gridY = param.getSubsamplingYOffset();
switch(param.getCompressionMode()) {
case ImageWriteParam.MODE_DISABLED:
throw new IIOException("JPEG compression cannot be disabled");
case ImageWriteParam.MODE_EXPLICIT:
float quality = param.getCompressionQuality();
quality = JPEG.convertToLinearQuality(quality);
qTables = new JPEGQTable[2];
qTables[0] = JPEGQTable.K1Luminance.getScaledInstance(quality, true);
qTables[1] = JPEGQTable.K2Chrominance.getScaledInstance(quality, true);
break;
case ImageWriteParam.MODE_DEFAULT:
qTables = new JPEGQTable[2];
qTables[0] = JPEGQTable.K1Div2Luminance;
qTables[1] = JPEGQTable.K2Div2Chrominance;
break;
}
progressiveMode = param.getProgressiveMode();
if (param instanceof JPEGImageWriteParam) {
jparam = (JPEGImageWriteParam) param;
optimizeHuffman = jparam.getOptimizeHuffmanTables();
}
}
// Now examine the metadata
IIOMetadata mdata = image.getMetadata();
if (mdata != null) {
if (mdata instanceof JPEGMetadata) {
metadata = (JPEGMetadata) mdata;
if (debug) {
System.out.println("We have metadata, and it's JPEG metadata");
}
} else {
if (!rasterOnly) {
ImageTypeSpecifier type = destType;
if (type == null) {
type = new ImageTypeSpecifier(rimage);
}
metadata = (JPEGMetadata) convertImageMetadata(mdata, type, param);
} else {
warningOccurred(WARNING_METADATA_NOT_JPEG_FOR_RASTER);
}
}
}
// First set a default state
// If it's there, use it
ignoreJFIF = false;
// If it's there, use it
ignoreAdobe = false;
// Change if needed
newAdobeTransform = JPEG.ADOBE_IMPOSSIBLE;
writeDefaultJFIF = false;
writeAdobe = false;
// By default we'll do no conversion:
int inCsType = JPEG.JCS_UNKNOWN;
int outCsType = JPEG.JCS_UNKNOWN;
JFIFMarkerSegment jfif = null;
AdobeMarkerSegment adobe = null;
SOFMarkerSegment sof = null;
if (metadata != null) {
jfif = (JFIFMarkerSegment) metadata.findMarkerSegment(JFIFMarkerSegment.class, true);
adobe = (AdobeMarkerSegment) metadata.findMarkerSegment(AdobeMarkerSegment.class, true);
sof = (SOFMarkerSegment) metadata.findMarkerSegment(SOFMarkerSegment.class, true);
}
// By default don't write one
iccProfile = null;
// PhotoYCC does this
convertTosRGB = false;
converted = null;
if (destType != null) {
if (numBandsUsed != destType.getNumBands()) {
throw new IIOException("Number of source bands != number of destination bands");
}
cs = destType.getColorModel().getColorSpace();
// Check the metadata against the destination type
if (metadata != null) {
checkSOFBands(sof, numBandsUsed);
checkJFIF(jfif, destType, false);
// Do we want to write an ICC profile?
if ((jfif != null) && (ignoreJFIF == false)) {
if (JPEG.isNonStandardICC(cs)) {
iccProfile = ((ICC_ColorSpace) cs).getProfile();
}
}
checkAdobe(adobe, destType, false);
} else {
// If we can add a JFIF or an Adobe marker segment, do so
if (JPEG.isJFIFcompliant(destType, false)) {
writeDefaultJFIF = true;
// Do we want to write an ICC profile?
if (JPEG.isNonStandardICC(cs)) {
iccProfile = ((ICC_ColorSpace) cs).getProfile();
}
} else {
int transform = JPEG.transformForType(destType, false);
if (transform != JPEG.ADOBE_IMPOSSIBLE) {
writeAdobe = true;
newAdobeTransform = transform;
}
}
// re-create the metadata
metadata = new JPEGMetadata(destType, null, this);
}
inCsType = getSrcCSType(destType);
outCsType = getDefaultDestCSType(destType);
} else {
// no destination type
if (metadata == null) {
if (fullImage) {
// no dest, no metadata, full image
// Use default metadata matching the image and param
metadata = new JPEGMetadata(new ImageTypeSpecifier(rimage), param, this);
if (metadata.findMarkerSegment(JFIFMarkerSegment.class, true) != null) {
cs = rimage.getColorModel().getColorSpace();
if (JPEG.isNonStandardICC(cs)) {
iccProfile = ((ICC_ColorSpace) cs).getProfile();
}
}
inCsType = getSrcCSType(rimage);
outCsType = getDefaultDestCSType(rimage);
}
// else no dest, no metadata, not an image,
// so no special headers, no color conversion
} else {
// no dest type, but there is metadata
checkSOFBands(sof, numBandsUsed);
if (fullImage) {
// no dest, metadata, image
// Check that the metadata and the image match
ImageTypeSpecifier inputType = new ImageTypeSpecifier(rimage);
inCsType = getSrcCSType(rimage);
if (cm != null) {
boolean alpha = cm.hasAlpha();
switch(cs.getType()) {
case ColorSpace.TYPE_GRAY:
if (!alpha) {
outCsType = JPEG.JCS_GRAYSCALE;
} else {
if (jfif != null) {
ignoreJFIF = true;
warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
}
// out colorspace remains unknown
}
if ((adobe != null) && (adobe.transform != JPEG.ADOBE_UNKNOWN)) {
newAdobeTransform = JPEG.ADOBE_UNKNOWN;
warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
}
break;
case ColorSpace.TYPE_RGB:
if (!alpha) {
if (jfif != null) {
outCsType = JPEG.JCS_YCbCr;
if (JPEG.isNonStandardICC(cs) || ((cs instanceof ICC_ColorSpace) && (jfif.iccSegment != null))) {
iccProfile = ((ICC_ColorSpace) cs).getProfile();
}
} else if (adobe != null) {
switch(adobe.transform) {
case JPEG.ADOBE_UNKNOWN:
outCsType = JPEG.JCS_RGB;
break;
case JPEG.ADOBE_YCC:
outCsType = JPEG.JCS_YCbCr;
break;
default:
warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
newAdobeTransform = JPEG.ADOBE_UNKNOWN;
outCsType = JPEG.JCS_RGB;
break;
}
} else {
// consult the ids
int outCS = sof.getIDencodedCSType();
// consult the sampling factors
if (outCS != JPEG.JCS_UNKNOWN) {
outCsType = outCS;
} else {
boolean subsampled = isSubsampled(sof.componentSpecs);
if (subsampled) {
outCsType = JPEG.JCS_YCbCr;
} else {
outCsType = JPEG.JCS_RGB;
}
}
}
} else {
// RGBA
if (jfif != null) {
ignoreJFIF = true;
warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
}
if (adobe != null) {
if (adobe.transform != JPEG.ADOBE_UNKNOWN) {
newAdobeTransform = JPEG.ADOBE_UNKNOWN;
warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
}
outCsType = JPEG.JCS_RGBA;
} else {
// consult the ids
int outCS = sof.getIDencodedCSType();
// consult the sampling factors
if (outCS != JPEG.JCS_UNKNOWN) {
outCsType = outCS;
} else {
boolean subsampled = isSubsampled(sof.componentSpecs);
outCsType = subsampled ? JPEG.JCS_YCbCrA : JPEG.JCS_RGBA;
}
}
}
break;
case ColorSpace.TYPE_3CLR:
if (cs == JPEG.JCS.getYCC()) {
if (!alpha) {
if (jfif != null) {
convertTosRGB = true;
convertOp = new ColorConvertOp(cs, JPEG.JCS.sRGB, null);
outCsType = JPEG.JCS_YCbCr;
} else if (adobe != null) {
if (adobe.transform != JPEG.ADOBE_YCC) {
newAdobeTransform = JPEG.ADOBE_YCC;
warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
}
outCsType = JPEG.JCS_YCC;
} else {
outCsType = JPEG.JCS_YCC;
}
} else {
// PhotoYCCA
if (jfif != null) {
ignoreJFIF = true;
warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
} else if (adobe != null) {
if (adobe.transform != JPEG.ADOBE_UNKNOWN) {
newAdobeTransform = JPEG.ADOBE_UNKNOWN;
warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
}
}
outCsType = JPEG.JCS_YCCA;
}
}
}
}
}
// else no dest, metadata, not an image. Defaults ok
}
}
boolean metadataProgressive = false;
int[] scans = null;
if (metadata != null) {
if (sof == null) {
sof = (SOFMarkerSegment) metadata.findMarkerSegment(SOFMarkerSegment.class, true);
}
if ((sof != null) && (sof.tag == JPEG.SOF2)) {
metadataProgressive = true;
if (progressiveMode == ImageWriteParam.MODE_COPY_FROM_METADATA) {
// Might still be null
scans = collectScans(metadata, sof);
} else {
numScans = 0;
}
}
if (jfif == null) {
jfif = (JFIFMarkerSegment) metadata.findMarkerSegment(JFIFMarkerSegment.class, true);
}
}
thumbnails = image.getThumbnails();
int numThumbs = image.getNumThumbnails();
forceJFIF = false;
// then thumbnails can be written
if (!writeDefaultJFIF) {
// If there is no metadata, then we can't write thumbnails
if (metadata == null) {
thumbnails = null;
if (numThumbs != 0) {
warningOccurred(WARNING_IGNORING_THUMBS);
}
} else {
// then the user must specify JFIF on the metadata
if (fullImage == false) {
if (jfif == null) {
// Or we can't include thumbnails
thumbnails = null;
if (numThumbs != 0) {
warningOccurred(WARNING_IGNORING_THUMBS);
}
}
} else {
// It is a full image, and there is metadata
if (jfif == null) {
// Can it have JFIF?
if ((outCsType == JPEG.JCS_GRAYSCALE) || (outCsType == JPEG.JCS_YCbCr)) {
if (numThumbs != 0) {
forceJFIF = true;
warningOccurred(WARNING_FORCING_JFIF);
}
} else {
// Nope, not JFIF-compatible
thumbnails = null;
if (numThumbs != 0) {
warningOccurred(WARNING_IGNORING_THUMBS);
}
}
}
}
}
}
// Set up a boolean to indicate whether we need to call back to
// write metadata
boolean haveMetadata = ((metadata != null) || writeDefaultJFIF || writeAdobe);
// Now that we have dealt with metadata, finalize our tables set up
// Are we going to write tables? By default, yes.
boolean writeDQT = true;
boolean writeDHT = true;
// But if the metadata has no tables, no.
DQTMarkerSegment dqt = null;
DHTMarkerSegment dht = null;
int restartInterval = 0;
if (metadata != null) {
dqt = (DQTMarkerSegment) metadata.findMarkerSegment(DQTMarkerSegment.class, true);
dht = (DHTMarkerSegment) metadata.findMarkerSegment(DHTMarkerSegment.class, true);
DRIMarkerSegment dri = (DRIMarkerSegment) metadata.findMarkerSegment(DRIMarkerSegment.class, true);
if (dri != null) {
restartInterval = dri.restartInterval;
}
if (dqt == null) {
writeDQT = false;
}
if (dht == null) {
// Ignored if optimizeHuffman is true
writeDHT = false;
}
}
// to use
if (qTables == null) {
// Get them from metadata, or use defaults
if (dqt != null) {
qTables = collectQTablesFromMetadata(metadata);
} else if (streamQTables != null) {
qTables = streamQTables;
} else if ((jparam != null) && (jparam.areTablesSet())) {
qTables = jparam.getQTables();
} else {
qTables = JPEG.getDefaultQTables();
}
}
// If we are optimizing, we don't want any tables.
if (optimizeHuffman == false) {
// If they were for progressive scans, we can't use them.
if ((dht != null) && (metadataProgressive == false)) {
DCHuffmanTables = collectHTablesFromMetadata(metadata, true);
ACHuffmanTables = collectHTablesFromMetadata(metadata, false);
} else if (streamDCHuffmanTables != null) {
DCHuffmanTables = streamDCHuffmanTables;
ACHuffmanTables = streamACHuffmanTables;
} else if ((jparam != null) && (jparam.areTablesSet())) {
DCHuffmanTables = jparam.getDCHuffmanTables();
ACHuffmanTables = jparam.getACHuffmanTables();
} else {
DCHuffmanTables = JPEG.getDefaultHuffmanTables(true);
ACHuffmanTables = JPEG.getDefaultHuffmanTables(false);
}
}
// By default, ids are 1 - N, no subsampling
int[] componentIds = new int[numBandsUsed];
int[] HsamplingFactors = new int[numBandsUsed];
int[] VsamplingFactors = new int[numBandsUsed];
int[] QtableSelectors = new int[numBandsUsed];
for (int i = 0; i < numBandsUsed; i++) {
// JFIF compatible
componentIds[i] = i + 1;
HsamplingFactors[i] = 1;
VsamplingFactors[i] = 1;
QtableSelectors[i] = 0;
}
// Now override them with the contents of sof, if there is one,
if (sof != null) {
for (int i = 0; i < numBandsUsed; i++) {
if (forceJFIF == false) {
// else use JFIF-compatible default
componentIds[i] = sof.componentSpecs[i].componentId;
}
HsamplingFactors[i] = sof.componentSpecs[i].HsamplingFactor;
VsamplingFactors[i] = sof.componentSpecs[i].VsamplingFactor;
QtableSelectors[i] = sof.componentSpecs[i].QtableSelector;
}
}
sourceXOffset += gridX;
sourceWidth -= gridX;
sourceYOffset += gridY;
sourceHeight -= gridY;
int destWidth = (sourceWidth + periodX - 1) / periodX;
int destHeight = (sourceHeight + periodY - 1) / periodY;
// Create an appropriate 1-line databuffer for writing
int lineSize = sourceWidth * numBandsUsed;
DataBufferByte buffer = new DataBufferByte(lineSize);
// Create a raster from that
int[] bandOffs = JPEG.bandOffsets[numBandsUsed - 1];
raster = Raster.createInterleavedRaster(buffer, sourceWidth, 1, lineSize, numBandsUsed, bandOffs, null);
// Call the writer, who will call back for every scanline
clearAbortRequest();
cbLock.lock();
try {
processImageStarted(currentImage);
} finally {
cbLock.unlock();
}
boolean aborted = false;
if (debug) {
System.out.println("inCsType: " + inCsType);
System.out.println("outCsType: " + outCsType);
}
// Note that getData disables acceleration on buffer, but it is
// just a 1-line intermediate data transfer buffer that does not
// affect the acceleration of the source image.
aborted = writeImage(structPointer, buffer.getData(), inCsType, outCsType, numBandsUsed, bandSizes, sourceWidth, destWidth, destHeight, periodX, periodY, qTables, writeDQT, DCHuffmanTables, ACHuffmanTables, writeDHT, optimizeHuffman, (progressiveMode != ImageWriteParam.MODE_DISABLED), numScans, scans, componentIds, HsamplingFactors, VsamplingFactors, QtableSelectors, haveMetadata, restartInterval);
cbLock.lock();
try {
if (aborted) {
processWriteAborted();
} else {
processImageComplete();
}
ios.flush();
} finally {
cbLock.unlock();
}
// After a successful write
currentImage++;
}
use of java.awt.image.DataBufferByte in project jdk8u_jdk by JetBrains.
the class ImageTypeProducer method readInternal.
private Raster readInternal(int imageIndex, ImageReadParam param, boolean wantRaster) throws IOException {
readHeader(imageIndex, false);
WritableRaster imRas = null;
int numImageBands = 0;
if (!wantRaster) {
// Can we read this image?
Iterator imageTypes = getImageTypes(imageIndex);
if (imageTypes.hasNext() == false) {
throw new IIOException("Unsupported Image Type");
}
image = getDestination(param, imageTypes, width, height);
imRas = image.getRaster();
// The destination may still be incompatible.
numImageBands = image.getSampleModel().getNumBands();
// Check whether we can handle any implied color conversion
// Throws IIOException if the stream and the image are
// incompatible, and sets convert if a java conversion
// is necessary
checkColorConversion(image, param);
// Check the source and destination bands in the param
checkReadParamBandSettings(param, numComponents, numImageBands);
} else {
// Set the output color space equal to the input colorspace
// This disables all conversions
setOutColorSpace(structPointer, colorSpaceCode);
image = null;
}
// Create an intermediate 1-line Raster that will hold the decoded,
// subsampled, clipped, band-selected image data in a single
// byte-interleaved buffer. The above transformations
// will occur in C for performance. Every time this Raster
// is filled we will call back to acceptPixels below to copy
// this to whatever kind of buffer our image has.
int[] srcBands = JPEG.bandOffsets[numComponents - 1];
int numRasterBands = (wantRaster ? numComponents : numImageBands);
destinationBands = null;
Rectangle srcROI = new Rectangle(0, 0, 0, 0);
destROI = new Rectangle(0, 0, 0, 0);
computeRegions(param, width, height, image, srcROI, destROI);
int periodX = 1;
int periodY = 1;
minProgressivePass = 0;
maxProgressivePass = Integer.MAX_VALUE;
if (param != null) {
periodX = param.getSourceXSubsampling();
periodY = param.getSourceYSubsampling();
int[] sBands = param.getSourceBands();
if (sBands != null) {
srcBands = sBands;
numRasterBands = srcBands.length;
}
if (!wantRaster) {
// ignore dest bands for Raster
destinationBands = param.getDestinationBands();
}
minProgressivePass = param.getSourceMinProgressivePass();
maxProgressivePass = param.getSourceMaxProgressivePass();
if (param instanceof JPEGImageReadParam) {
JPEGImageReadParam jparam = (JPEGImageReadParam) param;
if (jparam.areTablesSet()) {
abbrevQTables = jparam.getQTables();
abbrevDCHuffmanTables = jparam.getDCHuffmanTables();
abbrevACHuffmanTables = jparam.getACHuffmanTables();
}
}
}
int lineSize = destROI.width * numRasterBands;
buffer = new DataBufferByte(lineSize);
int[] bandOffs = JPEG.bandOffsets[numRasterBands - 1];
raster = Raster.createInterleavedRaster(buffer, destROI.width, 1, lineSize, numRasterBands, bandOffs, null);
// target Raster that will permit a simple setRect for each scanline
if (wantRaster) {
target = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, destROI.width, destROI.height, lineSize, numRasterBands, bandOffs, null);
} else {
target = imRas;
}
int[] bandSizes = target.getSampleModel().getSampleSize();
for (int i = 0; i < bandSizes.length; i++) {
if (bandSizes[i] <= 0 || bandSizes[i] > 8) {
throw new IIOException("Illegal band size: should be 0 < size <= 8");
}
}
/*
* If the process is sequential, and we have restart markers,
* we could skip to the correct restart marker, if the library
* lets us. That's an optimization to investigate later.
*/
// Check for update listeners (don't call back if none)
boolean callbackUpdates = ((updateListeners != null) || (progressListeners != null));
// Set up progression data
initProgressData();
// and set knownPassCount
if (imageIndex == imageMetadataIndex) {
// We have metadata
knownPassCount = 0;
for (Iterator iter = imageMetadata.markerSequence.iterator(); iter.hasNext(); ) {
if (iter.next() instanceof SOSMarkerSegment) {
knownPassCount++;
}
}
}
progInterval = Math.max((target.getHeight() - 1) / 20, 1);
if (knownPassCount > 0) {
progInterval *= knownPassCount;
} else if (maxProgressivePass != Integer.MAX_VALUE) {
progInterval *= (maxProgressivePass - minProgressivePass + 1);
}
if (debug) {
System.out.println("**** Read Data *****");
System.out.println("numRasterBands is " + numRasterBands);
System.out.print("srcBands:");
for (int i = 0; i < srcBands.length; i++) System.out.print(" " + srcBands[i]);
System.out.println();
System.out.println("destination bands is " + destinationBands);
if (destinationBands != null) {
for (int i = 0; i < destinationBands.length; i++) {
System.out.print(" " + destinationBands[i]);
}
System.out.println();
}
System.out.println("sourceROI is " + srcROI);
System.out.println("destROI is " + destROI);
System.out.println("periodX is " + periodX);
System.out.println("periodY is " + periodY);
System.out.println("minProgressivePass is " + minProgressivePass);
System.out.println("maxProgressivePass is " + maxProgressivePass);
System.out.println("callbackUpdates is " + callbackUpdates);
}
// Finally, we are ready to read
processImageStarted(currentImage);
boolean aborted = false;
// Note that getData disables acceleration on buffer, but it is
// just a 1-line intermediate data transfer buffer that will not
// affect the acceleration of the resulting image.
aborted = readImage(structPointer, buffer.getData(), numRasterBands, srcBands, bandSizes, srcROI.x, srcROI.y, srcROI.width, srcROI.height, periodX, periodY, abbrevQTables, abbrevDCHuffmanTables, abbrevACHuffmanTables, minProgressivePass, maxProgressivePass, callbackUpdates);
if (aborted) {
processReadAborted();
} else {
processImageComplete();
}
return target;
}
use of java.awt.image.DataBufferByte in project jdk8u_jdk by JetBrains.
the class IncorrectClipXorModeSW2Surface method getBufferedImage.
private static BufferedImage getBufferedImage(int sw) {
final BufferedImage bi = new BufferedImage(sw, sw, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bi.createGraphics();
g2d.setColor(Color.RED);
g2d.fillRect(0, 0, sw, sw);
g2d.dispose();
final DataBuffer db = bi.getRaster().getDataBuffer();
if (db instanceof DataBufferInt) {
((DataBufferInt) db).getData();
} else if (db instanceof DataBufferShort) {
((DataBufferShort) db).getData();
} else if (db instanceof DataBufferByte) {
((DataBufferByte) db).getData();
} else {
try {
bi.setAccelerationPriority(0.0f);
} catch (final Throwable ignored) {
}
}
return bi;
}
Aggregations