List of usage examples for java.awt Image getHeight
public abstract int getHeight(ImageObserver observer);
From source file:org.jfree.experimental.swt.SWTGraphics2D.java
/** * Draws an image./*from w w w . j av a 2 s. com*/ * * @param image the image (<code>null</code> not permitted). * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * @param bgcolor the background colour. * @param observer an image observer. * * @return A boolean. */ public boolean drawImage(Image image, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) { ParamChecks.nullNotPermitted(image, "image"); int w = image.getWidth(null); int h = image.getHeight(null); if (w == -1 || h == -1) { return false; } Paint savedPaint = getPaint(); fill(new Rectangle2D.Double(x, y, w, h)); setPaint(savedPaint); return drawImage(image, x, y, width, height, observer); }
From source file:org.eclipse.birt.chart.device.g2d.G2dRendererBase.java
/** * Scales image according to output DPI. If 96, do not need to scale * /*w w w . ja v a 2 s . co m*/ * @param img * @return */ private java.awt.Image scaleImage(java.awt.Image img) { if (this._ids.getDpiResolution() == 96) { // Do not scale in normal dpi return img; } double scale = this._ids.getDpiResolution() / 96d; int newWidth = (int) (img.getWidth((ImageObserver) getDisplayServer().getObserver()) * scale); int newHeight = (int) (img.getHeight((ImageObserver) getDisplayServer().getObserver()) * scale); return img.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT); }
From source file:Jpeg.java
public JpegInfo(Image image) { Components = new Object[NumberOfComponents]; compWidth = new int[NumberOfComponents]; compHeight = new int[NumberOfComponents]; BlockWidth = new int[NumberOfComponents]; BlockHeight = new int[NumberOfComponents]; imageobj = image;// w w w. j ava 2 s . co m imageWidth = image.getWidth(null); imageHeight = image.getHeight(null); Comment = "JPEG Encoder Copyright 1998, James R. Weeks and BioElectroMech. "; getYCCArray(); }
From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfGraphics2D.java
/** * @see Graphics#drawImage(Image, int, int, Color, ImageObserver) *//*from w w w. ja v a 2s . c o m*/ @Override public boolean drawImage(final Image img, final int x, final int y, final Color bgcolor, final ImageObserver observer) { waitForImage(img); return drawImage(img, x, y, img.getWidth(observer), img.getHeight(observer), bgcolor, observer); }
From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfGraphics2D.java
/** * @see Graphics#drawImage(Image, int, int, int, int, Color, ImageObserver) *///from w w w .j a v a 2 s .c om @Override public boolean drawImage(final Image img, final int x, final int y, final int width, final int height, final Color bgcolor, final ImageObserver observer) { waitForImage(img); final double scalex = width / (double) img.getWidth(observer); final double scaley = height / (double) img.getHeight(observer); final AffineTransform tx = AffineTransform.getTranslateInstance(x, y); tx.scale(scalex, scaley); return drawImage(img, null, tx, bgcolor, observer); }
From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfLogicalPageDrawable.java
protected boolean drawImage(final RenderableReplacedContentBox content, final Image image, final com.lowagie.text.Image itextImage) { final StyleSheet layoutContext = content.getStyleSheet(); final boolean shouldScale = layoutContext.getBooleanStyleProperty(ElementStyleKeys.SCALE); final int x = (int) StrictGeomUtility.toExternalValue(content.getX()); final int y = (int) StrictGeomUtility.toExternalValue(content.getY()); final int width = (int) StrictGeomUtility.toExternalValue(content.getWidth()); final int height = (int) StrictGeomUtility.toExternalValue(content.getHeight()); if (width == 0 || height == 0) { PdfLogicalPageDrawable.logger.debug("Error: Image area is empty: " + content); return false; }//from www .j ava 2 s.c om final WaitingImageObserver obs = new WaitingImageObserver(image); obs.waitImageLoaded(); final int imageWidth = image.getWidth(obs); final int imageHeight = image.getHeight(obs); if (imageWidth < 1 || imageHeight < 1) { return false; } final Rectangle2D.Double drawAreaBounds = new Rectangle2D.Double(x, y, width, height); final AffineTransform scaleTransform; final Graphics2D g2; if (shouldScale == false) { double deviceScaleFactor = 1; final double devResolution = getMetaData() .getNumericFeatureValue(OutputProcessorFeature.DEVICE_RESOLUTION); if (getMetaData().isFeatureSupported(OutputProcessorFeature.IMAGE_RESOLUTION_MAPPING)) { if (devResolution != 72.0 && devResolution > 0) { // Need to scale the device to its native resolution before attempting to draw the image.. deviceScaleFactor = (72.0 / devResolution); } } final int clipWidth = Math.min(width, (int) Math.ceil(deviceScaleFactor * imageWidth)); final int clipHeight = Math.min(height, (int) Math.ceil(deviceScaleFactor * imageHeight)); final ElementAlignment horizontalAlignment = (ElementAlignment) layoutContext .getStyleProperty(ElementStyleKeys.ALIGNMENT); final ElementAlignment verticalAlignment = (ElementAlignment) layoutContext .getStyleProperty(ElementStyleKeys.VALIGNMENT); final int alignmentX = (int) RenderUtility.computeHorizontalAlignment(horizontalAlignment, width, clipWidth); final int alignmentY = (int) RenderUtility.computeVerticalAlignment(verticalAlignment, height, clipHeight); g2 = (Graphics2D) getGraphics().create(); g2.clip(drawAreaBounds); g2.translate(x, y); g2.translate(alignmentX, alignmentY); g2.clip(new Rectangle2D.Float(0, 0, clipWidth, clipHeight)); g2.scale(deviceScaleFactor, deviceScaleFactor); scaleTransform = null; } else { g2 = (Graphics2D) getGraphics().create(); g2.clip(drawAreaBounds); g2.translate(x, y); g2.clip(new Rectangle2D.Float(0, 0, width, height)); final double scaleX; final double scaleY; final boolean keepAspectRatio = layoutContext .getBooleanStyleProperty(ElementStyleKeys.KEEP_ASPECT_RATIO); if (keepAspectRatio) { final double scaleFactor = Math.min(width / (double) imageWidth, height / (double) imageHeight); scaleX = scaleFactor; scaleY = scaleFactor; } else { scaleX = width / (double) imageWidth; scaleY = height / (double) imageHeight; } final int clipWidth = (int) (scaleX * imageWidth); final int clipHeight = (int) (scaleY * imageHeight); final ElementAlignment horizontalAlignment = (ElementAlignment) layoutContext .getStyleProperty(ElementStyleKeys.ALIGNMENT); final ElementAlignment verticalAlignment = (ElementAlignment) layoutContext .getStyleProperty(ElementStyleKeys.VALIGNMENT); final int alignmentX = (int) RenderUtility.computeHorizontalAlignment(horizontalAlignment, width, clipWidth); final int alignmentY = (int) RenderUtility.computeVerticalAlignment(verticalAlignment, height, clipHeight); g2.translate(alignmentX, alignmentY); scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY); } final PdfGraphics2D pdfGraphics2D = (PdfGraphics2D) g2; pdfGraphics2D.drawPdfImage(itextImage, image, scaleTransform, null); g2.dispose(); return true; }
From source file:org.exoplatform.ecm.webui.component.explorer.UIDocumentInfo.java
public String getThumbnailSize(Node node) throws Exception { node = node instanceof NodeLinkAware ? ((NodeLinkAware) node).getTargetNode().getRealNode() : node; String imageSize = null;/*from w ww . jav a 2s . c o m*/ if (node.hasProperty(ThumbnailService.BIG_SIZE)) { Image image = ImageIO.read(node.getProperty(ThumbnailService.BIG_SIZE).getStream()); imageSize = Integer.toString(image.getWidth(null)) + "x" + Integer.toString(image.getHeight(null)); } return imageSize; }
From source file:org.yccheok.jstock.gui.Utils.java
public static java.awt.Image getScaledImage(Image image, int maxWidth, int maxHeight) { // This code ensures that all the pixels in the image are loaded image = new ImageIcon(image).getImage(); final int imgWidth = image.getWidth(null); final int imgHeight = image.getHeight(null); final int preferredWidth = Math.min(imgWidth, maxWidth); final int preferredHeight = Math.min(imgHeight, maxHeight); final double scaleX = (double) preferredWidth / (double) imgWidth; final double scaleY = (double) preferredHeight / (double) imgHeight; final double bestScale = Math.min(scaleX, scaleY); return image.getScaledInstance((int) ((double) imgWidth * bestScale), (int) ((double) imgHeight * bestScale), Image.SCALE_SMOOTH); }
From source file:net.yacy.http.servlets.YaCyDefaultServlet.java
/** * Handles a YaCy servlet template, reads the template and replaces the template * items with actual values. Because of supported server side includes target * might not be the same as request.getPathInfo * //from w ww.ja va 2 s. co m * @param target the path to the template * @param request the remote servlet request * @param response * @throws IOException * @throws ServletException */ protected void handleTemplate(String target, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Switchboard sb = Switchboard.getSwitchboard(); String localeSelection = sb.getConfig("locale.language", "browser"); if (localeSelection.endsWith("browser")) { String lng = request.getLocale().getLanguage(); if (lng.equalsIgnoreCase("en")) { // because en is handled as "default" in localizer localeSelection = "default"; } else { localeSelection = lng; } } File targetFile = getLocalizedFile(target, localeSelection); File targetClass = rewriteClassFile(_resourceBase.addPath(target).getFile()); String targetExt = target.substring(target.lastIndexOf('.') + 1); long now = System.currentTimeMillis(); if (target.endsWith(".css")) { response.setDateHeader(HeaderFramework.LAST_MODIFIED, now); response.setDateHeader(HeaderFramework.EXPIRES, now + 3600000); // expires in 1 hour (which is still often, others use 1 week, month or year) } else if (target.endsWith(".png")) { // expires in 1 minute (reduce heavy image creation load) if (response.containsHeader(HeaderFramework.LAST_MODIFIED)) { response.getHeaders(HeaderFramework.LAST_MODIFIED).clear(); } response.setHeader(HeaderFramework.CACHE_CONTROL, "public, max-age=" + Integer.toString(60)); } else { response.setDateHeader(HeaderFramework.LAST_MODIFIED, now); response.setDateHeader(HeaderFramework.EXPIRES, now); // expires now } if ((targetClass != null)) { serverObjects args = new serverObjects(); Enumeration<String> argNames = request.getParameterNames(); // on ssi jetty dispatcher merged local ssi query parameters while (argNames.hasMoreElements()) { String argName = argNames.nextElement(); // standard attributes are just pushed as string args.put(argName, request.getParameter(argName)); } RequestHeader legacyRequestHeader = generateLegacyRequestHeader(request, target, targetExt); // add multipart-form fields to parameter if (ServletFileUpload.isMultipartContent(request)) { final String bodyEncoding = request.getHeader(HeaderFramework.CONTENT_ENCODING); if (HeaderFramework.CONTENT_ENCODING_GZIP.equalsIgnoreCase(bodyEncoding)) { parseMultipart(new GZIPRequestWrapper(request), args); } else { parseMultipart(request, args); } } // eof modification to read attribute Object tmp; try { if (args.isEmpty()) { // yacy servlets typically test for args != null (but not for args .isEmpty()) tmp = invokeServlet(targetClass, legacyRequestHeader, null); } else { tmp = invokeServlet(targetClass, legacyRequestHeader, args); } } catch (InvocationTargetException e) { if (e.getCause() instanceof InvalidURLLicenceException) { /* A non authaurized user is trying to fetch a image with a bad or already released license code */ response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getCause().getMessage()); return; } if (e.getCause() instanceof TemplateMissingParameterException) { /* A template is used but miss some required parameter */ response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getCause().getMessage()); return; } ConcurrentLog.logException(e); throw new ServletException(targetFile.getAbsolutePath()); } catch (IllegalArgumentException | IllegalAccessException e) { ConcurrentLog.logException(e); throw new ServletException(targetFile.getAbsolutePath()); } if (tmp instanceof RasterPlotter || tmp instanceof EncodedImage || tmp instanceof Image) { net.yacy.cora.util.ByteBuffer result = null; if (tmp instanceof RasterPlotter) { final RasterPlotter yp = (RasterPlotter) tmp; // send an image to client result = RasterPlotter.exportImage(yp.getImage(), "png"); } else if (tmp instanceof EncodedImage) { final EncodedImage yp = (EncodedImage) tmp; result = yp.getImage(); /** When encodedImage is empty, return a code 500 rather than only an empty response * as it is better handled across different browsers */ if (result == null || result.length() == 0) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); result.close(); return; } if (yp.isStatic()) { // static image never expires response.setDateHeader(HeaderFramework.EXPIRES, now + 3600000); // expires in 1 hour } } else if (tmp instanceof Image) { final Image i = (Image) tmp; // generate an byte array from the generated image int width = i.getWidth(null); if (width < 0) { width = 96; // bad hack } int height = i.getHeight(null); if (height < 0) { height = 96; // bad hack } final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); bi.createGraphics().drawImage(i, 0, 0, width, height, null); result = RasterPlotter.exportImage(bi, targetExt); } updateRespHeadersForImages(target, response); final String mimeType = Classification.ext2mime(targetExt, MimeTypes.Type.TEXT_HTML.asString()); response.setContentType(mimeType); response.setContentLength(result.length()); response.setStatus(HttpServletResponse.SC_OK); result.writeTo(response.getOutputStream()); result.close(); return; } if (tmp instanceof InputStream) { /* Images and favicons can also be written directly from an inputStream */ updateRespHeadersForImages(target, response); writeInputStream(response, targetExt, (InputStream) tmp); return; } servletProperties templatePatterns; if (tmp == null) { // if no args given, then tp will be an empty Hashtable object (not null) templatePatterns = new servletProperties(); } else if (tmp instanceof servletProperties) { templatePatterns = (servletProperties) tmp; if (templatePatterns.getOutgoingHeader() != null) { // handle responseHeader entries set by servlet ResponseHeader tmpouthdr = templatePatterns.getOutgoingHeader(); for (String hdrkey : tmpouthdr.keySet()) { if (!HeaderFramework.STATUS_CODE.equals(hdrkey)) { // skip default init response status value (not std. ) String val = tmpouthdr.get(hdrkey); if (!response.containsHeader(hdrkey) && val != null) { // to be on the safe side, add only new hdr (mainly used for CORS_ALLOW_ORIGIN) response.setHeader(hdrkey, tmpouthdr.get(hdrkey)); } } } // handle login cookie if (tmpouthdr.getCookiesEntries() != null) { for (Cookie c : tmpouthdr.getCookiesEntries()) { response.addCookie(c); } } } } else { templatePatterns = new servletProperties((serverObjects) tmp); } // handle YaCy http commands // handle action auth: check if the servlets requests authentication if (templatePatterns.containsKey(serverObjects.ACTION_AUTHENTICATE)) { if (!request.authenticate(response)) { return; } //handle action forward } else if (templatePatterns.containsKey(serverObjects.ACTION_LOCATION)) { String location = templatePatterns.get(serverObjects.ACTION_LOCATION, ""); if (location.isEmpty()) { location = request.getPathInfo(); } //TODO: handle equivalent of this from httpdfilehandler // final ResponseHeader headers = getDefaultHeaders(request.getPathInfo()); // headers.setAdditionalHeaderProperties(templatePatterns.getOutgoingHeader().getAdditionalHeaderProperties()); //put the cookies into the new header TODO: can we put all headerlines, without trouble? response.setHeader(HeaderFramework.LOCATION, location); response.setStatus(HttpServletResponse.SC_FOUND); return; } if (targetFile.exists() && targetFile.isFile() && targetFile.canRead()) { sb.setConfig("server.servlets.called", appendPath(sb.getConfig("server.servlets.called", ""), target)); if (args != null && !args.isEmpty()) { sb.setConfig("server.servlets.submitted", appendPath(sb.getConfig("server.servlets.submitted", ""), target)); } // add the application version, the uptime and the client name to every rewrite table templatePatterns.put(servletProperties.PEER_STAT_VERSION, yacyBuildProperties.getVersion()); templatePatterns.put(servletProperties.PEER_STAT_UPTIME, ((System.currentTimeMillis() - sb.startupTime) / 1000) / 60); // uptime in minutes templatePatterns.putHTML(servletProperties.PEER_STAT_CLIENTNAME, sb.peers.mySeed().getName()); templatePatterns.putHTML(servletProperties.PEER_STAT_CLIENTID, sb.peers.myID()); templatePatterns.put(servletProperties.PEER_STAT_MYTIME, GenericFormatter.SHORT_SECOND_FORMATTER.format()); templatePatterns.put(servletProperties.RELATIVE_BASE, YaCyDefaultServlet.getRelativeBase(target)); Seed myPeer = sb.peers.mySeed(); templatePatterns.put("newpeer", myPeer.getAge() >= 1 ? 0 : 1); templatePatterns.putHTML("newpeer_peerhash", myPeer.hash); boolean authorized = sb.adminAuthenticated(legacyRequestHeader) >= 2; templatePatterns.put("authorized", authorized ? 1 : 0); // used in templates and other html (e.g. to display lock/unlock symbol) templatePatterns.put("simpleheadernavbar", sb.getConfig("decoration.simpleheadernavbar", "navbar-default")); // add navigation keys to enable or disable menu items templatePatterns.put("navigation-p2p", sb.getConfigBool(SwitchboardConstants.DHT_ENABLED, true) || !sb.isRobinsonMode() ? 1 : 0); templatePatterns.put("navigation-p2p_authorized", authorized ? 1 : 0); String submitted = sb.getConfig("server.servlets.submitted", ""); boolean crawler_enabled = true; /* submitted.contains("Crawler_p") || submitted.contains("ConfigBasic") || submitted.contains("Load_RSS_p");*/ boolean advanced_enabled = crawler_enabled || submitted.contains("IndexImportMediawiki_p") || submitted.contains("CrawlStart"); templatePatterns.put("navigation-crawlmonitor", crawler_enabled); templatePatterns.put("navigation-crawlmonitor_authorized", authorized ? 1 : 0); templatePatterns.put("navigation-advanced", advanced_enabled); templatePatterns.put("navigation-advanced_authorized", authorized ? 1 : 0); templatePatterns.put(SwitchboardConstants.GREETING_HOMEPAGE, sb.getConfig(SwitchboardConstants.GREETING_HOMEPAGE, "")); templatePatterns.put(SwitchboardConstants.GREETING_SMALL_IMAGE, sb.getConfig(SwitchboardConstants.GREETING_SMALL_IMAGE, "")); templatePatterns.put(SwitchboardConstants.GREETING_IMAGE_ALT, sb.getConfig(SwitchboardConstants.GREETING_IMAGE_ALT, "")); templatePatterns.put("clientlanguage", localeSelection); String mimeType = Classification.ext2mime(targetExt, MimeTypes.Type.TEXT_HTML.asString()); InputStream fis; long fileSize = targetFile.length(); if (fileSize <= Math.min(4 * 1024 * 1204, MemoryControl.available() / 100)) { // read file completely into ram, avoid that too many files are open at the same time fis = new ByteArrayInputStream(FileUtils.read(targetFile)); } else { fis = new BufferedInputStream(new FileInputStream(targetFile)); } // set response header response.setContentType(mimeType); response.setStatus(HttpServletResponse.SC_OK); ByteArrayOutputStream bas = new ByteArrayOutputStream(4096); try { // apply templates TemplateEngine.writeTemplate(targetFile.getName(), fis, bas, templatePatterns); // handle SSI parseSSI(bas.toByteArray(), request, response); } finally { try { fis.close(); } catch (IOException ignored) { ConcurrentLog.warn("FILEHANDLER", "YaCyDefaultServlet: could not close target file " + targetFile.getName()); } try { bas.close(); } catch (IOException ignored) { /* Should never happen with a ByteArrayOutputStream */ } } } } }
From source file:org.rdv.viz.image.HighResImageViz.java
/** * Print the displayed image. If no image is being displayed, this will method * will do nothing./*from w w w . j a v a 2 s . c o m*/ */ private void printImage() { // get the displayed image final Image displayedImage = getDisplayedImage(); if (displayedImage == null) { return; } // setup a print job PrinterJob printJob = PrinterJob.getPrinterJob(); // set the renderer for the image printJob.setPrintable(new Printable() { public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException { //we only have one page to print if (pageIndex != 0) { return Printable.NO_SUCH_PAGE; } Graphics2D g2d = (Graphics2D) g; // move to corner of imageable page g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); // get page dimensions double pageWidth = pageFormat.getImageableWidth(); double pageHeight = pageFormat.getImageableHeight(); // get image dimensions int imageWidth = displayedImage.getWidth(null); int imageHeight = displayedImage.getHeight(null); // get scale factor for image double widthScale = pageWidth / imageWidth; double heightScale = pageHeight / imageHeight; double scale = Math.min(widthScale, heightScale); // draw image with width and height scaled to page int scaledWidth = (int) (scale * imageWidth); int scaledHeight = (int) (scale * imageHeight); g2d.drawImage(displayedImage, 0, 0, scaledWidth, scaledHeight, null); return Printable.PAGE_EXISTS; } }); // set the job name to the channel name (plus jpg extension) // this is used as a hint for a file name when printing to file String channelName = (String) seriesList_.getChannels().iterator().next(); String jobName = channelName.replace("/", " - "); if (!jobName.endsWith(".jpg")) { jobName += ".jpg"; } printJob.setJobName(jobName); // show the print dialog and print if ok clicked if (printJob.printDialog()) { try { printJob.print(); } catch (PrinterException pe) { JOptionPane.showMessageDialog(null, "Failed to print image.", "Print Image Error", JOptionPane.ERROR_MESSAGE); pe.printStackTrace(); } } }