use of javax.imageio.metadata.IIOMetadata in project ultimate-java by pantinor.
the class PackImagesUtil method readGif.
private static ImageFrame[] readGif(File file) throws IOException {
ArrayList<ImageFrame> frames = new ArrayList<>(2);
ImageReader reader = (ImageReader) ImageIO.getImageReadersByFormatName("gif").next();
reader.setInput(ImageIO.createImageInputStream(file));
int lastx = 0;
int lasty = 0;
int width = -1;
int height = -1;
IIOMetadata metadata = reader.getStreamMetadata();
Color backgroundColor = null;
if (metadata != null) {
IIOMetadataNode globalRoot = (IIOMetadataNode) metadata.getAsTree(metadata.getNativeMetadataFormatName());
NodeList globalColorTable = globalRoot.getElementsByTagName("GlobalColorTable");
NodeList globalScreeDescriptor = globalRoot.getElementsByTagName("LogicalScreenDescriptor");
if (globalScreeDescriptor != null && globalScreeDescriptor.getLength() > 0) {
IIOMetadataNode screenDescriptor = (IIOMetadataNode) globalScreeDescriptor.item(0);
if (screenDescriptor != null) {
width = Integer.parseInt(screenDescriptor.getAttribute("logicalScreenWidth"));
height = Integer.parseInt(screenDescriptor.getAttribute("logicalScreenHeight"));
}
}
if (globalColorTable != null && globalColorTable.getLength() > 0) {
IIOMetadataNode colorTable = (IIOMetadataNode) globalColorTable.item(0);
if (colorTable != null) {
String bgIndex = colorTable.getAttribute("backgroundColorIndex");
IIOMetadataNode colorEntry = (IIOMetadataNode) colorTable.getFirstChild();
while (colorEntry != null) {
if (colorEntry.getAttribute("index").equals(bgIndex)) {
int red = Integer.parseInt(colorEntry.getAttribute("red"));
int green = Integer.parseInt(colorEntry.getAttribute("green"));
int blue = Integer.parseInt(colorEntry.getAttribute("blue"));
backgroundColor = new Color(red, green, blue);
break;
}
colorEntry = (IIOMetadataNode) colorEntry.getNextSibling();
}
}
}
}
BufferedImage master = null;
boolean hasBackround = false;
for (int frameIndex = 0; ; frameIndex++) {
BufferedImage image;
try {
image = reader.read(frameIndex);
} catch (IndexOutOfBoundsException io) {
break;
}
if (width == -1 || height == -1) {
width = image.getWidth();
height = image.getHeight();
}
IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(frameIndex).getAsTree("javax_imageio_gif_image_1.0");
IIOMetadataNode gce = (IIOMetadataNode) root.getElementsByTagName("GraphicControlExtension").item(0);
NodeList children = root.getChildNodes();
int delay = Integer.valueOf(gce.getAttribute("delayTime"));
String disposal = gce.getAttribute("disposalMethod");
if (master == null) {
master = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
master.createGraphics().setColor(backgroundColor);
master.createGraphics().fillRect(0, 0, master.getWidth(), master.getHeight());
hasBackround = image.getWidth() == width && image.getHeight() == height;
master.createGraphics().drawImage(image, 0, 0, null);
} else {
int x = 0;
int y = 0;
for (int nodeIndex = 0; nodeIndex < children.getLength(); nodeIndex++) {
Node nodeItem = children.item(nodeIndex);
if (nodeItem.getNodeName().equals("ImageDescriptor")) {
NamedNodeMap map = nodeItem.getAttributes();
x = Integer.valueOf(map.getNamedItem("imageLeftPosition").getNodeValue());
y = Integer.valueOf(map.getNamedItem("imageTopPosition").getNodeValue());
}
}
if (disposal.equals("restoreToPrevious")) {
BufferedImage from = null;
for (int i = frameIndex - 1; i >= 0; i--) {
if (!frames.get(i).getDisposal().equals("restoreToPrevious") || frameIndex == 0) {
from = frames.get(i).getImage();
break;
}
}
{
ColorModel model = from.getColorModel();
boolean alpha = from.isAlphaPremultiplied();
WritableRaster raster = from.copyData(null);
master = new BufferedImage(model, raster, alpha, null);
}
} else if (disposal.equals("restoreToBackgroundColor") && backgroundColor != null) {
if (!hasBackround || frameIndex > 1) {
master.createGraphics().fillRect(lastx, lasty, frames.get(frameIndex - 1).getWidth(), frames.get(frameIndex - 1).getHeight());
}
}
master.createGraphics().drawImage(image, x, y, null);
lastx = x;
lasty = y;
}
{
BufferedImage copy;
{
ColorModel model = master.getColorModel();
boolean alpha = master.isAlphaPremultiplied();
WritableRaster raster = master.copyData(null);
copy = new BufferedImage(model, raster, alpha, null);
}
frames.add(new ImageFrame(copy, delay, disposal, image.getWidth(), image.getHeight()));
}
master.flush();
}
reader.dispose();
return frames.toArray(new ImageFrame[frames.size()]);
}
use of javax.imageio.metadata.IIOMetadata in project pdfbox by apache.
the class JPEGFactory method encodeImageToJPEGStream.
private static void encodeImageToJPEGStream(BufferedImage image, float quality, int dpi, OutputStream out) throws IOException {
// encode to JPEG
ImageOutputStream ios = null;
ImageWriter imageWriter = null;
try {
// find JAI writer
imageWriter = getJPEGImageWriter();
ios = ImageIO.createImageOutputStream(out);
imageWriter.setOutput(ios);
// add compression
JPEGImageWriteParam jpegParam = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
jpegParam.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
jpegParam.setCompressionQuality(quality);
// add metadata
ImageTypeSpecifier imageTypeSpecifier = new ImageTypeSpecifier(image);
IIOMetadata data = imageWriter.getDefaultImageMetadata(imageTypeSpecifier, jpegParam);
Element tree = (Element) data.getAsTree("javax_imageio_jpeg_image_1.0");
Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
jfif.setAttribute("Xdensity", Integer.toString(dpi));
jfif.setAttribute("Ydensity", Integer.toString(dpi));
// 1 = dots/inch
jfif.setAttribute("resUnits", "1");
// write
imageWriter.write(data, new IIOImage(image, null, null), jpegParam);
} finally {
// clean up
IOUtils.closeQuietly(out);
if (ios != null) {
ios.close();
}
if (imageWriter != null) {
imageWriter.dispose();
}
}
}
use of javax.imageio.metadata.IIOMetadata in project pdfbox by apache.
the class TestImageIOUtils method checkResolution.
/**
* checks whether the resolution of an image file is as expected.
*
* @param filename the name of the file
* @param expectedResolution the expected resolution
*
* @throws IOException if something goes wrong
*/
private void checkResolution(String filename, int expectedResolution) throws IOException {
assertFalse("Empty file " + filename, new File(filename).length() == 0);
String suffix = filename.substring(filename.lastIndexOf('.') + 1);
if ("BMP".equals(suffix.toUpperCase())) {
// BMP reader doesn't work
checkBmpResolution(filename, expectedResolution);
return;
}
Iterator readers = ImageIO.getImageReadersBySuffix(suffix);
assertTrue("No image reader found for suffix " + suffix, readers.hasNext());
ImageReader reader = (ImageReader) readers.next();
try (ImageInputStream iis = ImageIO.createImageInputStream(new File(filename))) {
assertNotNull("No ImageInputStream created for file " + filename, iis);
reader.setInput(iis);
IIOMetadata imageMetadata = reader.getImageMetadata(0);
Element root = (Element) imageMetadata.getAsTree(STANDARD_METADATA_FORMAT);
NodeList dimensionNodes = root.getElementsByTagName("Dimension");
assertTrue("No resolution found in image file " + filename, dimensionNodes.getLength() > 0);
Element dimensionElement = (Element) dimensionNodes.item(0);
NodeList pixelSizeNodes = dimensionElement.getElementsByTagName("HorizontalPixelSize");
assertTrue("No X resolution found in image file " + filename, pixelSizeNodes.getLength() > 0);
Node pixelSizeNode = pixelSizeNodes.item(0);
String val = pixelSizeNode.getAttributes().getNamedItem("value").getNodeValue();
int actualResolution = (int) Math.round(25.4 / Double.parseDouble(val));
assertEquals("X resolution doesn't match in image file " + filename, expectedResolution, actualResolution);
pixelSizeNodes = dimensionElement.getElementsByTagName("VerticalPixelSize");
assertTrue("No Y resolution found in image file " + filename, pixelSizeNodes.getLength() > 0);
pixelSizeNode = pixelSizeNodes.item(0);
val = pixelSizeNode.getAttributes().getNamedItem("value").getNodeValue();
actualResolution = (int) Math.round(25.4 / Double.parseDouble(val));
assertEquals("Y resolution doesn't match", expectedResolution, actualResolution);
}
reader.dispose();
}
use of javax.imageio.metadata.IIOMetadata in project pdfbox by apache.
the class TestImageIOUtils method checkTiffCompression.
/**
* checks whether the compression of a TIFF file is as expected.
*
* @param filename Filename
* @param expectedCompression expected TIFF compression
*
* @throws IOException if something goes wrong
*/
void checkTiffCompression(String filename, String expectedCompression) throws IOException {
Iterator readers = ImageIO.getImageReadersBySuffix("tiff");
ImageReader reader = (ImageReader) readers.next();
try (ImageInputStream iis = ImageIO.createImageInputStream(new File(filename))) {
reader.setInput(iis);
IIOMetadata imageMetadata = reader.getImageMetadata(0);
Element root = (Element) imageMetadata.getAsTree(STANDARD_METADATA_FORMAT);
Element comprElement = (Element) root.getElementsByTagName("Compression").item(0);
Node comprTypeNode = comprElement.getElementsByTagName("CompressionTypeName").item(0);
String actualCompression = comprTypeNode.getAttributes().getNamedItem("value").getNodeValue();
assertEquals("Incorrect TIFF compression in file " + filename, expectedCompression, actualCompression);
}
reader.dispose();
}
use of javax.imageio.metadata.IIOMetadata in project protools by SeanDragon.
the class ToolImageResize method resize.
/**
* 缩放gif图片
*
* @param originalFile
* 原图片
* @param resizedFile
* 缩放后的图片
* @param newWidth
* 宽度
* @param quality
* 缩放比例 (等比例)
*
* @throws IOException
*/
private static void resize(File originalFile, File resizedFile, int newWidth, float quality) throws IOException {
if (quality < 0 || quality > 1) {
throw new IllegalArgumentException("Quality has to be between 0 and 1");
}
ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
Image i = ii.getImage();
Image resizedImage = null;
int iWidth = i.getWidth(null);
int iHeight = i.getHeight(null);
if (iWidth > iHeight) {
resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH);
} else {
resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH);
}
// This code ensures that all the pixels in the image are loaded.
Image temp = new ImageIcon(resizedImage).getImage();
// Create the buffered image.
BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null), BufferedImage.TYPE_INT_RGB);
// Copy image to buffered image.
Graphics g = bufferedImage.createGraphics();
// Clear background and paint the image.
g.setColor(Color.white);
g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
g.drawImage(temp, 0, 0, null);
g.dispose();
// Soften.
float softenFactor = 0.05f;
float[] softenArray = { 0, softenFactor, 0, softenFactor, 1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0 };
Kernel kernel = new Kernel(3, 3, softenArray);
ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
bufferedImage = cOp.filter(bufferedImage, null);
// Write the jpeg to a file.
try (FileOutputStream out = new FileOutputStream(resizedFile)) {
ImageWriter imageWriter = ImageIO.getImageWritersBySuffix("jpg").next();
ImageOutputStream ios = ImageIO.createImageOutputStream(out);
imageWriter.setOutput(ios);
// and metadata
IIOMetadata imageMetaData = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(bufferedImage), null);
JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(quality);
imageWriter.write(imageMetaData, new IIOImage(bufferedImage, null, null), jpegParams);
}
}
Aggregations