use of javax.imageio.metadata.IIOMetadata in project imageio-ext by geosolutions-it.
the class EmptyImage method write.
private void write(IIOMetadata sm, IIOImage iioimage, ImageWriteParam p, boolean writeHeader, boolean writeData) throws IOException {
if (stream == null) {
throw new IllegalStateException("output == null!");
}
if (iioimage == null) {
throw new IllegalArgumentException("image == null!");
}
if (iioimage.hasRaster() && !canWriteRasters()) {
throw new UnsupportedOperationException("TIFF ImageWriter cannot write Rasters!");
}
this.image = iioimage.getRenderedImage();
SampleModel sampleModel = image.getSampleModel();
this.sourceXOffset = image.getMinX();
this.sourceYOffset = image.getMinY();
this.sourceWidth = image.getWidth();
this.sourceHeight = image.getHeight();
Rectangle imageBounds = new Rectangle(sourceXOffset, sourceYOffset, sourceWidth, sourceHeight);
ColorModel colorModel = null;
if (p == null) {
this.param = getDefaultWriteParam();
this.sourceBands = null;
this.periodX = 1;
this.periodY = 1;
this.numBands = sampleModel.getNumBands();
colorModel = image.getColorModel();
} else {
this.param = p;
// Get source region and subsampling factors
Rectangle sourceRegion = param.getSourceRegion();
if (sourceRegion != null) {
// Clip to actual image bounds
sourceRegion = sourceRegion.intersection(imageBounds);
sourceXOffset = sourceRegion.x;
sourceYOffset = sourceRegion.y;
sourceWidth = sourceRegion.width;
sourceHeight = sourceRegion.height;
}
// Adjust for subsampling offsets
int gridX = param.getSubsamplingXOffset();
int gridY = param.getSubsamplingYOffset();
this.sourceXOffset += gridX;
this.sourceYOffset += gridY;
this.sourceWidth -= gridX;
this.sourceHeight -= gridY;
// Get subsampling factors
this.periodX = param.getSourceXSubsampling();
this.periodY = param.getSourceYSubsampling();
int[] sBands = param.getSourceBands();
if (sBands != null) {
sourceBands = sBands;
this.numBands = sourceBands.length;
} else {
this.numBands = sampleModel.getNumBands();
}
ImageTypeSpecifier destType = p.getDestinationType();
if (destType != null) {
ColorModel cm = destType.getColorModel();
if (cm.getNumComponents() == numBands) {
colorModel = cm;
}
}
if (colorModel == null) {
colorModel = image.getColorModel();
}
}
this.imageType = new ImageTypeSpecifier(colorModel, sampleModel);
ImageUtil.canEncodeImage(this, this.imageType);
// Compute output dimensions
int destWidth = (sourceWidth + periodX - 1) / periodX;
int destHeight = (sourceHeight + periodY - 1) / periodY;
if (destWidth <= 0 || destHeight <= 0) {
throw new IllegalArgumentException("Empty source region!");
}
// this.bitDepth = 8; // XXX fix?
clearAbortRequest();
int progressStep = 1;
processImageStarted(0);
int[] sampleSize = sampleModel.getSampleSize();
long tot = 0;
for (int i = 0; i < this.numBands; i++) tot += sampleSize[i];
long sizeImage = (tot * this.sourceHeight * this.sourceWidth) / 8;
long var = 4294967296L;
boolean isForceToBigTIFF = false;
if (p instanceof TIFFImageWriteParam) {
isForceToBigTIFF = ((TIFFImageWriteParam) p).isForceToBigTIFF();
}
if (sizeImage > var || isForceToBigTIFF || isBtiff == true)
isBtiff = true;
else
isBtiff = false;
// Optionally write the header.
if (writeHeader) {
// Clear previous stream metadata.
this.streamMetadata = null;
// Try to convert non-null input stream metadata.
if (sm != null) {
this.streamMetadata = (TIFFStreamMetadata) convertStreamMetadata(sm, param);
}
// Set to default if not converted.
if (this.streamMetadata == null) {
this.streamMetadata = (TIFFStreamMetadata) getDefaultStreamMetadata(param);
}
// Write the header.
writeHeader();
// 3) Write the pointer to the first IFD after the header.
if (!isBtiff) {
stream.seek(headerPosition + 4);
nextSpace = (nextSpace + 3) & ~0x3;
stream.writeInt((int) nextSpace);
} else {
stream.seek(headerPosition + 8);
nextSpace = (nextSpace + 7) & ~0x7;
stream.writeLong(nextSpace);
}
}
// Write out the IFD and any sub IFDs, followed by a zero
// Clear previous image metadata.
this.imageMetadata = null;
// Initialize the metadata object.
IIOMetadata im = iioimage.getMetadata();
if (im != null) {
if (im instanceof TIFFImageMetadata) {
// Clone the one passed in.
this.imageMetadata = ((TIFFImageMetadata) im).getShallowClone();
} else if (Arrays.asList(im.getMetadataFormatNames()).contains(TIFFImageMetadata.nativeMetadataFormatName)) {
this.imageMetadata = convertNativeImageMetadata(im);
} else if (im.isStandardMetadataFormatSupported()) {
try {
// Convert standard metadata.
this.imageMetadata = convertStandardImageMetadata(im);
} catch (IIOInvalidTreeException e) {
// XXX Warning
}
}
}
// Use default metadata if still null.
if (this.imageMetadata == null) {
this.imageMetadata = (TIFFImageMetadata) getDefaultImageMetadata(this.imageType, this.param);
}
// Set or overwrite mandatory fields in the root IFD
setupMetadata(colorModel, sampleModel, destWidth, destHeight);
// Set compressor fields.
compressor.setWriter(this);
// Metadata needs to be set on the compressor before the IFD is
// written as the compressor could modify the metadata.
compressor.setMetadata(imageMetadata);
compressor.setStream(stream);
// Initialize scaling tables for this image
initializeScaleTables(sampleModel.getSampleSize());
// Determine whether bilevel.
this.isBilevel = ImageUtil.isBinary(this.image.getSampleModel());
// Check for photometric inversion.
this.isInverted = (nativePhotometricInterpretation == BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_BLACK_IS_ZERO && photometricInterpretation == BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_WHITE_IS_ZERO) || (nativePhotometricInterpretation == BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_WHITE_IS_ZERO && photometricInterpretation == BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_BLACK_IS_ZERO);
// Analyze image data suitability for direct copy.
this.isImageSimple = (isBilevel || (!isInverted && ImageUtil.imageIsContiguous(this.image))) && // no value rescaling
!isRescaling && // no subbanding
sourceBands == null && periodX == 1 && // no subsampling
periodY == 1 && colorConverter == null;
TIFFIFD rootIFD = imageMetadata.getRootIFD();
rootIFD.writeToStream(stream, isBtiff);
this.nextIFDPointerPos = stream.getStreamPosition();
if (!isBtiff) {
stream.writeInt(0);
} else {
stream.writeLong(0);
}
// Seek to end of IFD data
long lastIFDPosition = rootIFD.getLastPosition();
stream.seek(lastIFDPosition);
if (lastIFDPosition > this.nextSpace) {
this.nextSpace = lastIFDPosition;
}
// empty image, return.
if (!writeData) {
return;
}
// Get positions of fields within the IFD to update as we write
// each strip or tile
long stripOrTileByteCountsPosition = rootIFD.getStripOrTileByteCountsPosition();
long stripOrTileOffsetsPosition = rootIFD.getStripOrTileOffsetsPosition();
// Compute total number of pixels for progress notification
this.totalPixels = tileWidth * tileLength * tilesDown * tilesAcross;
this.pixelsDone = 0;
// Write the image, a strip or tile at a time
for (int tj = 0; tj < tilesDown; tj++) {
for (int ti = 0; ti < tilesAcross; ti++) {
long pos = stream.getStreamPosition();
// Write the (possibly compressed) tile data
Rectangle tileRect = new Rectangle(sourceXOffset + ti * tileWidth * periodX, sourceYOffset + tj * tileLength * periodY, tileWidth * periodX, tileLength * periodY);
try {
int byteCount = writeTile(tileRect, compressor);
if (pos + byteCount > nextSpace) {
nextSpace = pos + byteCount;
}
pixelsDone += tileRect.width * tileRect.height;
float currentProgress = 100.0F * pixelsDone / totalPixels;
if (currentProgress > progressStep * PROGRESS_FACTOR_MULTIPLIER) {
processImageProgress(currentProgress);
progressStep++;
}
// Fill in the offset and byte count for the file
stream.mark();
stream.seek(stripOrTileOffsetsPosition);
if (!isBtiff) {
stream.writeInt((int) pos);
stripOrTileOffsetsPosition += 4;
stream.seek(stripOrTileByteCountsPosition);
stream.writeInt(byteCount);
stripOrTileByteCountsPosition += 4;
} else {
stream.writeLong(pos);
stripOrTileOffsetsPosition += 8;
stream.seek(stripOrTileByteCountsPosition);
stream.writeLong(byteCount);
stripOrTileByteCountsPosition += 8;
}
stream.reset();
} catch (IOException e) {
throw new IIOException("I/O error writing TIFF file!", e);
}
if (abortRequested()) {
processWriteAborted();
return;
}
}
}
processImageComplete();
}
use of javax.imageio.metadata.IIOMetadata in project imageio-ext by geosolutions-it.
the class JP2BoxesTest method testBoxInfo.
// // private final static String fileName3 = "simple.jpx";
//
// private final static String fileName3 = "bogota.jp2";
// private final static String fileName2 = "example.jp2";
@org.junit.Test
public void testBoxInfo() throws IOException {
if (!runTests)
return;
File file = new File(fileName);
if (!file.exists()) {
file = TestData.file(this, fileName);
}
// File file2 = new File(fileName2);
// if (!file2.exists()) {
// file2 = TestData.file(this, fileName2);
// }
//
// File file3 = new File(fileName3);
// if (!file3.exists()) {
// file3 = TestData.file(this, fileName3);
// }
JP2KKakaduImageReader reader = new JP2KKakaduImageReader(new JP2KKakaduImageReaderSpi());
reader.setInput(file);
// visualize(reader.readAsRenderedImage(0, null), "");
IIOMetadata imageMetadata = reader.getImageMetadata(0);
IIOMetadata streamMetadata = reader.getStreamMetadata();
reader.dispose();
if (TestData.isInteractiveTest()) {
if (imageMetadata != null)
displayImageIOMetadata(imageMetadata.getAsTree(JP2KImageMetadata.nativeMetadataFormatName));
if (streamMetadata != null)
displayImageIOMetadata(streamMetadata.getAsTree(JP2KStreamMetadata.nativeMetadataFormatName));
}
// if (imageMetadata2 != null)
// displayImageIOMetadata(imageMetadata2
// .getAsTree(JP2KImageMetadata.nativeMetadataFormatName));
// if (streamMetadata2 != null)
// displayImageIOMetadata(streamMetadata2
// .getAsTree(JP2KStreamMetadata.nativeMetadataFormatName));
//
// if (imageMetadata3 != null) {
// Node treeNode = imageMetadata3
// .getAsTree(JP2KImageMetadata.nativeMetadataFormatName);
// displayImageIOMetadata(treeNode);
// }
// if (streamMetadata3 != null)
// displayImageIOMetadata(streamMetadata3
// .getAsTree(JP2KStreamMetadata.nativeMetadataFormatName));
}
use of javax.imageio.metadata.IIOMetadata in project ChatGameFontificator by GlitchCog.
the class AnimatedGifUtil method loadDittoAnimatedGif.
/**
* Fix (ditto) for Java's animated GIF interpretation
*
* Adapted from http://stackoverflow.com/questions/26801433/fix-frame-rate-of-animated-gif-in-java#answer-26829534
*
* @param url
* The URL for the animated GIF to be loaded
* @param dim
* The dimension object to be filled by the width and height of the loaded animated GIF
* @return The loaded animated GIF
* @throws Exception
*/
public static Image loadDittoAnimatedGif(final URL url, Dimension dim) {
final Image dimImage = new ImageIcon(url).getImage();
Image image = null;
try {
ImageReader gifReader = ImageIO.getImageReadersByFormatName(GIF_EXTENSION).next();
InputStream imageStream = url.openStream();
gifReader.setInput(ImageIO.createImageInputStream(imageStream));
IIOMetadata imageMetaData = gifReader.getImageMetadata(0);
String metaFormatName = imageMetaData.getNativeMetadataFormatName();
final int frameCount = gifReader.getNumImages(true);
ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream);
ImageWriter writer = ImageIO.getImageWriter(gifReader);
writer.setOutput(ios);
writer.prepareWriteSequence(null);
final int imgWidth = dimImage.getWidth(null);
final int imgHeight = dimImage.getHeight(null);
dim.setSize(imgWidth, imgHeight);
for (int i = 0; i < frameCount; i++) {
// This read method takes into account the frame's top and left coordinates
BufferedImage frame = gifReader.read(i);
IIOMetadataNode nodes = (IIOMetadataNode) gifReader.getImageMetadata(i).getAsTree(metaFormatName);
for (int j = 0; j < nodes.getLength(); j++) {
IIOMetadataNode node = (IIOMetadataNode) nodes.item(j);
if (GRAPHIC_CTRL_EXT.equalsIgnoreCase(node.getNodeName())) {
int delay = Integer.parseInt(node.getAttribute(ATTRIBUTE_DELAY_TIME));
// Minimum delay for browsers, which delay animated GIFs much more than would be to spec
if (delay < MIN_ANI_GIF_DELAY) {
node.setAttribute(ATTRIBUTE_DELAY_TIME, Integer.toString(MIN_ANI_GIF_DELAY));
}
// at least not for BTTV's (ditto)
if (node.getAttribute(ATTRIBUTE_DISPOSAL_METHOD).equals(DISPOSE_RESTORE_TO_PREVIOUS)) {
node.setAttribute(ATTRIBUTE_DISPOSAL_METHOD, DISPOSE_RESTORE_TO_BGCOLOR);
}
}
}
IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frame), null);
metadata.setFromTree(metadata.getNativeMetadataFormatName(), nodes);
// This modified frame is necessary to get the correct image placement, width, and height in the final GIF
BufferedImage frameMod = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
Graphics big = frameMod.getGraphics();
big.drawImage(frame, 0, 0, null);
IIOImage fixedFrame = new IIOImage(frameMod, null, metadata);
writer.writeToSequence(fixedFrame, writer.getDefaultWriteParam());
}
writer.endWriteSequence();
if (ios != null) {
ios.close();
}
image = Toolkit.getDefaultToolkit().createImage(baoStream.toByteArray());
} catch (Exception e) {
// If anything goes wrong, just load it normally
logger.error("Error loading animated GIF (ditto) from " + url, e);
image = new ImageIcon(url).getImage();
dim.setSize(image.getWidth(null), image.getHeight(null));
}
return image;
}
use of javax.imageio.metadata.IIOMetadata in project ChatGameFontificator by GlitchCog.
the class ControlWindow method saveScreenshot.
/**
* Takes and saves a screenshot of the current chat window
*
* @return whether the screenshot was saved
*/
private boolean saveScreenshot() {
// Take the screenshot before the save file chooser is shown
ChatPanel chat = chatWindow.getChatPanel();
BufferedImage chatImage = new BufferedImage(chat.getWidth(), chat.getHeight(), screenshotOptions.isTransparencyEnabled() ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB);
Graphics chatGraphics = chatImage.getGraphics();
chat.paint(chatGraphics);
final boolean chromaEnabled = Boolean.toString(true).equalsIgnoreCase(fProps.getProperty(FontificatorProperties.KEY_CHAT_CHROMA_ENABLED));
if (screenshotOptions.isTransparencyEnabled() && chromaEnabled) {
final int chromaKey = new Color(Integer.parseInt(fProps.getProperty(FontificatorProperties.KEY_COLOR_CHROMA_KEY), 16)).getRGB();
final int transparentPixel = new Color(0, true).getRGB();
for (int r = 0; r < chatImage.getHeight(); r++) {
for (int c = 0; c < chatImage.getWidth(); c++) {
if (chatImage.getRGB(c, r) == chromaKey) {
chatImage.setRGB(c, r, transparentPixel);
}
}
}
}
File saveFile = getTargetSaveFile(screenshotSaver, DEFAULT_SCREENSHOT_FILE_EXTENSION);
if (saveFile != null) {
try {
if (screenshotOptions.isMetadataEnabled()) {
ImageWriter writer = ImageIO.getImageWritersByFormatName("PNG").next();
ImageOutputStream stream = ImageIO.createImageOutputStream(saveFile);
writer.setOutput(stream);
IIOMetadata metadata = writer.getDefaultImageMetadata(ImageTypeSpecifier.createFromRenderedImage(chatImage), writer.getDefaultWriteParam());
IIOMetadataNode title = generateMetadataNode("Title", "CGF Screenshot");
IIOMetadataNode software = generateMetadataNode("Software", "Chat Game Fontificator");
final String fontGameName = ControlPanelFont.getFontGameName(fProps.getProperty(FontificatorProperties.KEY_FONT_FILE_FONT));
final String borderGameName = ControlPanelFont.getBorderGameName(fProps.getProperty(FontificatorProperties.KEY_FONT_FILE_BORDER));
IIOMetadataNode description = generateMetadataNode("Description", fontGameName + " Font / " + borderGameName + " Border");
IIOMetadataNode text = new IIOMetadataNode("tEXt");
text.appendChild(title);
text.appendChild(software);
text.appendChild(description);
final String metadataFormatStr = "javax_imageio_png_1.0";
IIOMetadataNode root = new IIOMetadataNode(metadataFormatStr);
root.appendChild(text);
metadata.mergeTree(metadataFormatStr, root);
writer.write(metadata, new IIOImage(chatImage, null, metadata), writer.getDefaultWriteParam());
stream.close();
} else {
ImageIO.write(chatImage, "png", saveFile);
}
return true;
} catch (Exception e) {
logger.error("Unable to save screenshot", e);
return false;
}
}
return false;
}
use of javax.imageio.metadata.IIOMetadata in project java-swing-tips by aterai.
the class MainPanel method createAnimatedGifFile.
private static File createAnimatedGifFile(List<Shape> list, Dimension size) throws IOException {
Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName("gif");
ImageWriter writer = it.hasNext() ? it.next() : null;
if (Objects.isNull(writer)) {
throw new IOException();
}
File file = File.createTempFile("anime", ".gif");
file.deleteOnExit();
try (ImageOutputStream stream = ImageIO.createImageOutputStream(file)) {
writer.setOutput(stream);
writer.prepareWriteSequence(null);
IIOMetadataNode gce = new IIOMetadataNode("GraphicControlExtension");
gce.setAttribute("disposalMethod", "none");
gce.setAttribute("userInputFlag", "FALSE");
gce.setAttribute("transparentColorFlag", "FALSE");
gce.setAttribute("transparentColorIndex", "0");
gce.setAttribute("delayTime", Objects.toString(DELAY));
IIOMetadataNode ae = new IIOMetadataNode("ApplicationExtension");
ae.setAttribute("applicationID", "NETSCAPE");
ae.setAttribute("authenticationCode", "2.0");
// last two bytes is an unsigned short (little endian) that
// indicates the number of times to loop.
// 0 means loop forever.
ae.setUserObject(new byte[] { 0x1, 0x0, 0x0 });
IIOMetadataNode aes = new IIOMetadataNode("ApplicationExtensions");
aes.appendChild(ae);
// Create animated GIF using imageio | Oracle Community
// https://community.oracle.com/thread/1264385
BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
ImageWriteParam iwp = writer.getDefaultWriteParam();
IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), iwp);
String metaFormat = metadata.getNativeMetadataFormatName();
Node root = metadata.getAsTree(metaFormat);
root.appendChild(gce);
root.appendChild(aes);
metadata.setFromTree(metaFormat, root);
// make frame
for (int i = 0; i < list.size() * DELAY; i++) {
paintFrame(image, list);
Collections.rotate(list, 1);
writeToSequence(writer, image, metadata);
metadata = null;
}
writer.endWriteSequence();
}
return file;
}
Aggregations