Java Code Examples for javax.imageio.ImageReader#dispose()
The following examples show how to use
javax.imageio.ImageReader#dispose() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImageUtil.java From density-converter with Apache License 2.0 | 6 votes |
@Deprecated public static BufferedImage readSvg(File file, Dimension sourceDimension) throws Exception { try (ImageInputStream input = ImageIO.createImageInputStream(file)) { Iterator<ImageReader> readers = ImageIO.getImageReaders(input); if (!readers.hasNext()) { throw new IllegalArgumentException("No reader for: " + file); } ImageReader reader = readers.next(); try { reader.setInput(input); ImageReadParam param = reader.getDefaultReadParam(); param.setSourceRenderSize(sourceDimension); return reader.read(0, param); } finally { reader.dispose(); } } }
Example 2
Source File: ImageUtils.java From java-bot-sdk with Apache License 2.0 | 6 votes |
public static Dimension getImageDimension(File imgFile) throws IOException { int pos = imgFile.getName().lastIndexOf("."); if (pos == -1) throw new IOException("No extension for file: " + imgFile.getAbsolutePath()); String suffix = imgFile.getName().substring(pos + 1); Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix); while(iter.hasNext()) { ImageReader reader = iter.next(); try { ImageInputStream stream = new FileImageInputStream(imgFile); reader.setInput(stream); int width = reader.getWidth(reader.getMinIndex()); int height = reader.getHeight(reader.getMinIndex()); return new Dimension(width, height); } catch (IOException e) { System.out.println("Error reading: " + imgFile.getAbsolutePath() + " " + e); } finally { reader.dispose(); } } throw new IOException("Not a known image file: " + imgFile.getAbsolutePath()); }
Example 3
Source File: IOHelper.java From Launcher with GNU General Public License v3.0 | 6 votes |
public static BufferedImage readTexture(Object input, boolean cloak) throws IOException { ImageReader reader = ImageIO.getImageReadersByMIMEType("image/png").next(); try { reader.setInput(ImageIO.createImageInputStream(input), false, false); // Verify texture bounds int width = reader.getWidth(0); int height = reader.getHeight(0); if (!isValidTextureBounds(width, height, cloak)) throw new IOException(String.format("Invalid texture bounds: %dx%d", width, height)); // Read image return reader.read(0); } finally { reader.dispose(); } }
Example 4
Source File: ImageGifFile.java From MyBox with Apache License 2.0 | 6 votes |
public static GIFImageMetadata getGifMetadata(File file) { try { // ImageReaderSpi readerSpi = new GIFImageReaderSpi(); // GIFImageReader gifReader = (GIFImageReader) readerSpi.createReaderInstance(); ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next(); try ( ImageInputStream iis = ImageIO.createImageInputStream(file)) { reader.setInput(iis, false); GIFImageMetadata metadata = (GIFImageMetadata) reader.getImageMetadata(0); reader.dispose(); return metadata; } } catch (Exception e) { logger.error(e.toString()); return null; } }
Example 5
Source File: SimpleSelectionIIIFBuilder.java From wandora with GNU General Public License v3.0 | 6 votes |
public static int[] getImageDimensions(Object f) throws IOException { if(f instanceof URL) f=((URL)f).openStream(); ImageInputStream in = ImageIO.createImageInputStream(f); try{ final Iterator readers = ImageIO.getImageReaders(in); if(readers.hasNext()){ ImageReader reader=(ImageReader)readers.next(); try{ reader.setInput(in); return new int[]{reader.getWidth(0), reader.getHeight(0)}; }finally{ reader.dispose(); } } }finally { if(in!=null) in.close(); } return null; }
Example 6
Source File: TexCache.java From jaamsim with Apache License 2.0 | 6 votes |
public static Dimension getImageDimension(URI imageURI) { ImageInputStream inStream = null; try { inStream = ImageIO.createImageInputStream(imageURI.toURL().openStream()); Iterator<ImageReader> it = ImageIO.getImageReaders(inStream); if (it.hasNext()) { ImageReader reader = it.next(); reader.setInput(inStream); Dimension ret = new Dimension(reader.getWidth(0), reader.getHeight(0)); reader.dispose(); inStream.close(); return ret; } } catch (IOException ex) { } return null; }
Example 7
Source File: SimbergExport.java From wandora with GNU General Public License v3.0 | 6 votes |
public static int[] getImageDimensions(File f) throws IOException { ImageInputStream in = ImageIO.createImageInputStream(f); try{ final Iterator readers = ImageIO.getImageReaders(in); if(readers.hasNext()){ ImageReader reader=(ImageReader)readers.next(); try{ reader.setInput(in); return new int[]{reader.getWidth(0), reader.getHeight(0)}; }finally{ reader.dispose(); } } }finally { if(in!=null) in.close(); } return null; }
Example 8
Source File: JPEGFactory.java From sambox with Apache License 2.0 | 6 votes |
private static BufferedImage readJpeg(Object fileOrStream) throws IOException { Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("JPEG"); ImageReader reader = null; while (readers.hasNext()) { reader = readers.next(); if (reader.canReadRaster()) { break; } } requireIOCondition(nonNull(reader), "Cannot find an ImageIO reader for JPEG image"); try (ImageInputStream iis = ImageIO.createImageInputStream(fileOrStream)) { reader.setInput(iis); ImageIO.setUseCache(false); return reader.read(0); } finally { reader.dispose(); } }
Example 9
Source File: MainPanel.java From java-swing-tips with MIT License | 5 votes |
private static List<BufferedImage> loadFromStream(ImageInputStream imageStream) throws IOException { Iterable<ImageReader> it = () -> ImageIO.getImageReaders(imageStream); ImageReader reader = StreamSupport.stream(it.spliterator(), false) .filter(MainPanel::checkGifFormat) .findFirst() .orElseThrow(() -> new IOException("Can not read image format!")); reader.setInput(imageStream, false, false); List<BufferedImage> list = new ArrayList<>(); for (int i = 0; i < reader.getNumImages(true); i++) { IIOImage frame = reader.readAll(i, null); list.add((BufferedImage) frame.getRenderedImage()); } reader.dispose(); return list; }
Example 10
Source File: ImageIOHelper.java From JewelCrawler with GNU General Public License v3.0 | 5 votes |
public static File createImage(File imageFile, String imageFormat) { File tempFile = null; try { Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat); ImageReader reader = readers.next(); ImageInputStream iis = ImageIO.createImageInputStream(imageFile); reader.setInput(iis); // Read the stream metadata IIOMetadata streamMetadata = reader.getStreamMetadata(); // Set up the writeParam TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US); tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED); // Get tif writer and set output to file Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("tiff"); ImageWriter writer = writers.next(); BufferedImage bi = reader.read(0); IIOImage image = new IIOImage(bi, null, reader.getImageMetadata(0)); tempFile = tempImageFile(imageFile); ImageOutputStream ios = ImageIO.createImageOutputStream(tempFile); writer.setOutput(ios); writer.write(streamMetadata, image, tiffWriteParam); ios.close(); writer.dispose(); reader.dispose(); } catch (Exception exc) { exc.printStackTrace(); } return tempFile; }
Example 11
Source File: ConnectorHandlerTest.java From syndesis with Apache License 2.0 | 5 votes |
@Test public void connectorIconShouldHaveCorrectContentType() throws IOException { try (MockWebServer mockWebServer = new MockWebServer(); final Buffer resultBuffer = new Buffer()) { mockWebServer.start(); resultBuffer.writeAll(Okio.source(getClass().getResourceAsStream("test-image.png"))); mockWebServer.enqueue(new MockResponse().setHeader(CONTENT_TYPE, "image/png").setBody(resultBuffer)); final Connector connector = new Connector.Builder().id("connector-id").icon(mockWebServer.url("/u/23079786").toString()) .build(); when(dataManager.fetch(Connector.class, "connector-id")).thenReturn(connector); when(dataManager.fetchAll(Integration.class)).thenReturn(ListResult.of(Collections.emptyList())); final Response response = handler.getConnectorIcon("connector-id").get(); assertThat(response.getStatusInfo()).as("Wrong status code").isEqualTo(Response.Status.OK); assertThat(response.getHeaderString(CONTENT_TYPE)).as("Wrong content type").isEqualTo("image/png"); assertThat(response.getHeaderString(CONTENT_LENGTH)).as("Wrong content length").isEqualTo("2018"); final StreamingOutput so = (StreamingOutput) response.getEntity(); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (BufferedSink sink = Okio.buffer(Okio.sink(bos)); BufferedSource source = new Buffer(); ImageInputStream iis = ImageIO.createImageInputStream(source.inputStream());) { so.write(sink.outputStream()); source.readAll(sink); final Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); if (readers.hasNext()) { final ImageReader reader = readers.next(); try { reader.setInput(iis); assertThat(reader.getHeight(0)).as("Wrong image height").isEqualTo(106d); assertThat(reader.getWidth(0)).as("Wrong image width").isEqualTo(106d); } finally { reader.dispose(); } } } } }
Example 12
Source File: ConnectorsITCase.java From syndesis with Apache License 2.0 | 5 votes |
@Test public void testUpdateIcon() throws IOException { final LinkedMultiValueMap<String, Object> multipartData = new LinkedMultiValueMap<>(); multipartData.add("icon", new InputStreamResource(getClass().getResourceAsStream("test-image.png"))); final ResponseEntity<Connector> updated = post("/api/v1/connectors/twitter/icon", multipartData, Connector.class, tokenRule.validToken(), HttpStatus.OK, multipartHeaders()); assertThat(updated.getBody().getId()).isPresent(); assertThat(updated.getBody().getIcon()).isNotBlank().startsWith("db:"); final ResponseEntity<ByteArrayResource> got = get("/api/v1/connectors/twitter/icon", ByteArrayResource.class); assertThat(got.getHeaders().getFirst("Content-Type")).isEqualTo("image/png"); try (ImageInputStream iis = ImageIO.createImageInputStream(got.getBody().getInputStream());) { final Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); if (readers.hasNext()) { final ImageReader reader = readers.next(); try { reader.setInput(iis); final Dimension dimensions = new Dimension(reader.getWidth(0), reader.getHeight(0)); assertThat(dimensions.getHeight()).as("Wrong image height").isEqualTo(106d); assertThat(dimensions.getWidth()).as("Wrong image width").isEqualTo(106d); } finally { reader.dispose(); } } } }
Example 13
Source File: HtmlTagBasedGenerator.java From fess with Apache License 2.0 | 5 votes |
protected Result saveImage(final ImageInputStream input, final File outputFile) throws IOException { final FessConfig fessConfig = ComponentUtil.getFessConfig(); final Iterator<ImageReader> readers = ImageIO.getImageReaders(input); if (readers.hasNext()) { final ImageReader reader = readers.next(); try { reader.setInput(input); final ImageReadParam param = reader.getDefaultReadParam(); final int width = reader.getWidth(0); final int height = reader.getHeight(0); if (width <= 0 || height <= 0) { return Result.NO_IMAGE; } if (!fessConfig.validateThumbnailSize(width, height)) { return Result.INVALID_SIZE; } final int samplingWidth = width / fessConfig.getThumbnailHtmlImageThumbnailWidthAsInteger(); final int samplingHeight = height / fessConfig.getThumbnailHtmlImageThumbnailHeightAsInteger(); param.setSourceSubsampling(samplingWidth <= 0 ? 1 : samplingWidth, samplingHeight <= 0 ? 1 : samplingHeight, 0, 0); param.setSourceRegion(new Rectangle(width, height > width ? width : height)); final BufferedImage image = reader.read(0, param); final int thumbnailWidth = fessConfig.getThumbnailHtmlImageThumbnailWidthAsInteger(); final int thumbnailHeight = (int) ((height > width ? width : height) * fessConfig.getThumbnailHtmlImageThumbnailWidthAsInteger().floatValue() / width); final BufferedImage thumbnail = new BufferedImage(thumbnailWidth, thumbnailHeight, image.getType()); thumbnail.getGraphics().drawImage(image.getScaledInstance(thumbnailWidth, thumbnailHeight, Image.SCALE_AREA_AVERAGING), 0, 0, thumbnailWidth, thumbnailHeight, null); ImageIO.write(thumbnail, fessConfig.getThumbnailHtmlImageFormat(), outputFile); image.flush(); return Result.OK; } finally { reader.dispose(); } } return Result.FAILED; }
Example 14
Source File: BufferedImageHttpMessageConverter.java From spring-analysis-note with MIT License | 5 votes |
@Override public BufferedImage read(@Nullable Class<? extends BufferedImage> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { ImageInputStream imageInputStream = null; ImageReader imageReader = null; try { imageInputStream = createImageInputStream(inputMessage.getBody()); MediaType contentType = inputMessage.getHeaders().getContentType(); if (contentType == null) { throw new HttpMessageNotReadableException("No Content-Type header", inputMessage); } Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(contentType.toString()); if (imageReaders.hasNext()) { imageReader = imageReaders.next(); ImageReadParam irp = imageReader.getDefaultReadParam(); process(irp); imageReader.setInput(imageInputStream, true); return imageReader.read(0, irp); } else { throw new HttpMessageNotReadableException( "Could not find javax.imageio.ImageReader for Content-Type [" + contentType + "]", inputMessage); } } finally { if (imageReader != null) { imageReader.dispose(); } if (imageInputStream != null) { try { imageInputStream.close(); } catch (IOException ex) { // ignore } } } }
Example 15
Source File: MCRIView2Tools.java From mycore with GNU General Public License v3.0 | 5 votes |
/** * combines image tiles of specified zoomLevel to one image. * * @param iviewFile * .iview2 file * @param zoomLevel * the zoom level where 0 is thumbnail size * @return a combined image * @throws IOException * any IOException while reading tiles * @throws JDOMException * if image properties could not be parsed. */ public static BufferedImage getZoomLevel(Path iviewFile, int zoomLevel) throws IOException, JDOMException { ImageReader reader = getTileImageReader(); try (FileSystem zipFileSystem = getFileSystem(iviewFile)) { Path iviewFileRoot = zipFileSystem.getRootDirectories().iterator().next(); MCRTiledPictureProps imageProps = MCRTiledPictureProps.getInstanceFromDirectory(iviewFileRoot); if (zoomLevel < 0 || zoomLevel > imageProps.getZoomlevel()) { throw new IndexOutOfBoundsException( "Zoom level " + zoomLevel + " is not in range 0 - " + imageProps.getZoomlevel()); } return getZoomLevel(iviewFileRoot, imageProps, reader, zoomLevel); } finally { reader.dispose(); } }
Example 16
Source File: ImageFileReaders.java From MyBox with Apache License 2.0 | 5 votes |
public static BufferedImage readFileByHeight(String format, String filename, int height) { BufferedImage bufferedImage; int scale = 1; try { if ("ico".equals(format) || "icon".equals(format)) { bufferedImage = readIcon(new File(filename)); return ImageManufacture.scaleImageHeightKeep(bufferedImage, height); } ImageReader reader = getReader(format); try ( ImageInputStream in = ImageIO.createImageInputStream( new BufferedInputStream(new BufferedInputStream(new FileInputStream(filename))))) { reader.setInput(in, false); if (reader.getHeight(0) <= height) { scale = 1; } else { scale = reader.getHeight(0) / height + 1; if (scale < 2) { scale = 2; } } // logger.debug(height + " " + scale); ImageReadParam param = reader.getDefaultReadParam(); param.setSourceSubsampling(scale, scale, 0, 0); bufferedImage = reader.read(0, param); // logger.debug(bufferedImage.getWidth() + " " + bufferedImage.getHeight()); reader.dispose(); } } catch (Exception e) { bufferedImage = readBrokenImage(e, new File(filename), scale); } return bufferedImage; }
Example 17
Source File: JPEGCodec.java From jpexs-decompiler with GNU General Public License v3.0 | 5 votes |
public int decode(Buffer in, Buffer out) { out.setMetaTo(in); out.format = outputFormat; if (in.isFlag(DISCARD)) { return CODEC_OK; } byte[] data = (byte[]) in.data; if (data == null) { out.setFlag(DISCARD); return CODEC_FAILED; } ByteArrayImageInputStream tmp = new ByteArrayImageInputStream(data); try { // ImageReader ir = (ImageReader) ImageIO.getImageReadersByMIMEType("image/jpeg").next(); ImageReader ir = new MJPGImageReader(new MJPGImageReaderSpi()); ir.setInput(tmp); out.data = ir.read(0); ir.dispose(); out.sampleCount = 1; out.offset = 0; out.length = (int) tmp.getStreamPosition(); return CODEC_OK; } catch (IOException ex) { ex.printStackTrace(); out.setFlag(DISCARD); return CODEC_FAILED; } }
Example 18
Source File: ImagePanel.java From marathonv5 with Apache License 2.0 | 4 votes |
private void initializeAnnotations() { try { ImageInputStream iis = ImageIO.createImageInputStream(imageFile); Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); if (readers.hasNext()) { ImageReader reader = readers.next(); reader.setInput(iis); IIOMetadata imageMetadata = reader.getImageMetadata(0); org.w3c.dom.Node root = imageMetadata.getAsTree(imageMetadata.getNativeMetadataFormatName()); NodeList childNodes = root.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { org.w3c.dom.Node item = childNodes.item(i); if (item.getNodeName().equals("tEXt")) { org.w3c.dom.Node textNode = item; NodeList entryNodes = textNode.getChildNodes(); for (int j = 0; j < entryNodes.getLength(); j++) { org.w3c.dom.Node entry = entryNodes.item(j); if (entry.getNodeName().equals("tEXtEntry")) { NamedNodeMap attributes = entry.getAttributes(); String kw = attributes.getNamedItem("keyword").getNodeValue(); String value = attributes.getNamedItem("value").getNodeValue(); Pattern p = Pattern.compile("a1810-(\\d+)-(\\d+\\.\\d+)-(\\d+\\.\\d+)-(\\d+\\.\\d+)-(\\d+\\.\\d+)"); Matcher matcher = p.matcher(kw); if (matcher.matches()) { Annotation annotation = new Annotation(); annotation.setX(Double.parseDouble(matcher.group(2))); annotation.setY(Double.parseDouble(matcher.group(3))); annotation.setWidth(Double.parseDouble(matcher.group(4))); annotation.setHeight(Double.parseDouble(matcher.group(5))); annotation.setText(value); annotation.setFill(ANNOTATION_COLOR); annotations.add(annotation); } } } } } reader.dispose(); } } catch (IOException e) { e.printStackTrace(); } }
Example 19
Source File: ImageIOHelper.java From tess4j with Apache License 2.0 | 4 votes |
/** * Merges multiple images into one multi-page TIFF image. * * @param inputImages an array of image files * @param outputTiff the output multi-page TIFF file * @throws IOException */ public static void mergeTiff(File[] inputImages, File outputTiff) throws IOException { if (inputImages.length == 0) { // if no image return; } Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT); if (!writers.hasNext()) { throw new RuntimeException(JAI_IMAGE_WRITER_MESSAGE); } ImageWriter writer = writers.next(); //Set up the writeParam TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US); // tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED); // commented out to preserve original sizes //Get the stream metadata IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam); try (ImageOutputStream ios = ImageIO.createImageOutputStream(outputTiff)) { writer.setOutput(ios); boolean firstPage = true; int index = 1; for (File inputImage : inputImages) { String imageFileFormat = getImageFileFormat(inputImage); Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFileFormat); if (!readers.hasNext()) { throw new RuntimeException(JAI_IMAGE_READER_MESSAGE); } ImageReader reader = readers.next(); try (ImageInputStream iis = ImageIO.createImageInputStream(inputImage)) { reader.setInput(iis); int imageTotal = reader.getNumImages(true); for (int i = 0; i < imageTotal; i++) { IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam()); if (firstPage) { writer.write(streamMetadata, oimage, tiffWriteParam); firstPage = false; } else { writer.writeInsert(index++, oimage, tiffWriteParam); } } } finally { if (reader != null) { reader.dispose(); } } } } finally { writer.dispose(); } }
Example 20
Source File: PageImageWriter.java From sejda with GNU Affero General Public License v3.0 | 4 votes |
/** * Checks if the input file is a JPEG using CMYK * If that's the case, converts to RGB and returns the file path */ private static Optional<SeekableSource> convertCMYKJpegIf(SeekableSource source) throws IOException, TaskIOException { try { if (FileType.JPEG.equals(getFileType(source))) { try (ImageInputStream iis = ImageIO.createImageInputStream(source.asNewInputStream())) { ImageReader reader = ImageIO.getImageReadersByFormatName("jpg").next(); boolean isCmyk = false; try { ImageIO.setUseCache(false); reader.setInput(iis); for (Iterator<ImageTypeSpecifier> it = reader.getImageTypes(0); it.hasNext(); ) { ImageTypeSpecifier typeSpecifier = it.next(); if (typeSpecifier.getColorModel().getColorSpace().getType() == ColorSpace.TYPE_CMYK) { isCmyk = true; } } if (isCmyk) { LOG.debug("Detected a CMYK JPEG image, will convert to RGB and save to a new file"); // convert to rgb // twelvemonkeys JPEG plugin already converts it to rgb when reading the image // just write it out BufferedImage image = reader.read(0); File tmpFile = IOUtils.createTemporaryBuffer(); ImageIO.write(image, "jpg", tmpFile); return Optional.of(SeekableSources.seekableSourceFrom(tmpFile)); } } finally { reader.dispose(); } } } } catch (IIOException e) { if(e.getMessage().startsWith("Not a JPEG stream")) { // this was a different image format with a JPEG extension } else { throw e; } } return Optional.empty(); }