List of usage examples for javax.imageio ImageIO read
public static BufferedImage read(ImageInputStream stream) throws IOException
From source file:com.afis.jx.ckfinder.connector.utils.ImageUtils.java
/** * Creates image file with fixed width and height. * * @param sourceFile input file//from ww w. jav a 2s . c om * @param destFile file to save * @param width image width * @param height image height * @param quality image quality * @throws IOException when error occurs. */ public static void createResizedImage(final File sourceFile, final File destFile, final int width, final int height, final float quality) throws IOException { BufferedImage image = ImageIO.read(sourceFile); Dimension dimension = new Dimension(width, height); if (image.getHeight() == dimension.height && image.getWidth() == dimension.width) { writeUntouchedImage(sourceFile, destFile); } else { resizeImage(image, dimension.width, dimension.height, quality, destFile); } }
From source file:ddf.catalog.transformer.OverlayMetacardTransformerTest.java
private BufferedImage getImage(byte[] imageBytes) throws IOException { try (final ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes)) { final ImageInputStream imageInputStream = ImageIO.createImageInputStream(inputStream); return ImageIO.read(imageInputStream); }/* w w w .jav a2s. c om*/ }
From source file:net.groupbuy.util.ImageUtils.java
/** * //from w w w . ja va 2 s . com * * @param srcFile * ? * @param destFile * * @param destWidth * * @param destHeight * */ public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) { Assert.notNull(srcFile); Assert.notNull(destFile); Assert.state(destWidth > 0); Assert.state(destHeight > 0); if (type == Type.jdk) { Graphics2D graphics2D = null; ImageOutputStream imageOutputStream = null; ImageWriter imageWriter = null; try { BufferedImage srcBufferedImage = ImageIO.read(srcFile); int srcWidth = srcBufferedImage.getWidth(); int srcHeight = srcBufferedImage.getHeight(); int width = destWidth; int height = destHeight; if (srcHeight >= srcWidth) { width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth)); } else { height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight)); } BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB); graphics2D = destBufferedImage.createGraphics(); graphics2D.setBackground(BACKGROUND_COLOR); graphics2D.clearRect(0, 0, destWidth, destHeight); graphics2D.drawImage(srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), (destWidth / 2) - (width / 2), (destHeight / 2) - (height / 2), null); imageOutputStream = ImageIO.createImageOutputStream(destFile); imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName())) .next(); imageWriter.setOutput(imageOutputStream); ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam(); imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0)); imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam); imageOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (graphics2D != null) { graphics2D.dispose(); } if (imageWriter != null) { imageWriter.dispose(); } if (imageOutputStream != null) { try { imageOutputStream.close(); } catch (IOException e) { } } } } else { IMOperation operation = new IMOperation(); operation.thumbnail(destWidth, destHeight); operation.gravity("center"); operation.background(toHexEncoding(BACKGROUND_COLOR)); operation.extent(destWidth, destHeight); operation.quality((double) DEST_QUALITY); operation.addImage(srcFile.getPath()); operation.addImage(destFile.getPath()); if (type == Type.graphicsMagick) { ConvertCmd convertCmd = new ConvertCmd(true); if (graphicsMagickPath != null) { convertCmd.setSearchPath(graphicsMagickPath); } try { convertCmd.run(operation); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IM4JavaException e) { e.printStackTrace(); } } else { ConvertCmd convertCmd = new ConvertCmd(false); if (imageMagickPath != null) { convertCmd.setSearchPath(imageMagickPath); } try { convertCmd.run(operation); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IM4JavaException e) { e.printStackTrace(); } } } }
From source file:algorithm.ImageInformationEmbeddingFrame.java
/** * Create empty image with enough capacity to embed the payload * /*from w w w. j av a 2 s . c o m*/ * @param carrier * @param payload * @return image for payload * @throws IOException */ private BufferedImage createPayloadImage(File carrier, File payload) throws IOException { BufferedImage carrierImage = ImageIO.read(carrier); byte[] payloadBytes = FileUtils.readFileToByteArray(payload); int neededPayloadHeight = getNeededHeight(carrierImage.getWidth(), payloadBytes.length); return new BufferedImage(carrierImage.getWidth(), neededPayloadHeight, BufferedImage.TYPE_INT_RGB); }
From source file:com.sun.socialsite.util.ImageUtil.java
/** * Grabs an image from a URI (and scales it to some reasonable size). * * @param uriString the URI from which to grab the image. *///w w w . ja v a 2 s . c o m public BufferedImage getImage(final String uriString) { // TODO: better approach to Exceptions if ((uriString == null) || ("".equals(uriString))) { return null; } URI uri = null; GetMethod method = null; try { uri = new URI(uriString, false); HttpClient httpClient = new HttpClient(httpConnectionManager); method = new GetMethod(uri.getEscapedURI()); httpClient.executeMethod(method); BufferedImage origImage = ImageIO.read(method.getResponseBodyAsStream()); log.debug(String.format("Got origImage for %s", uriString)); return getScaledImage(origImage, maxWidth, maxHeight); } catch (ConnectException e) { log.warn(String.format("Failed to retrieve image: %s [%s]", uriString, e.toString())); return null; } catch (ConnectTimeoutException e) { log.warn(String.format("Failed to retrieve image: %s [%s]", uriString, e.toString())); return null; } catch (SocketTimeoutException e) { log.warn(String.format("Failed to retrieve image: %s [%s]", uriString, e.toString())); return null; } catch (UnknownHostException e) { log.warn(String.format("Failed to retrieve image: %s [%s]", uriString, e.toString())); return null; } catch (IllegalArgumentException e) { log.warn(String.format("Failed to retrieve image: %s [%s]", uriString, e.toString())); return null; } catch (IllegalStateException e) { log.warn(String.format("Failed to retrieve image: %s [%s]", uriString, e.toString())); return null; } catch (IIOException e) { log.warn(String.format("Failed to process image: %s [%s]", uriString, e.toString())); return null; } catch (Throwable t) { log.error(String.format("Failed to retrieve image: %s", uriString), t); return null; } finally { if (method != null) { method.releaseConnection(); } } }
From source file:com.cognifide.aet.job.common.comparators.layout.utils.ImageComparisonTest.java
@Test public void compare_differentSizeScreenshots_expectSizeDifferenceMarkedWithYellow() throws Exception { InputStream sampleStream = null; InputStream patternStream = null; InputStream maskStream = null; InputStream expectedMaskStream = null; try {/*from w w w . j a v a 2s . c om*/ // given sampleStream = getClass().getResourceAsStream("/mock/LayoutComparator/canvasSizeDiff/collected.png"); patternStream = getClass().getResourceAsStream("/mock/LayoutComparator/canvasSizeDiff/pattern.png"); BufferedImage sample = ImageIO.read(sampleStream); BufferedImage pattern = ImageIO.read(patternStream); // when ImageComparisonResult imageComparisonResult = ImageComparison.compare(pattern, sample); // then assertThat(imageComparisonResult.isMatch(), is(false)); assertThat(imageComparisonResult.getHeightDifference(), is(100)); assertThat(imageComparisonResult.getWidthDifference(), is(20)); assertThat(imageComparisonResult.getPixelDifferenceCount(), is(14399)); maskStream = imageToStream(imageComparisonResult.getResultImage()); expectedMaskStream = getClass().getResourceAsStream("/mock/LayoutComparator/canvasSizeDiff/mask.png"); assertThat(IOUtils.contentEquals(maskStream, expectedMaskStream), is(true)); } finally { closeInputStreams(sampleStream, patternStream, maskStream, expectedMaskStream); } }
From source file:doge.photo.DogePhotoManipulator.java
private static BufferedImage readClassImage(String name) { try (InputStream imgInputStream = new ClassPathResource(name).getInputStream()) { return ImageIO.read(imgInputStream); } catch (IOException e) { throw new RuntimeException(e); }/*w w w.j av a2 s.c om*/ }
From source file:com.el.ecom.utils.ImageUtils.java
/** * //from w ww .j av a 2 s. c o m * * @param srcFile ? * @param destFile * @param destWidth * @param destHeight */ public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) { Assert.notNull(srcFile); Assert.state(srcFile.exists()); Assert.state(srcFile.isFile()); Assert.notNull(destFile); Assert.state(destWidth > 0); Assert.state(destHeight > 0); if (type == Type.jdk) { Graphics2D graphics2D = null; ImageOutputStream imageOutputStream = null; ImageWriter imageWriter = null; try { BufferedImage srcBufferedImage = ImageIO.read(srcFile); int srcWidth = srcBufferedImage.getWidth(); int srcHeight = srcBufferedImage.getHeight(); int width = destWidth; int height = destHeight; if (srcHeight >= srcWidth) { width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth)); } else { height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight)); } BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB); graphics2D = destBufferedImage.createGraphics(); graphics2D.setBackground(BACKGROUND_COLOR); graphics2D.clearRect(0, 0, destWidth, destHeight); graphics2D.drawImage(srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), (destWidth / 2) - (width / 2), (destHeight / 2) - (height / 2), null); imageOutputStream = ImageIO.createImageOutputStream(destFile); imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName())) .next(); imageWriter.setOutput(imageOutputStream); ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam(); imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0)); imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam); imageOutputStream.flush(); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { if (graphics2D != null) { graphics2D.dispose(); } if (imageWriter != null) { imageWriter.dispose(); } try { if (imageOutputStream != null) { imageOutputStream.close(); } } catch (IOException e) { } } } else { IMOperation operation = new IMOperation(); operation.thumbnail(destWidth, destHeight); operation.gravity("center"); operation.background(toHexEncoding(BACKGROUND_COLOR)); operation.extent(destWidth, destHeight); operation.quality((double) DEST_QUALITY); try { operation.addImage(srcFile.getCanonicalPath()); operation.addImage(destFile.getCanonicalPath()); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } if (type == Type.graphicsMagick) { ConvertCmd convertCmd = new ConvertCmd(true); if (graphicsMagickPath != null) { convertCmd.setSearchPath(graphicsMagickPath); } try { convertCmd.run(operation); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage(), e); } catch (IM4JavaException e) { throw new RuntimeException(e.getMessage(), e); } } else { ConvertCmd convertCmd = new ConvertCmd(false); if (imageMagickPath != null) { convertCmd.setSearchPath(imageMagickPath); } try { convertCmd.run(operation); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage(), e); } catch (IM4JavaException e) { throw new RuntimeException(e.getMessage(), e); } } } }
From source file:de.steilerdev.myVerein.server.model.GridFSRepository.java
public GridFSFile storeClubLogo(MultipartFile clubLogoFile) throws MongoException { if (!clubLogoFile.getContentType().startsWith("image")) { logger.warn("Trying to store a club logo, which is not an image"); throw new MongoException("The file needs to be an image"); } else if (!(clubLogoFile.getContentType().equals("image/jpeg") || clubLogoFile.getContentType().equals("image/png"))) { logger.warn("Trying to store an incompatible image " + clubLogoFile.getContentType()); throw new MongoException("The used image is not compatible, please use only PNG or JPG files"); } else {//from ww w .j a va2 s.co m File clubLogoTempFile = null; try { clubLogoTempFile = File.createTempFile("tempClubLogo", "png"); clubLogoTempFile.deleteOnExit(); if (clubLogoFile.getContentType().equals("image/png")) { logger.debug("No need to convert club logo"); clubLogoFile.transferTo(clubLogoTempFile); } else { logger.info("Converting club logo file to png"); //Reading, converting and writing club logo ImageIO.write(ImageIO.read(clubLogoFile.getInputStream()), clubLogoFileFormat, clubLogoTempFile); } //Deleting current file deleteCurrentClubLogo(); try (FileInputStream clubLogoStream = new FileInputStream(clubLogoTempFile)) { logger.debug("Saving club logo"); //Saving file return gridFS.store(clubLogoStream, clubLogoFileName, clubLogoFileFormatMIME); } } catch (IOException e) { e.printStackTrace(); throw new MongoException("Unable to store file"); } finally { if (clubLogoTempFile != null) { clubLogoTempFile.delete(); } } } }
From source file:com.liusoft.dlog4j.util.ImageUtils.java
/** * ???//from w ww .j a v a 2 s .c o m * ????? * 3: 180 * 6: 90 * 8: 27090 * @param img_fn * @param orient * @throws IOException */ public static boolean rotateImage(String img_fn, int orient, String dest_fn) throws IOException { double radian = 0; switch (orient) { case 3: radian = 180.0; break; case 6: radian = 90.0; break; case 8: radian = 270.0; break; default: return false; } BufferedImage old_img = (BufferedImage) ImageIO.read(new File(img_fn)); int width = old_img.getWidth(); int height = old_img.getHeight(); BufferedImage new_img = new BufferedImage(height, width, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = new_img.createGraphics(); AffineTransform origXform = g2d.getTransform(); AffineTransform newXform = (AffineTransform) (origXform.clone()); // center of rotation is center of the panel double xRot = 0; double yRot = 0; switch (orient) { case 3: xRot = width / 2.0; yRot = height / 2.0; case 6: xRot = height / 2.0; yRot = xRot; break; case 8: xRot = width / 2.0; yRot = xRot; break; default: return false; } newXform.rotate(Math.toRadians(radian), xRot, yRot); g2d.setTransform(newXform); // draw image centered in panel g2d.drawImage(old_img, 0, 0, null); // Reset to Original g2d.setTransform(origXform); FileOutputStream out = new FileOutputStream(dest_fn); try { ImageIO.write(new_img, "JPG", out); } finally { out.close(); } return true; }