List of usage examples for javax.imageio ImageIO read
public static BufferedImage read(ImageInputStream stream) throws IOException
From source file:com.galenframework.utils.GalenUtils.java
public static File makeFullScreenshot(WebDriver driver) throws IOException, InterruptedException { // scroll up first scrollVerticallyTo(driver, 0);/*from w w w . j a v a 2 s . c om*/ byte[] bytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES); BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); int capturedWidth = image.getWidth(); int capturedHeight = image.getHeight(); long longScrollHeight = (Long) ((JavascriptExecutor) driver).executeScript( "return Math.max(" + "document.body.scrollHeight, document.documentElement.scrollHeight," + "document.body.offsetHeight, document.documentElement.offsetHeight," + "document.body.clientHeight, document.documentElement.clientHeight);"); Double devicePixelRatio = ((Number) ((JavascriptExecutor) driver) .executeScript(JS_RETRIEVE_DEVICE_PIXEL_RATIO)).doubleValue(); int scrollHeight = (int) longScrollHeight; File file = File.createTempFile("screenshot", ".png"); int adaptedCapturedHeight = (int) (((double) capturedHeight) / devicePixelRatio); BufferedImage resultingImage; if (Math.abs(adaptedCapturedHeight - scrollHeight) > 40) { int scrollOffset = adaptedCapturedHeight; int times = scrollHeight / adaptedCapturedHeight; int leftover = scrollHeight % adaptedCapturedHeight; final BufferedImage tiledImage = new BufferedImage(capturedWidth, (int) (((double) scrollHeight) * devicePixelRatio), BufferedImage.TYPE_INT_RGB); Graphics2D g2dTile = tiledImage.createGraphics(); g2dTile.drawImage(image, 0, 0, null); int scroll = 0; for (int i = 0; i < times - 1; i++) { scroll += scrollOffset; scrollVerticallyTo(driver, scroll); BufferedImage nextImage = ImageIO.read( new ByteArrayInputStream(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES))); g2dTile.drawImage(nextImage, 0, (i + 1) * capturedHeight, null); } if (leftover > 0) { scroll += scrollOffset; scrollVerticallyTo(driver, scroll); BufferedImage nextImage = ImageIO.read( new ByteArrayInputStream(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES))); BufferedImage lastPart = nextImage.getSubimage(0, nextImage.getHeight() - (int) (((double) leftover) * devicePixelRatio), nextImage.getWidth(), leftover); g2dTile.drawImage(lastPart, 0, times * capturedHeight, null); } scrollVerticallyTo(driver, 0); resultingImage = tiledImage; } else { resultingImage = image; } if (GalenConfig.getConfig().shouldAutoresizeScreenshots()) { try { resultingImage = GalenUtils.resizeScreenshotIfNeeded(driver, resultingImage); } catch (Exception ex) { LOG.trace("Couldn't resize screenshot", ex); } } ImageIO.write(resultingImage, "png", file); return file; }
From source file:common.utils.ImageUtils.java
/** * resize input image to new dinesions(only smaller) and save it to outputStream * @param file_stream input image for scaling * @param new_width desired value of width in result image * @param rez writes resulting image to a file * @throws IOException/*from ww w. j a v a 2 s .c o m*/ */ public static void saveScaledImageWidth(File file_stream, int new_width, OutputStream rez) throws IOException { //long time = System.nanoTime(); BufferedImage image = ImageIO.read(file_stream); double scale_factor = getScaling(image.getWidth(), new_width); saveScaledImageWidth(image, scale_factor, rez); }
From source file:com.gst.infrastructure.documentmanagement.data.ImageData.java
public void resizeImage(InputStream in, OutputStream out, int maxWidth, int maxHeight) throws IOException { BufferedImage src = ImageIO.read(in); if (src.getWidth() <= maxWidth && src.getHeight() <= maxHeight) { out.write(getContent());/*from w ww . j a v a 2s .c o m*/ return; } float widthRatio = (float) src.getWidth() / maxWidth; float heightRatio = (float) src.getHeight() / maxHeight; float scaleRatio = widthRatio > heightRatio ? widthRatio : heightRatio; // TODO(lindahl): Improve compressed image quality (perhaps quality // ratio) int newWidth = (int) (src.getWidth() / scaleRatio); int newHeight = (int) (src.getHeight() / scaleRatio); int colorModel = fileExtension == ContentRepositoryUtils.IMAGE_FILE_EXTENSION.JPEG ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(newWidth, newHeight, colorModel); Graphics2D g = target.createGraphics(); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(src, 0, 0, newWidth, newHeight, Color.BLACK, null); g.dispose(); ImageIO.write(target, fileExtension != null ? fileExtension.getValueWithoutDot() : "jpeg", out); }
From source file:UploadImage.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // change the following parameters to connect to the oracle database String username = "lingbo"; String password = "TlboSci1994"; String drivername = "oracle.jdbc.driver.OracleDriver"; String dbstring = "jdbc:oracle:thin:@gwynne.cs.ualberta.ca:1521:CRS"; int pic_id;/*from w w w. j a va 2 s . c om*/ try { //Parse the HTTP request to get the image stream DiskFileUpload fu = new DiskFileUpload(); List FileItems = fu.parseRequest(request); // Process the uploaded items, assuming only 1 image file uploaded Iterator i = FileItems.iterator(); FileItem item = (FileItem) i.next(); while (i.hasNext() && item.isFormField()) { item = (FileItem) i.next(); } //Get the image stream InputStream instream = item.getInputStream(); BufferedImage img = ImageIO.read(instream); BufferedImage thumbNail = shrink(img, 10); // Connect to the database and create a statement Connection conn = getConnected(drivername, dbstring, username, password); Statement stmt = conn.createStatement(); /* * First, to generate a unique pic_id using an SQL sequence */ ResultSet rset1 = stmt.executeQuery("SELECT pic_id_sequence.nextval from dual"); rset1.next(); pic_id = rset1.getInt(1); //Insert an empty blob into the table first. Note that you have to //use the Oracle specific function empty_blob() to create an empty blob stmt.execute("INSERT INTO pictures VALUES(" + pic_id + ",'test',empty_blob())"); // to retrieve the lob_locator // Note that you must use "FOR UPDATE" in the select statement String cmd = "SELECT * FROM pictures WHERE pic_id = " + pic_id + " FOR UPDATE"; ResultSet rset = stmt.executeQuery(cmd); rset.next(); BLOB myblob = ((OracleResultSet) rset).getBLOB(3); //Write the image to the blob object OutputStream outstream = myblob.setBinaryStream(1); ImageIO.write(thumbNail, "jpg", outstream); /* int size = myblob.getBufferSize(); byte[] buffer = new byte[size]; int length = -1; while ((length = instream.read(buffer)) != -1) outstream.write(buffer, 0, length); */ instream.close(); outstream.close(); stmt.executeUpdate("commit"); response_message = " Upload OK! "; conn.close(); } catch (Exception ex) { //System.out.println( ex.getMessage()); response_message = ex.getMessage(); } //Output response to the client response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<HTML>\n" + "<HEAD><TITLE>Upload Message</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>" + response_message + "</H1>\n" + "</BODY></HTML>"); }
From source file:ch.astina.hesperid.web.pages.report.ReportIndex.java
protected JasperPrint createReport() throws Exception { JasperDesign jasperDesign = JRXmlLoader .load(new ByteArrayInputStream(reportType.getJasperXmlCode().getBytes())); JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign); Map<String, Object> parameters = new HashMap<String, Object>(); Image logo = ImageIO.read(getClass().getClassLoader().getResourceAsStream("hesperid-logo-blue-big.jpeg")); parameters.put("logo", logo); parameters.put("reportTitle", reportType.getName()); List hqlResult = hqlDAO.getExecuteHql(reportType.getHqlQuery()); JRBeanCollectionDataSource hqlResultDataSource = new JRBeanCollectionDataSource(hqlResult); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, hqlResultDataSource); return jasperPrint; }
From source file:info.magnolia.filesystembrowser.app.imageprovider.FSImageProvider.java
private Resource scaleImage(File file) { FileInputStream fis = null;/* www .ja va2s . c o m*/ try { fis = new FileInputStream(file); final BufferedImage img = ImageIO.read(fis); if (img != null) { int width = img.getWidth(); int height = img.getHeight(); BufferedImage result = img; if (width > 200) { double ratio = (double) height / width; int newWidth = 200; int newHeight = (int) (newWidth * ratio); result = new ScaleFilter(newWidth, newHeight).filter(img, null); result = new CropFilter(0, 0, newWidth, newHeight).filter(result, null); } final InputStream is = createStreamSource(result, "png"); StreamResource.StreamSource streamSource = new StreamResource.StreamSource() { @Override public InputStream getStream() { return is; } }; return new StreamResource(streamSource, "image" + System.currentTimeMillis() + ".png"); } } catch (IOException e) { log.error("Failed to scale a resource {}.", file, e); } finally { IOUtils.closeQuietly(fis); } return null; }
From source file:dotaSoundEditor.Helpers.PortraitFinder.java
private void buildItemPortraits(VPKArchive vpk) { BufferedImage image = null;// w w w . ja v a 2 s. c o m for (VPKEntry entry : vpk.getEntriesForDir("resource/flash3/images/items/")) { if (entry.getType().equals("png")) { File imageFile = new File(entry.getPath()); try (FileChannel fc = FileUtils.openOutputStream(imageFile).getChannel()) { fc.write(entry.getData()); image = ImageIO.read(imageFile); String item = entry.getName(); portraitMap.put(item, image); } catch (IOException ex) { System.err.println("Can't write " + entry.getPath() + ": " + ex.getMessage()); } } } }
From source file:com.ctsim.dmi.MainFrame.java
/** * Creates new form MainFrame/*from w w w . j av a 2s . co m*/ */ public MainFrame() { initComponents(); timer = new Timer(30, this); timer.start(); t1 = Calendar.getInstance(); try { brake_indicator_yellow = ImageIO.read(FileUtils .toFile(this.getClass().getClassLoader().getResource("img/brake_indicator_yellow.png"))); brake_indicator_red = ImageIO.read( FileUtils.toFile(this.getClass().getClassLoader().getResource("img/brake_indicator_red.png"))); speedoDial = ImageIO .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/speedo_dial.png"))); speedoPinWhite = ImageIO.read( FileUtils.toFile(this.getClass().getClassLoader().getResource("img/speedo_pin_white.png"))); speedoPinYellow = ImageIO.read( FileUtils.toFile(this.getClass().getClassLoader().getResource("img/speedo_pin_yellow.png"))); speedoPinRed = ImageIO .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/speedo_pin_red.png"))); targetDestination = ImageIO.read( FileUtils.toFile(this.getClass().getClassLoader().getResource("img/target_destination.png"))); atp_status_auto = ImageIO.read( FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atp_status_auto.png"))); atp_status_mcs = ImageIO .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atp_status_mcs.png"))); atp_status_atb = ImageIO .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atp_status_atb.png"))); atp_status_yard_sr = ImageIO.read( FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atp_status_yard_sr.png"))); atp_status_yard_eoa = ImageIO.read( FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atp_status_yard_eoa.png"))); atp_status_line_sr = ImageIO.read( FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atp_status_line_sr.png"))); atp_status_rv = ImageIO .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atp_status_rv.png"))); atp_blank = ImageIO .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atp_blank.png"))); atenna_yellow = ImageIO .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atena_yellow.png"))); atenna_green = ImageIO .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atena_green.png"))); atenna_fail = ImageIO .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/atena_fail.png"))); ato_status_ok = ImageIO .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/ato_status_ok.png"))); ato_status_fail = ImageIO.read( FileUtils.toFile(this.getClass().getClassLoader().getResource("img/ato_status_fail.png"))); door_indicator_both = ImageIO.read( FileUtils.toFile(this.getClass().getClassLoader().getResource("img/door_indicator_both.png"))); door_indicator_left = ImageIO.read( FileUtils.toFile(this.getClass().getClassLoader().getResource("img/door_indicator_left.png"))); door_indicator_right = ImageIO.read( FileUtils.toFile(this.getClass().getClassLoader().getResource("img/door_indicator_right.png"))); door_status_close = ImageIO.read( FileUtils.toFile(this.getClass().getClassLoader().getResource("img/door_status_close.png"))); door_status_open = ImageIO.read( FileUtils.toFile(this.getClass().getClassLoader().getResource("img/door_status_open.png"))); scroll_arrow = ImageIO .read(FileUtils.toFile(this.getClass().getClassLoader().getResource("img/scroll_arrow.png"))); } catch (IOException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:de.ailis.wlandsuite.PackHtds.java
/** * @see de.ailis.wlandsuite.cli.PackProg#pack(java.io.File, * java.io.OutputStream)/*from w w w.j a v a 2 s .c o m*/ */ @Override public void pack(File directory, OutputStream output) throws IOException { Htds htds; List<HtdsTileset> tilesets; List<Pic> tiles; int tilesetNo, tileNo; File file; File tilesetDir; tilesets = new ArrayList<HtdsTileset>(); tilesetNo = 0; while (true) { tileNo = 0; tilesetDir = new File( String.format("%s%c%03d", new Object[] { directory.getPath(), File.separatorChar, tilesetNo })); if (!tilesetDir.exists()) { break; } log.info("Reading tileset " + tilesetNo); tiles = new ArrayList<Pic>(); while (true) { file = new File(String.format("%s%c%03d.png", new Object[] { tilesetDir.getPath(), File.separatorChar, tileNo })); if (!file.exists()) { break; } tiles.add(new Pic(ImageIO.read(file))); tileNo++; } tilesets.add(new HtdsTileset(tiles)); tilesetNo++; } htds = new Htds(tilesets); if (this.disk == -1) { htds.write(output); } else { htds.write(output, this.disk); } }
From source file:com.tdclighthouse.prototype.services.callbacks.ImageCreationCallBack.java
@Override public String doInSession(Session session) throws RepositoryException { String result = null;/* w w w . j a va2 s .co m*/ try { // FIXME refactor Node node = createImageSetNode(session, contentType); result = DocumentManager.getHandle(node).getIdentifier(); String mimeType = new MimetypesFileTypeMap().getContentType(file); Node galleryProcessorService = session.getNode(PluginConstants.Paths.GALLERY_PROCESSOR_SERVICE); for (NodeIterator sizes = galleryProcessorService.getNodes(); sizes.hasNext();) { Node size = sizes.nextNode(); if (size.isNodeType(PluginConstants.NodeType.FRONTEND_PLUGINCONFIG)) { Node subjectNode = getNode(node, size.getName(), PluginConstants.NodeType.HIPPOGALLERY_IMAGE); Long height = size.getProperty(PluginConstants.PropertyName.HEIGHT).getLong(); Long width = size.getProperty(PluginConstants.PropertyName.WIDTH).getLong(); BufferedImage bufferedImage = ImageIO.read(file); InputStream inputStream; if (height == 0 && width == 0) { inputStream = new FileInputStream(file); height = (long) bufferedImage.getHeight(); width = (long) bufferedImage.getWidth(); } else { ImageSize scaledSize = getScaledSize(height, width, bufferedImage); BufferedImage scaledImage = ImageUtils.scaleImage(bufferedImage, scaledSize.width.intValue(), scaledSize.height.intValue(), ScalingStrategy.BEST_QUALITY); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ImageIO.write(scaledImage, "jpg", byteArrayOutputStream); byteArrayOutputStream.flush(); inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); height = (long) scaledImage.getHeight(); width = (long) scaledImage.getWidth(); } subjectNode.setProperty(PluginConstants.PropertyName.JCR_DATA, session.getValueFactory().createBinary(inputStream)); subjectNode.setProperty(PluginConstants.PropertyName.JCR_MIME_TYPE, mimeType); subjectNode.setProperty(PluginConstants.PropertyName.JCR_LAST_MODIFIED, new GregorianCalendar()); subjectNode.setProperty(PluginConstants.PropertyName.HIPPOGALLERY_HEIGHT, height); subjectNode.setProperty(PluginConstants.PropertyName.HIPPOGALLERY_WIDTH, width); } } } catch (IOException | WorkflowException e) { throw new RepositoryException(e); } return result; }