List of usage examples for javax.imageio ImageIO read
public static BufferedImage read(ImageInputStream stream) throws IOException
From source file:com.codenvy.corp.MainPage.java
public void gotoManageViewAndGrabCLDIDEBornDown() throws IOException, InterruptedException { driver.get(String.format(mangeViewUrlCLDIDE, agileIdPLF)); new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOf(burnDownMAinContainer)); burnDownNamePlf = new WebDriverWait(driver, 10) .until(ExpectedConditions.visibilityOfElementLocated(By.id("ghx-items-trigger"))).getText(); Thread.sleep(10000);/*ww w . j a v a 2 s .com*/ File screen = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); Point p = burnDownMAinContainer.getLocation(); int width = burnDownMAinContainer.getSize().getWidth(); int height = burnDownMAinContainer.getSize().getHeight(); BufferedImage img = ImageIO.read(screen); BufferedImage dest = img.getSubimage(p.getX(), p.getY() - 50, width, height); ImageIO.write(dest, "png", screen); File file = new File(burnDownNamePlf + ".png"); FileUtils.copyFile(screen, file); addText(file, burnDownNamePlf); }
From source file:com.piaoyou.util.ImageUtil.java
/** * @todo: xem lai ham nay, neu kich thuoc nho hon max thi ta luu truc tiep * inputStream xuong thumbnailFile luon * * This method create a thumbnail and reserve the ratio of the output image * NOTE: This method closes the inputStream after it have done its work. * * @param inputStream the stream of a jpeg file * @param outputStream the output stream * @param maxWidth the maximum width of the image * @param maxHeight the maximum height of the image * @throws IOException//from w w w . j a v a2 s. co m * @throws BadInputException */ public static void createThumbnail(InputStream inputStream, OutputStream outputStream, int maxWidth, int maxHeight) throws IOException { if (inputStream == null) { throw new IllegalArgumentException("inputStream must not be null."); } if (outputStream == null) { throw new IllegalArgumentException("outputStream must not be null."); } //boolean useSun = false; if (maxWidth <= 0) { throw new IllegalArgumentException("maxWidth must >= 0"); } if (maxHeight <= 0) { throw new IllegalArgumentException("maxHeight must >= 0"); } try { //JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(inputStream); //BufferedImage srcImage = decoder.decodeAsBufferedImage(); byte[] srcByte = FileUtil.getBytes(inputStream); InputStream is = new ByteArrayInputStream(srcByte); //ImageIcon imageIcon = new ImageIcon(srcByte); //Image srcImage = imageIcon.getImage(); BufferedImage srcImage = ImageIO.read(is); if (srcImage == null) { throw new IOException("Cannot decode image. Please check your file again."); } int imgWidth = srcImage.getWidth(); int imgHeight = srcImage.getHeight(); // imgWidth or imgHeight could be -1, which is considered as an assertion AssertionUtil.doAssert((imgWidth > 0) && (imgHeight > 0), "Assertion: ImageUtil: cannot get the image size."); // Set the scale. AffineTransform tx = new AffineTransform(); if ((imgWidth > maxWidth) || (imgHeight > maxHeight)) { double scaleX = (double) maxWidth / imgWidth; double scaleY = (double) maxHeight / imgHeight; double scaleRatio = (scaleX < scaleY) ? scaleX : scaleY; imgWidth = (int) (imgWidth * scaleX); imgWidth = (imgWidth == 0) ? 1 : imgWidth; imgHeight = (int) (imgHeight * scaleY); imgHeight = (imgHeight == 0) ? 1 : imgHeight; // scale as needed tx.scale(scaleRatio, scaleRatio); } else {// we don't need any transform here, just save it to file and return outputStream.write(srcByte); return; } // create thumbnail image BufferedImage bufferedImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g = bufferedImage.createGraphics(); boolean useTransform = false; if (useTransform) {// use transfrom to draw //log.trace("use transform"); g.drawImage(srcImage, tx, null); } else {// use java filter //log.trace("use filter"); Image scaleImage = getScaledInstance(srcImage, imgWidth, imgHeight); g.drawImage(scaleImage, 0, 0, null); } g.dispose();// free resource // write it to outputStream // JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream); // encoder.encode(bufferedImage); ImageIO.write(bufferedImage, "jpeg", outputStream); } catch (IOException e) { log.error("Error", e); throw e; } finally {// this finally is very important try { inputStream.close(); } catch (IOException e) { /* ignore */ e.printStackTrace(); } try { outputStream.close(); } catch (IOException e) {/* ignore */ e.printStackTrace(); } } }
From source file:com.capstone.giveout.controllers.UsersController.java
private void saveImages(User user, MultipartFile image) throws IOException { if (image == null || image.isEmpty()) return;//from w ww .j av a 2 s . c o m BufferedImage img = ImageIO.read(image.getInputStream()); ImageFileManager imgMan = ImageFileManager.get(USERS_ROOT_PATH); imgMan.saveImage(user.getId(), User.SIZE_FULL, img); user.setImageUrlFull(Routes.USERS_IMAGE_PATH.replace("{id}", String.valueOf(user.getId())).replace("{size}", User.SIZE_FULL)); BufferedImage scaledImg = Scalr.resize(img, 640); imgMan.saveImage(user.getId(), User.SIZE_MEDIUM, scaledImg); user.setImageUrlMedium(Routes.USERS_IMAGE_PATH.replace("{id}", String.valueOf(user.getId())) .replace("{size}", User.SIZE_MEDIUM)); users.save(user); }
From source file:ispok.pres.bb.NewVisitor.java
/** * * @return/* w w w .java2s . c om*/ */ public String addVisitor() { PostalCodeDto postalCodeDto = new PostalCodeDto(postalCode); postalCodeService.savePostalCode(postalCodeDto); CityDto cityDto = new CityDto(city); cityService.saveCity(cityDto); RegionDto regionDto = new RegionDto(region); regionService.saveRegion(regionDto); DomicileDto domicileDto = new DomicileDto(); domicileDto.setAddress1(address); domicileDto.setCityId(cityDto.getId()); domicileDto.setPostalCodeId(postalCodeDto.getId()); logger.debug("Country: {}", countryId); domicileDto.setCountryId(countryId); domicileDto.setRegionId(regionDto.getId()); domicileService.saveDomicile(domicileDto); VisitorDto visitorDto = new VisitorDto(); visitorDto.setFirstName(firstName); visitorDto.setLastName(lastName); visitorDto.setBirthDate(birthDate); visitorDto.setNin(nin); visitorDto.setNickname(nickname); visitorDto.setTelephone(telephone); visitorDto.setEmail(email); visitorDto.setSex(sex); visitorDto.setPassword(password); visitorDto.setBonusPoints(0); logger.debug("Citizenship: {}", citizenshipId); if (citizenshipId == null) { citizenshipId = countryId; } visitorDto.setCitizenshipId(citizenshipId); visitorDto.setDomicileId(domicileDto.getId()); try { logger.trace("Read photo file"); logger.debug("Photo name: {}", photoFile.getFileName()); BufferedImage originalPhotoImage = ImageIO.read(photoFile.getInputstream()); int width = originalPhotoImage.getWidth(); int height = originalPhotoImage.getHeight(); float scaleFactorNormalize; float scaleFactorThumb; if (height > width) { scaleFactorThumb = (float) 200 / height; scaleFactorNormalize = (float) 500 / height; } else { scaleFactorThumb = (float) 200 / width; scaleFactorNormalize = (float) 500 / width; } logger.debug("Scale factor for normalized photo: {}", scaleFactorNormalize); logger.debug("Scale factor for photo thumbnail: {}", scaleFactorThumb); // Image scaledImage = bi.getScaledInstance((int) (width * scaleFactor), (int) (height * scaleFactor), Image.SCALE_SMOOTH); // BufferedImage resizedImage = new BufferedImage((int) (width * scaleFactor), (int) (height * scaleFactor), bi.getType()); // Graphics2D g = resizedImage.createGraphics(); // g.drawImage(scaledImage, 0, 0, new Color(0, 0, 0), null); // g.dispose(); // // BufferedImage resizedImage = bi.getScaledInstance(width, height, width) // AffineTransform at = AffineTransform.getScaleInstance(scaleFactor, scaleFactor); // AffineTransformOp ato = new AffineTransformOp(at, null); // Graphics2D g = bi.createGraphics(); // g.drawImage(bi, ato, 0, 0); // g.dispose(); // int normalizedWidth = (int) (width * scaleFactorNormalize); int normalizeHeight = (int) (height * scaleFactorNormalize); logger.debug("Normalized Width: {}", normalizedWidth); logger.debug("Normalized Height: {}", normalizeHeight); int thumbWidth = (int) (width * scaleFactorThumb); int thumbHeight = (int) (height * scaleFactorThumb); logger.debug("Thumb width: {}", thumbWidth); logger.debug("Thumb height: {}", thumbHeight); BufferedImage normalizedPhotoImage = ImageUtil.resizeImage(originalPhotoImage, normalizedWidth, normalizeHeight); logger.debug("Width of normalized photo: {}", normalizedPhotoImage.getWidth()); logger.debug("Height of normalized photo: {}", normalizedPhotoImage.getHeight()); BufferedImage thumbPhotoImage = ImageUtil.resizeImage(originalPhotoImage, thumbWidth, thumbHeight); logger.debug("Width of thumb photo: {}", thumbPhotoImage.getWidth()); logger.debug("Height of thumb photo: {}", thumbPhotoImage.getHeight()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(normalizedPhotoImage, "png", baos); baos.flush(); normalizedPhotoData = baos.toByteArray(); baos = new ByteArrayOutputStream(); ImageIO.write(thumbPhotoImage, "png", baos); baos.flush(); thumbPhotoData = baos.toByteArray(); } catch (IOException ex) { logger.catching(ex); } if (photoFile != null) { visitorDto.setPhoto(normalizedPhotoData); } else { visitorDto.setPhoto(new byte[0]); } if ("".equals(password)) { password = RandomString.getRandomString(6); } visitorService.addVisitor(visitorDto); id = visitorDto.getId(); return "/admin/management/visitors/confirmNew.xhtml"; }
From source file:org.shredzone.cilla.admin.AbstractImageBean.java
/** * Creates a {@link StreamedContent} for the given {@link DataHandler}, with the image * having the given width and height. The aspect ratio is kept. A PNG type image is * returned./*www.j ava 2 s . c om*/ * <p> * <em>NOTE:</em> The scaled image is cached related to the {@link DataHandler}. Thus, * it is not possible to create different sizes of the same {@link DataHandler} using * this method. A weak cache is used, to keep the memory footprint as small as * possible. * * @param dh * {@link DataHandler} to stream * @param process * Width, height and image type to be used * @return {@link StreamedContent} containing that image */ protected StreamedContent createStreamedContent(DataHandler dh, ImageProcessing process) { byte[] scaledData = null; if (dh != null) { scaledData = weakScaleCache.get(dh); if (scaledData == null) { try { BufferedImage image = ImageIO.read(dh.getInputStream()); if (image != null) { BufferedImage scaled = scale(image, process.getWidth(), process.getHeight()); try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { ImageIO.write(scaled, process.getType().getFormatName(), bos); scaledData = bos.toByteArray(); } if (weakScaleCache.size() < maxCache) { weakScaleCache.put(dh, scaledData); } } } catch (IOException ex) { log.error("Exception while streaming scaled content: " + dh.getName(), ex); } } } if (scaledData != null) { return new DefaultStreamedContent(new ByteArrayInputStream(scaledData), process.getType().getContentType()); } else { return createEmptyStreamedContent(); } }
From source file:at.tuwien.ifs.somtoolbox.apps.viewer.fileutils.ExportUtils.java
public static void drawLinkInfo(GrowingLayer growingLayer, MapPNode mapPnode, double unitWidth, Graphics2D graphics, String dataFilesPrefix) { int width = (int) unitWidth; for (int x = 0; x < growingLayer.getXSize(); x++) { for (int y = 0; y < growingLayer.getYSize(); y++) { try { if (growingLayer.getUnit(x, y) != null) { String[] mappedData = growingLayer.getUnit(x, y).getMappedInputNames(); if (mappedData != null) { boolean hasValidLink = false; for (String element : mappedData) { if (new File(dataFilesPrefix + element).exists()) { hasValidLink = true; break; }/*ww w .j a va 2s .c o m*/ } if (hasValidLink) { try { BufferedImage icon = ImageIO.read(new FileInputStream(ExportUtils.class .getResource(RESOURCE_PATH_ICONS + "note.png").getFile())); // icon = scaleImageByHeight(icon, (int) (unitWidth - 2)); int iconHeight = (int) (unitWidth * 0.7); int iconWidth = (int) ((double) iconHeight / (double) icon.getHeight() * icon.getWidth()); int restWidth = (width - iconWidth) / 2; int restHeight = (width - iconHeight) / 2; graphics.drawImage(icon, x * width + restWidth, y * width + restHeight, iconWidth, iconHeight, null); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } catch (LayerAccessException e) { // should not happen e.printStackTrace(); } } } }
From source file:com.silverpeas.util.ImageUtil.java
public static String[] getWidthAndHeightByHeight(InputStream image, int heightParam) { String[] result = new String[2]; try {//from ww w .ja va2s . c om BufferedImage inputBuf = ImageIO.read(image); // calcul de la taille de la sortie double inputBufWidth; double inputBufHeight; double height; double ratio; double width; if (inputBuf.getHeight() > heightParam) { inputBufHeight = inputBuf.getHeight(); inputBufWidth = inputBuf.getWidth(); height = heightParam; ratio = inputBufHeight / height; width = inputBufWidth / ratio; } else { height = inputBuf.getHeight(); width = inputBuf.getWidth(); } String sWidth = Double.toString(width); String sHeight = Double.toString(height); result[0] = sWidth.substring(0, sWidth.indexOf('.')); result[1] = sHeight.substring(0, sHeight.indexOf('.')); return result; } catch (Exception e) { SilverTrace.error("util", "ImageUtil.getWidthAndHeightByHeight", "root.MSG_GEN_ERROR", e); } return result; }
From source file:CubaHSQLDBServer.java
private CubaHSQLDBServer() { Font monospaced = Font.decode("monospaced"); statusArea = new JTextArea(2, 80); statusArea.setFont(monospaced);/*ww w . j a va 2 s . c o m*/ statusArea.setMargin(new Insets(5, 5, 5, 5)); exceptionArea = new JTextArea(26, 80); exceptionArea.setFont(monospaced); exceptionArea.setMargin(new Insets(5, 5, 5, 5)); JPanel exceptionWrapperContainer = new JPanel(); exceptionWrapperContainer.setLayout(new BorderLayout(0, 0)); exceptionWrapperContainer.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1)); exceptionWrapperContainer.add(exceptionArea); JPanel statusWrapperContainer = new JPanel(); statusWrapperContainer.setLayout(new BorderLayout(0, 0)); statusWrapperContainer.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1)); statusWrapperContainer.add(statusArea); addCopyPopup(statusArea); addCopyPopup(exceptionArea); exceptionBox = new JPanel(); LayoutBuilder.create(exceptionBox, BoxLayout.Y_AXIS).addSpace(5).addComponent(exceptionWrapperContainer); LayoutBuilder.create(this.getContentPane(), BoxLayout.X_AXIS).addSpace(5).addContainer(BoxLayout.Y_AXIS) .addSpace(5).addComponent(statusWrapperContainer).addComponent(exceptionBox).addSpace(5) .returnToParent().addSpace(5); statusArea.setEditable(false); exceptionArea.setEditable(false); exceptionBox.setVisible(false); exceptionArea.setBackground(new Color(255, 255, 212)); this.pack(); this.setResizable(true); this.setTitle("HSQLDB Server"); try { this.setIconImage(ImageIO.read(getClass().getResourceAsStream("/icons/database.png"))); } catch (IOException e) { throw new IllegalStateException("Unable to find icon for HSQLDB window"); } }
From source file:info.fetter.rrdclient.GraphCommand.java
protected void parseOutput(byte[] output) throws IOException { if (isOutputParsed) return;/*from w w w.j av a 2 s.c o m*/ ByteArrayInputStream in = new ByteArrayInputStream(output); image = ImageIO.read(in); if (logger.isTraceEnabled()) logger.trace("Image size : " + image.getWidth() + "x" + image.getHeight()); isOutputParsed = true; }