List of usage examples for javax.imageio ImageReader setInput
public void setInput(Object input, boolean seekForwardOnly)
From source file:Main.java
static public void main(String args[]) throws Exception { FileInputStream fin = new FileInputStream("a.gif"); Iterator readers = ImageIO.getImageReadersBySuffix("GIF"); ImageReader imageReader = (ImageReader) readers.next(); ImageInputStream iis = ImageIO.createImageInputStream(fin); imageReader.setInput(iis, false); imageReader.addIIOReadProgressListener(new IIOReadProgressListener() { public void imageComplete(ImageReader source) { System.out.println("image complete " + source); }/*from www . jav a2 s. c o m*/ public void imageProgress(ImageReader source, float percentageDone) { System.out.println("image progress " + source + ": " + percentageDone + "%"); } public void imageStarted(ImageReader source, int imageIndex) { System.out.println("image #" + imageIndex + " started " + source); } public void readAborted(ImageReader source) { System.out.println("read aborted " + source); } public void sequenceComplete(ImageReader source) { System.out.println("sequence complete " + source); } public void sequenceStarted(ImageReader source, int minIndex) { System.out.println("sequence started " + source + ": " + minIndex); } public void thumbnailComplete(ImageReader source) { System.out.println("thumbnail complete " + source); } public void thumbnailProgress(ImageReader source, float percentageDone) { System.out.println("thumbnail started " + source + ": " + percentageDone + "%"); } public void thumbnailStarted(ImageReader source, int imageIndex, int thumbnailIndex) { System.out.println("thumbnail progress " + source + ", " + thumbnailIndex + " of " + imageIndex); } }); BufferedImage image = imageReader.read(0); Iterator imageWriters = ImageIO.getImageWritersBySuffix("JPG"); ImageWriter imageWriter = (ImageWriter) imageWriters.next(); File file = new File("b.JPG"); ImageOutputStream ios = ImageIO.createImageOutputStream(file); imageWriter.setOutput(ios); imageWriter.write(image); }
From source file:de.mpg.imeji.presentation.metadata.extractors.BasicExtractor.java
public static List<String> extractTechMd(Item item) throws Exception { List<String> techMd = new ArrayList<String>(); URI uri = item.getFullImageUrl(); String imageUrl = uri.toURL().toString(); GetMethod method = new GetMethod(imageUrl); method.setFollowRedirects(false);//from w ww. j a v a 2 s . c o m String userHandle = null; userHandle = LoginHelper.login(PropertyReader.getProperty("imeji.escidoc.user"), PropertyReader.getProperty("imeji.escidoc.password")); method.addRequestHeader("Cookie", "escidocCookie=" + userHandle); HttpClient client = new HttpClient(); client.executeMethod(method); InputStream input = method.getResponseBodyAsStream(); ImageInputStream iis = ImageIO.createImageInputStream(input); Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); if (readers.hasNext()) { // pick the first available ImageReader ImageReader reader = readers.next(); // attach source to the reader reader.setInput(iis, true); // read metadata of first image IIOMetadata metadata = reader.getImageMetadata(0); String[] names = metadata.getMetadataFormatNames(); int length = names.length; for (int i = 0; i < length; i++) { displayMetadata(techMd, metadata.getAsTree(names[i])); } } return techMd; }
From source file:com.shending.support.CompressPic.java
public static void cut(String srcFile, String dstFile, int widthRange, int heightRange) { int x = 0;/*from w ww .j a v a 2s . c o m*/ int y = 0; try { ImageInputStream iis = ImageIO.createImageInputStream(new File(srcFile)); Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis); ImageReader reader = (ImageReader) iterator.next(); reader.setInput(iis, true); ImageReadParam param = reader.getDefaultReadParam(); int oldWidth = reader.getWidth(0); int oldHeight = reader.getHeight(0); int newWidth, newHeight; newWidth = oldHeight * widthRange / heightRange; if (newWidth < oldWidth) { newHeight = oldHeight; x = (oldWidth - newWidth) / 2; } else { newWidth = oldWidth; newHeight = oldWidth * heightRange / widthRange; y = (oldHeight - newHeight) / 2; } Rectangle rectangle = new Rectangle(x, y, newWidth, newHeight); param.setSourceRegion(rectangle); BufferedImage bi = reader.read(0, param); File file = new File(dstFile); ImageIO.write(bi, reader.getFormatName(), file); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.shending.support.CompressPic.java
/** * ?/* w w w. j ava 2s . c om*/ * * @param srcFile * @param dstFile * @param widthRange * @param heightRange */ public static void cutSquare(String srcFile, String dstFile, int widthRange, int heightRange, int width, int height) { int x = 0; int y = 0; try { ImageInputStream iis = ImageIO.createImageInputStream(new File(srcFile)); Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis); ImageReader reader = (ImageReader) iterator.next(); reader.setInput(iis, true); ImageReadParam param = reader.getDefaultReadParam(); int oldWidth = reader.getWidth(0); int oldHeight = reader.getHeight(0); int newWidth, newHeight; if (width <= oldWidth && height <= oldHeight) { newWidth = oldHeight * widthRange / heightRange; if (newWidth < oldWidth) { newHeight = oldHeight; x = (oldWidth - newWidth) / 2; } else { newWidth = oldWidth; newHeight = oldWidth * heightRange / widthRange; y = (oldHeight - newHeight) / 2; } Rectangle rectangle = new Rectangle(x, y, newWidth, newHeight); param.setSourceRegion(rectangle); BufferedImage bi = reader.read(0, param); BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(bi.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null); File file = new File(dstFile); ImageIO.write(tag, reader.getFormatName(), file); } else { BufferedImage bi = reader.read(0, param); BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = tag.createGraphics(); g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, tag.getWidth(), tag.getHeight()); g2d.drawImage(bi.getScaledInstance(bi.getWidth(), bi.getHeight(), Image.SCALE_SMOOTH), (width - bi.getWidth()) / 2, (height - bi.getHeight()) / 2, null); g2d.dispose(); File file = new File(dstFile); ImageIO.write(tag, reader.getFormatName(), file); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.sketchy.utils.image.SketchyImage.java
public static SketchyImage load(File file) throws Exception { SketchyImage sketchyImage = null;//www. j ava2s .c om if (!file.exists() || !file.canRead()) { throw new Exception("Can not find or read File: " + file.getPath() + "!"); } if (!StringUtils.endsWithIgnoreCase(file.getName(), ".png")) { throw new Exception("Can not load SketchyImage! Must be a .png file!"); } Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByFormatName("png"); ImageReader imageReader = null; if (imageReaders.hasNext()) { // Just get first one imageReader = imageReaders.next(); } if (imageReader == null) { // this should never happen!! if so.. we got problems throw new Exception("Can not find ImageReader for .png Files!"); } ImageInputStream is = null; try { is = ImageIO.createImageInputStream(file); imageReader.setInput(is, true); IIOMetadata metaData = imageReader.getImageMetadata(0); // always get first image IIOMetadataNode metaDataNode = (IIOMetadataNode) metaData .getAsTree(metaData.getNativeMetadataFormatName()); if (metaDataNode == null) { throw new Exception("Error retreiving MetaData properties from .png File!"); } NodeList childNodes = metaDataNode.getElementsByTagName("pHYs"); // only look in the first node if (childNodes.getLength() == 0) { throw new Exception("Invalid SketchyImage file. It must contain 'pixelsPerUnit' MetaData!"); } IIOMetadataNode physNode = (IIOMetadataNode) childNodes.item(0); String pixelsPerUnitXAxisAttribute = physNode.getAttribute("pixelsPerUnitXAxis"); String pixelsPerUnitYAxisAttribute = physNode.getAttribute("pixelsPerUnitYAxis"); // String unitSpecifierAttribute = physNode.getAttribute("unitSpecifier"); Just assuming meter if (StringUtils.isBlank(pixelsPerUnitXAxisAttribute)) { throw new Exception("Invalid SketchyImage file. It must contain 'pixelsPerUnitXAxis' MetaData!"); } if (StringUtils.isBlank(pixelsPerUnitYAxisAttribute)) { throw new Exception("Invalid SketchyImage file. It must contain 'pixelsPerUnitYAxis' MetaData!"); } int pixelsPerUnitXAxis; try { pixelsPerUnitXAxis = Integer.parseInt(pixelsPerUnitXAxisAttribute); if (pixelsPerUnitXAxis <= 0) throw new Exception("Value must be > 0"); } catch (Exception e) { throw new Exception("Invalid 'pixelsPerUnitXAxis' MetaData Attribute! " + e.getMessage()); } int pixelsPerUnitYAxis; try { pixelsPerUnitYAxis = Integer.parseInt(pixelsPerUnitYAxisAttribute); if (pixelsPerUnitYAxis <= 0) throw new Exception("Value must be > 0"); } catch (Exception e) { throw new Exception("Invalid 'pixelsPerUnitYAxis' MetaData Attribute! " + e.getMessage()); } // We successfully processed the MetaData.. now read/set the image BufferedImage bufferedImage = imageReader.read(0); // always get first image double xPixelsPerMM = pixelsPerUnitXAxis / 1000.0; double yPixelsPerMM = pixelsPerUnitYAxis / 1000.0; sketchyImage = new SketchyImage(bufferedImage, xPixelsPerMM, yPixelsPerMM); } catch (Exception e) { throw new Exception("Error Loading SketchyImage File: " + file.getPath() + "! " + e.getMessage()); } finally { IOUtils.closeQuietly(is); } return sketchyImage; }
From source file:com.moviejukebox.scanner.artwork.PosterScanner.java
/** * Read an URL and get the dimensions of the image using a specific image * type//w ww . j ava2 s. c om * * @param imageUrl * @param imageType * @return */ public static Dimension getUrlDimensions(String imageUrl, String imageType) { Dimension imageDimension = new Dimension(0, 0); @SuppressWarnings("rawtypes") Iterator readers = ImageIO.getImageReadersBySuffix(imageType); if (readers.hasNext()) { ImageReader reader = (ImageReader) readers.next(); try (InputStream in = new URL(imageUrl).openStream(); ImageInputStream iis = ImageIO.createImageInputStream(in)) { reader.setInput(iis, Boolean.TRUE); imageDimension.setSize(reader.getWidth(0), reader.getHeight(0)); } catch (IOException ex) { LOG.debug("getUrlDimensions error: {}: can't open url: {}", ex.getMessage(), imageUrl); } finally { reader.dispose(); } } return imageDimension; }
From source file:org.jamwiki.parser.image.ImageProcessor.java
/** * Retrieve image dimensions. This method simply reads headers so it should perform * relatively fast./*w ww .j a v a2 s . c o m*/ */ protected static Dimension retrieveImageDimensions(File imageFile) throws IOException { long start = System.currentTimeMillis(); if (!imageFile.exists()) { logger.info("No file found while determining image dimensions: " + imageFile.getAbsolutePath()); return null; } ImageInputStream iis = null; Dimension dimensions = null; ImageReader reader = null; // use a FileInputStream and make sure it gets closed to prevent unclosed file // errors on some operating systems FileInputStream fis = null; try { fis = new FileInputStream(imageFile); iis = ImageIO.createImageInputStream(fis); Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); if (readers.hasNext()) { reader = readers.next(); reader.setInput(iis, true); dimensions = new Dimension(reader.getWidth(0), reader.getHeight(0)); } } finally { if (reader != null) { reader.dispose(); } if (iis != null) { try { iis.close(); } catch (IOException e) { // ignore } } IOUtils.closeQuietly(fis); } if (logger.isDebugEnabled()) { long execution = (System.currentTimeMillis() - start); logger.debug("Image dimension lookup for " + imageFile.getAbsolutePath() + " took " + (execution / 1000.000) + " s"); } return dimensions; }
From source file:com.occamlab.te.parsers.ImageParser.java
/** * Determines the width of the first image in an image file in pixels. * // w ww . ja v a 2 s. co m * @param imageLoc * the string location of the image (uri syntax expected) * @return int the image width in pixels, or -1 if unable. * @author Paul Daisey added 2011-05-13 to support WMTS ETS */ public static int getImageWidth(String imageLoc) { // Get the image as an InputStream InputStream is = null; try { URI imageUri = new URI(imageLoc); URL imageUrl = imageUri.toURL(); is = imageUrl.openStream(); } catch (Exception e) { jlogger.log(Level.SEVERE, "getImageWidth", e); return -1; } // Determine the image width try { // Create an image input stream on the image ImageInputStream iis = ImageIO.createImageInputStream(is); // Find all image readers that recognize the image format Iterator iter = ImageIO.getImageReaders(iis); // No readers found if (!iter.hasNext()) { return -1; } // Use the first reader ImageReader reader = (ImageReader) iter.next(); reader.setInput(iis, true); int width = reader.getWidth(0); iis.close(); return width; } catch (IOException e) { jlogger.log(Level.SEVERE, "getImageWidth", e); // The image could not be read } return -1; }
From source file:com.occamlab.te.parsers.ImageParser.java
/** * Determines the height of the first image in an image file in pixels. * /*from ww w. j a v a 2s. c om*/ * @param imageLoc * the string location of the image (uri syntax expected) * @return int the image width in pixels, or -1 if unable. * @author Paul Daisey added 2011-05-13 to support WMTS ETS */ public static int getImageHeight(String imageLoc) { // Get the image as an InputStream InputStream is = null; try { URI imageUri = new URI(imageLoc); URL imageUrl = imageUri.toURL(); is = imageUrl.openStream(); } catch (Exception e) { jlogger.log(Level.SEVERE, "getImageWidth", e); return -1; } // Determine the image width try { // Create an image input stream on the image ImageInputStream iis = ImageIO.createImageInputStream(is); // Find all image readers that recognize the image format Iterator iter = ImageIO.getImageReaders(iis); // No readers found if (!iter.hasNext()) { return -1; } // Use the first reader ImageReader reader = (ImageReader) iter.next(); reader.setInput(iis, true); int height = reader.getHeight(0); iis.close(); return height; } catch (IOException e) { jlogger.log(Level.SEVERE, "getImageWidth", e); // The image could not be read } return -1; }
From source file:com.moviejukebox.scanner.artwork.FanartScanner.java
public static boolean validateArtwork(IImage artworkImage, int artworkWidth, int artworkHeight, boolean checkAspect) { @SuppressWarnings("rawtypes") Iterator readers = ImageIO.getImageReadersBySuffix("jpeg"); ImageReader reader = (ImageReader) readers.next(); int urlWidth, urlHeight; float urlAspect; if (!ARTWORK_VALIDATE) { return true; }// www. ja v a2s .com if (StringTools.isNotValidString(artworkImage.getUrl())) { return false; } try { URL url = new URL(artworkImage.getUrl()); try (InputStream in = url.openStream(); ImageInputStream iis = ImageIO.createImageInputStream(in)) { reader.setInput(iis, true); urlWidth = reader.getWidth(0); urlHeight = reader.getHeight(0); } } catch (IOException error) { LOG.debug("ValidateFanart error: {}: can't open url", error.getMessage()); return false; // Quit and return a false fanart } urlAspect = (float) urlWidth / (float) urlHeight; if (checkAspect && urlAspect < 1.0) { LOG.debug("ValidateFanart {} rejected: URL is portrait format", artworkImage); return false; } // Adjust fanart width / height by the ValidateMatch figure int newArtworkWidth = artworkWidth * (ARTWORK_VALIDATE_MATCH / 100); int newArtworkHeight = artworkHeight * (ARTWORK_VALIDATE_MATCH / 100); if (urlWidth < newArtworkWidth) { LOG.debug("{} rejected: URL width ({}) is smaller than fanart width ({})", artworkImage, urlWidth, newArtworkWidth); return false; } if (urlHeight < newArtworkHeight) { LOG.debug("{} rejected: URL height ({}) is smaller than fanart height ({})", artworkImage, urlHeight, newArtworkHeight); return false; } return true; }