Java Code Examples for javax.imageio.ImageReader#getWidth()
The following examples show how to use
javax.imageio.ImageReader#getWidth() .
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: 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 2
Source File: ImageHelper.java From jpexs-decompiler with GNU General Public License v3.0 | 6 votes |
public static Dimension getDimesion(InputStream input) throws IOException { try (ImageInputStream in = ImageIO.createImageInputStream(input)) { final Iterator<ImageReader> readers = ImageIO.getImageReaders(in); if (readers.hasNext()) { ImageReader reader = readers.next(); try { reader.setInput(in); return new Dimension(reader.getWidth(0), reader.getHeight(0)); } finally { reader.dispose(); } } } catch (IOException ex) { } BufferedImage image = read(input); return new Dimension(image.getWidth(), image.getHeight()); }
Example 3
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 4
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 5
Source File: Dimension.java From WorldPainter with GNU General Public License v3.0 | 6 votes |
private java.awt.Dimension getImageSize(File image) throws IOException { String filename = image.getName(); int p = filename.lastIndexOf('.'); if (p == -1) { return null; } String suffix = filename.substring(p + 1).toLowerCase(); Iterator<ImageReader> readers = ImageIO.getImageReadersBySuffix(suffix); if (readers.hasNext()) { ImageReader reader = readers.next(); try { try (ImageInputStream in = new FileImageInputStream(image)) { reader.setInput(in); int width = reader.getWidth(reader.getMinIndex()); int height = reader.getHeight(reader.getMinIndex()); return new java.awt.Dimension(width, height); } } finally { reader.dispose(); } } else { return null; } }
Example 6
Source File: ImageUtil.java From density-converter with Apache License 2.0 | 6 votes |
/** * Gets image dimensions for given file * * @param imgFile image file * @return dimensions of image * @throws IOException if the file is not a known image */ 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); if (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); } finally { reader.dispose(); } } throw new IOException("Not a known image file: " + imgFile.getAbsolutePath()); }
Example 7
Source File: ImageUtils.java From jpress with GNU Lesser General Public License v3.0 | 6 votes |
private static BufferedImage readBuffereImage(ImageReader reader, int w, int h) throws IOException { ImageReadParam param = reader.getDefaultReadParam(); int srcWidth = reader.getWidth(0); int srcHeight = reader.getHeight(0); Rectangle rect = null; if ((float) w / h > (float) srcWidth / srcHeight) { h = h * srcWidth / w; w = srcWidth; rect = new Rectangle(0, (srcHeight - h) / 2, w, h); } else { w = w * srcHeight / h; h = srcHeight; rect = new Rectangle((srcWidth - w) / 2, 0, w, h); } param.setSourceRegion(rect); BufferedImage srcBuffered = reader.read(0, param); return srcBuffered; }
Example 8
Source File: ImageUtils.java From springboot-admin with Apache License 2.0 | 6 votes |
private static BufferedImage readBuffereImage(ImageReader reader, int w, int h) throws IOException { ImageReadParam param = reader.getDefaultReadParam(); int srcWidth = reader.getWidth(0); int srcHeight = reader.getHeight(0); Rectangle rect = null; if ((float) w / h > (float) srcWidth / srcHeight) { h = h * srcWidth / w; w = srcWidth; rect = new Rectangle(0, (srcHeight - h) / 2, w, h); } else { w = w * srcHeight / h; h = srcHeight; rect = new Rectangle((srcWidth - w) / 2, 0, w, h); } param.setSourceRegion(rect); BufferedImage srcBuffered = reader.read(0, param); return srcBuffered; }
Example 9
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 10
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 11
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 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: BigBufferedImage.java From OpenRS with GNU General Public License v3.0 | 5 votes |
public static BufferedImage create(File inputFile, int imageType) throws IOException { try (ImageInputStream stream = ImageIO.createImageInputStream(inputFile);) { Iterator<ImageReader> readers = ImageIO.getImageReaders(stream); if (readers.hasNext()) { try { ImageReader reader = readers.next(); reader.setInput(stream, true, true); int width = reader.getWidth(reader.getMinIndex()); int height = reader.getHeight(reader.getMinIndex()); BufferedImage image = create(width, height, imageType); int cores = Math.max(1, Runtime.getRuntime().availableProcessors() / 2); int block = Math.min(MAX_PIXELS_IN_MEMORY / cores / width, (int) (Math.ceil(height / (double) cores))); ExecutorService generalExecutor = Executors.newFixedThreadPool(cores); List<Callable<ImagePartLoader>> partLoaders = new ArrayList<>(); for (int y = 0; y < height; y += block) { partLoaders.add(new ImagePartLoader( y, width, Math.min(block, height - y), inputFile, image)); } generalExecutor.invokeAll(partLoaders); generalExecutor.shutdown(); return image; } catch (InterruptedException ex) { Logger.getLogger(BigBufferedImage.class.getName()).log(Level.SEVERE, null, ex); } } } return null; }
Example 14
Source File: ImageUtils.java From albert with MIT License | 5 votes |
/** * 给图片添加图片水印 * @param pressImg 水印图片 * @param srcImageFile 源图像地址 * @param destImageFile 目标图像地址 * @param x 修正值。 默认在中间 * @param y 修正值。 默认在中间 * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字 */ public static boolean pressImage(String pressImg, String srcImageFile,String destImageFile, int x, int y, float alpha) { try { File file = new File(srcImageFile); BufferedImage src = ImageIO.read(file); // 读入文件 Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg"); ImageReader reader = (ImageReader) readers.next(); ImageInputStream iis = ImageIO.createImageInputStream(file); reader.setInput(iis, true); int width = reader.getWidth(0); // 得到源图宽 int height = reader.getHeight(0); // 得到源图长 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.drawImage(src, 0, 0, width, height, null); // 水印文件 Image src_biao = ImageIO.read(new File(pressImg)); int wideth_biao = src_biao.getWidth(null); int height_biao = src_biao.getHeight(null); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); g.drawImage(src_biao, (width-wideth_biao-x) , (height-height_biao-y) , wideth_biao, height_biao, null); // 水印文件结束 g.dispose(); ImageIO.write((BufferedImage) image, "jpg", new File(destImageFile)); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
Example 15
Source File: ImageUtils.java From albert with MIT License | 5 votes |
/** * 获取图片的宽 * @param srcImageFile 源图片路径 * @return */ public static int getImageWidth(String srcImageFile){ try { File file = new File(srcImageFile); Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg"); ImageReader reader = (ImageReader) readers.next(); ImageInputStream iis = ImageIO.createImageInputStream(file); reader.setInput(iis, true); return reader.getWidth(0); } catch (IOException e) { e.printStackTrace(); return 0; } }
Example 16
Source File: BinaryGltfV1.java From JglTF with MIT License | 5 votes |
/** * Set the properties for the given {@link Image} that is stored * as a <code>"KHR_binary_glTF"</code> image. These properties * are * <ul> * <li>The image <code>width</code></li> * <li>The image <code>height</code></li> * <li>The image <code>mimeType</code></li> * </ul> * (Note that the buffer view ID is set explicitly with * {@link #setBinaryGltfBufferViewId(GlTFProperty, String)}) * * @param image The image * @param imageData The raw image data * @throws GltfException If the image data cannot be analyzed to derive * the required information */ public static void setBinaryGltfImageProperties( Image image, ByteBuffer imageData) { ImageReader imageReader = null; try { imageReader = ImageReaders.findImageReader(imageData); int width = imageReader.getWidth(0); int height = imageReader.getHeight(0); String mimeType = "image/" + imageReader.getFormatName(); GltfExtensionsV1.setExtensionPropertyValue(image, KHRONOS_BINARY_GLTF_EXTENSION_NAME, "width", width); GltfExtensionsV1.setExtensionPropertyValue(image, KHRONOS_BINARY_GLTF_EXTENSION_NAME, "height", height); GltfExtensionsV1.setExtensionPropertyValue(image, KHRONOS_BINARY_GLTF_EXTENSION_NAME, "mimeType", mimeType); } catch (IOException e) { throw new GltfException( "Could not derive image properties for binary glTF", e); } finally { if (imageReader != null) { imageReader.dispose(); } } }
Example 17
Source File: ImageFileReaders.java From MyBox with Apache License 2.0 | 5 votes |
public static BufferedImage readFileByWidth(String format, String filename, int width) { BufferedImage bufferedImage; int scale = 1; try { if ("ico".equals(format) || "icon".equals(format)) { bufferedImage = readIcon(new File(filename)); return ImageManufacture.scaleImageWidthKeep(bufferedImage, width); } ImageReader reader = getReader(format); try ( ImageInputStream in = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(filename)))) { reader.setInput(in, false); if (reader.getWidth(0) <= width) { scale = 1; } else { scale = reader.getWidth(0) / width + 1; if (scale < 2) { scale = 2; } } 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 18
Source File: ImageUtils.java From albert with MIT License | 4 votes |
/*** * 缩放图像,按照长宽缩放 * @param srcImageFile * @param result * @param height 变换后的高度 * @param width 变换后的长度 * @param bb 比例不对称时,是否补白,true 补白;false 不补白 * @return * @date 2016-3-30下午2:44:37 */ public static boolean scale2(String srcImageFile, String result, int height, int width, boolean bb) { try { double ratio = 0.0; // 缩放比例 File file = new File(srcImageFile); BufferedImage bi = ImageIO.read(file); // 读入文件 Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg"); ImageReader reader = (ImageReader) readers.next(); ImageInputStream iis = ImageIO.createImageInputStream(file); reader.setInput(iis, true); int width1 = reader.getWidth(0); // 得到源图宽 int height1 = reader.getHeight(0); // 得到源图长 @SuppressWarnings("static-access") Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH); // 计算比例 if ((height1 > height) || (width1 > width)) { if (height1 > width1) { ratio = (new Integer(height)).doubleValue() / height1; } else { ratio = (new Integer(width)).doubleValue() / width1; } AffineTransformOp op = new AffineTransformOp(AffineTransform .getScaleInstance(ratio, ratio), null); itemp = op.filter(bi, null); } if (bb) {//补白 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.setColor(Color.white); g.fillRect(0, 0, width, height); if (width == itemp.getWidth(null)) g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), Color.white, null); else g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), Color.white, null); g.dispose(); itemp = image; } ImageIO.write((BufferedImage) itemp, "JPEG", new File(result)); return true; } catch (IOException e) { e.printStackTrace(); return false; } }
Example 19
Source File: DbxClientV1IT.java From dropbox-sdk-java with MIT License | 4 votes |
@Test public void testThumbnail() throws Exception { String orig = p("test-imag" + E_ACCENT + ".jpeg"); // Upload an image. InputStream in = this.getClass().getResourceAsStream("/test-image.jpeg"); if (in == null) { throw new AssertionError("couldn't load test image \"test-image.jpeg\""); } DbxEntry.File origMD; try { origMD = client.uploadFile(orig, DbxWriteMode.add(), -1, in); } finally { IOUtil.closeInput(in); } BufferedImage origImage = ImageIO.read(getClass().getResource("/test-image.jpeg")); int origW = origImage.getWidth(); int origH = origImage.getHeight(); DbxThumbnailFormat[] formats = { DbxThumbnailFormat.JPEG, DbxThumbnailFormat.PNG, }; DbxThumbnailSize[] sizes = { DbxThumbnailSize.w32h32, DbxThumbnailSize.w64h64, DbxThumbnailSize.w64h64, DbxThumbnailSize.w640h480, DbxThumbnailSize.w1024h768, }; for (DbxThumbnailFormat format : formats) { long prevSize = 0; ImageReader reader = getImageReaderForFormat(format); for (DbxThumbnailSize size : sizes) { ByteArrayOutputStream out = new ByteArrayOutputStream(); DbxEntry.File md = client.getThumbnail(size, format, orig, null, out); byte[] data = out.toByteArray(); assertEquals(removeMediaInfo(origMD), removeMediaInfo(md)); // We're getting bigger and bigger thumbnails, so they should have more bytes // than the previous ones. assertTrue(data.length > prevSize); reader.setInput(new MemoryCacheImageInputStream(new ByteArrayInputStream(data))); int w = reader.getWidth(0); int h = reader.getHeight(0); int expectedW = Math.min(size.width, origW); int expectedH = Math.min(size.width, origH); assertTrue((w == expectedW && h <= expectedH) || (h == expectedH && w <= expectedW), "expected = " + expectedW + "x" + expectedH + ", got = " + w + "x" + h); } } }
Example 20
Source File: MockImageLoader.java From dawnsci with Eclipse Public License 1.0 | 4 votes |
private void readImages(IDataHolder output, ImageReader reader) throws IOException, ScanFileHolderException { int n = reader.getNumImages(true); if (n == 0) { return; } if (!loadData) return; boolean allSame = true; if (height < 0 || width < 0) { height = reader.getHeight(0); // this can throw NPE when using 12-bit reader width = reader.getWidth(0); for (int i = 1; i < n; i++) { if (height != reader.getHeight(i) || width != reader.getWidth(i)) { allSame = false; break; } } } final ImageTypeSpecifier its = reader.getRawImageType(0); // this raises an exception for 12-bit images when using standard reader if (allSame) { for (int i = 1; i < n; i++) { if (!its.equals(reader.getRawImageType(i))) { throw new ScanFileHolderException("Type of image in stack does not match first"); } } } int dtype = AWTImageUtils.getDTypeFromImage(its.getSampleModel(), keepBitWidth)[0]; if (n == 1) { ILazyDataset image; if (loadLazily) { image = createLazyDataset(dtype, height, width); } else { image = createDataset(reader.read(0)); } image.setName(DEF_IMAGE_NAME); image.setMetadata(metadata); output.addDataset(DEF_IMAGE_NAME, image); } else if (allSame) { ILazyDataset ld = createLazyDataset(dtype, n, height, width); ld.setMetadata(metadata); output.addDataset(STACK_NAME, ld); } else { createLazyDatasets(output, reader); } if (loadMetadata) { createMetadata(output, reader); metadata.setMetadata(metadataMap); output.setMetadata(metadata); } }