List of usage examples for java.awt Image getHeight
public abstract int getHeight(ImageObserver observer);
From source file:com.xpn.xwiki.plugin.image.ImagePlugin.java
/** * Reduces the size (i.e. the number of bytes) of an image by scaling its width and height and by reducing its * compression quality. This helps decreasing the time needed to download the image attachment. * //from w w w .j a v a 2 s. c o m * @param attachment the image to be shrunk * @param requestedWidth the desired image width; this value is taken into account only if it is greater than zero * and less than the current image width * @param requestedHeight the desired image height; this value is taken into account only if it is greater than zero * and less than the current image height * @param keepAspectRatio {@code true} to preserve the image aspect ratio even when both requested dimensions are * properly specified (in this case the image will be resized to best fit the rectangle with the * requested width and height), {@code false} otherwise * @param requestedQuality the desired compression quality * @param context the XWiki context * @return the modified image attachment * @throws Exception if shrinking the image fails */ private XWikiAttachment shrinkImage(XWikiAttachment attachment, int requestedWidth, int requestedHeight, boolean keepAspectRatio, float requestedQuality, XWikiContext context) throws Exception { Image image = this.imageProcessor.readImage(attachment.getContentInputStream(context)); // Compute the new image dimension. int currentWidth = image.getWidth(null); int currentHeight = image.getHeight(null); int[] dimensions = reduceImageDimensions(currentWidth, currentHeight, requestedWidth, requestedHeight, keepAspectRatio); float quality = requestedQuality; if (quality < 0) { // If no scaling is needed and the quality parameter is not specified, return the original image. if (dimensions[0] == currentWidth && dimensions[1] == currentHeight) { return attachment; } quality = this.defaultQuality; } // Scale the image to the new dimensions. RenderedImage shrunkImage = this.imageProcessor.scaleImage(image, dimensions[0], dimensions[1]); // Write the shrunk image to a byte array output stream. ByteArrayOutputStream bout = new ByteArrayOutputStream(); this.imageProcessor.writeImage(shrunkImage, attachment.getMimeType(context), quality, bout); // Create an image attachment for the shrunk image. XWikiAttachment thumbnail = (XWikiAttachment) attachment.clone(); thumbnail.setContent(new ByteArrayInputStream(bout.toByteArray()), bout.size()); return thumbnail; }
From source file:com.openbravo.pos.util.ThumbNailBuilder.java
private Image createThumbNail(Image img) { // MaskFilter filter = new MaskFilter(Color.WHITE); // ImageProducer prod = new FilteredImageSource(img.getSource(), filter); // img = Toolkit.getDefaultToolkit().createImage(prod); int targetw;//from w ww . j a va 2 s .c o m int targeth; double scalex = (double) m_width / (double) img.getWidth(null); double scaley = (double) m_height / (double) img.getHeight(null); if (scalex < scaley) { targetw = m_width; targeth = (int) (img.getHeight(null) * scalex); } else { targetw = (int) (img.getWidth(null) * scaley); targeth = (int) m_height; } int midw = img.getWidth(null); int midh = img.getHeight(null); BufferedImage midimg = null; Graphics2D g2d = null; Image previmg = img; int prevw = img.getWidth(null); int prevh = img.getHeight(null); do { if (midw > targetw) { midw /= 2; if (midw < targetw) { midw = targetw; } } else { midw = targetw; } if (midh > targeth) { midh /= 2; if (midh < targeth) { midh = targeth; } } else { midh = targeth; } if (midimg == null) { midimg = new BufferedImage(midw, midh, BufferedImage.TYPE_INT_ARGB); g2d = midimg.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); } g2d.drawImage(previmg, 0, 0, midw, midh, 0, 0, prevw, prevh, null); prevw = midw; prevh = midh; previmg = midimg; } while (midw != targetw || midh != targeth); g2d.dispose(); if (m_width != midimg.getWidth() || m_height != midimg.getHeight()) { midimg = new BufferedImage(m_width, m_height, BufferedImage.TYPE_INT_ARGB); int x = (m_width > targetw) ? (m_width - targetw) / 2 : 0; int y = (m_height > targeth) ? (m_height - targeth) / 2 : 0; g2d = midimg.createGraphics(); g2d.drawImage(previmg, x, y, x + targetw, y + targeth, 0, 0, targetw, targeth, null); g2d.dispose(); previmg = midimg; } return previmg; }
From source file:org.openstreetmap.josm.gui.layer.geoimage.ThumbsLoader.java
private BufferedImage loadThumb(ImageEntry entry) { final String cacheIdent = entry.getFile().toString() + ':' + maxSize; if (!cacheOff && cache != null) { try {/* w ww. j ava2 s .c om*/ BufferedImageCacheEntry cacheEntry = cache.get(cacheIdent); if (cacheEntry != null && cacheEntry.getImage() != null) { Logging.debug(" from cache"); return cacheEntry.getImage(); } } catch (IOException e) { Logging.warn(e); } } Image img = Toolkit.getDefaultToolkit().createImage(entry.getFile().getPath()); tracker.addImage(img, 0); try { tracker.waitForID(0); } catch (InterruptedException e) { Logging.error(" InterruptedException while loading thumb"); Thread.currentThread().interrupt(); return null; } if (tracker.isErrorID(1) || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) { Logging.error(" Invalid image"); return null; } final int w = img.getWidth(null); final int h = img.getHeight(null); final int hh, ww; final Integer exifOrientation = entry.getExifOrientation(); if (exifOrientation != null && ExifReader.orientationSwitchesDimensions(exifOrientation)) { ww = h; hh = w; } else { ww = w; hh = h; } Rectangle targetSize = ImageDisplay.calculateDrawImageRectangle(new Rectangle(0, 0, ww, hh), new Rectangle(0, 0, maxSize, maxSize)); BufferedImage scaledBI = new BufferedImage(targetSize.width, targetSize.height, BufferedImage.TYPE_INT_RGB); Graphics2D g = scaledBI.createGraphics(); final AffineTransform scale = AffineTransform.getScaleInstance((double) targetSize.width / ww, (double) targetSize.height / hh); if (exifOrientation != null) { final AffineTransform restoreOrientation = ExifReader.getRestoreOrientationTransform(exifOrientation, w, h); scale.concatenate(restoreOrientation); } while (!g.drawImage(img, scale, null)) { try { Thread.sleep(10); } catch (InterruptedException e) { Logging.warn("InterruptedException while drawing thumb"); Thread.currentThread().interrupt(); } } g.dispose(); tracker.removeImage(img); if (scaledBI.getWidth() <= 0 || scaledBI.getHeight() <= 0) { Logging.error(" Invalid image"); return null; } if (!cacheOff && cache != null) { try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { ImageIO.write(scaledBI, "png", output); cache.put(cacheIdent, new BufferedImageCacheEntry(output.toByteArray())); } catch (IOException e) { Logging.warn("Failed to save geoimage thumb to cache"); Logging.warn(e); } } return scaledBI; }
From source file:edu.ku.brc.ui.ImageDisplay.java
/** * @param newImage/*from ww w . j av a 2 s.c om*/ */ public void setImage(final Image newImage) { if (newImage != null && newImage.getWidth(null) > 0 && newImage.getHeight(null) > 0) { image = newImage; setNoImage(false); status = kImageOK; } else { image = null; setNoImage(true); } notifyOnUIThread(true, true); repaint(); //invalidate(); //doLayout(); }
From source file:com.google.code.facebook.graph.sna.applet.FacebookGraphApplet.java
/** * create an instance of a simple graph with controls to * demo the zoom features.//from w w w.ja va2 s. c o m * */ @Override public void init() { super.init(); // create a simple graph for the demo fetchUserGraph(); final Collection<? extends Entity<FieldEnum, ConnectionEnum>> vertices = graph.getVertices(); // a Map for the labels Map<Entity<FieldEnum, ConnectionEnum>, String> map = new HashMap<Entity<FieldEnum, ConnectionEnum>, String>(); Iterator<? extends Entity<FieldEnum, ConnectionEnum>> iterator = vertices.iterator(); while (iterator.hasNext()) { Entity<FieldEnum, ConnectionEnum> entity = iterator.next(); map.put(entity, entity.getLabel()); } FRLayout<Entity<FieldEnum, ConnectionEnum>, EdgeAdapter<ConnectionEnum>> layout = new FRLayout<Entity<FieldEnum, ConnectionEnum>, EdgeAdapter<ConnectionEnum>>( (Graph<Entity<FieldEnum, ConnectionEnum>, EdgeAdapter<ConnectionEnum>>) graph); layout.setMaxIterations(100); vv = new VisualizationViewer<Entity<FieldEnum, ConnectionEnum>, EdgeAdapter<ConnectionEnum>>(layout, new Dimension(2000, 2000)); Transformer<Entity<FieldEnum, ConnectionEnum>, Paint> vpf = new PickableVertexPaintTransformer<Entity<FieldEnum, ConnectionEnum>>( vv.getPickedVertexState(), Color.white, Color.yellow); vv.getRenderContext().setVertexFillPaintTransformer(vpf); vv.getRenderContext().setEdgeDrawPaintTransformer( new PickableEdgePaintTransformer<EdgeAdapter<ConnectionEnum>>(vv.getPickedEdgeState(), Color.black, Color.cyan)); vv.setBackground(Color.white); // a Map for the Icons final Map<Entity<FieldEnum, ConnectionEnum>, Icon> iconMap = new HashMap<Entity<FieldEnum, ConnectionEnum>, Icon>(); new Thread(new Runnable() { public void run() { Iterator<? extends Entity<FieldEnum, ConnectionEnum>> iterator = vertices.iterator(); while (iterator.hasNext()) { try { Entity<FieldEnum, ConnectionEnum> entity = iterator.next(); // Icon icon = // new LayeredIcon(new ImageIcon("http://facebookgraph.appspot.com/proxy?url=" + entity.getPicture(PictureType.SQUARE), "Profile Picture").getImage()); // iconMap.put(entity, icon); Image image = getImageFromEntity(entity); if (image != null && image.getWidth(null) > 0 && image.getHeight(null) > 0) { Icon icon = new LayeredIcon(image); iconMap.put(entity, icon); if ((iconMap.size() % 5) == 0) { vv.repaint(); } } } catch (Exception ex) { ex.printStackTrace(); } } vv.repaint(); } }).start(); final Transformer<Entity<FieldEnum, ConnectionEnum>, String> vertexStringerImpl = new VertexStringerImpl<Entity<FieldEnum, ConnectionEnum>>( map); Transformer<EdgeAdapter<ConnectionEnum>, String> edgeStringerImpl = new Transformer<EdgeAdapter<ConnectionEnum>, String>() { public String transform(EdgeAdapter<ConnectionEnum> edge) { return edge.toString(); } }; vv.getRenderContext().setEdgeLabelTransformer(edgeStringerImpl); vv.getRenderContext().setVertexLabelTransformer(vertexStringerImpl); vv.getRenderContext().setVertexLabelRenderer(new DefaultVertexLabelRenderer(Color.cyan)); vv.getRenderContext().setEdgeLabelRenderer(new DefaultEdgeLabelRenderer(Color.cyan)); // features on and off. For a real application, use VertexIconAndShapeFunction instead. final VertexIconShapeTransformer<Entity<FieldEnum, ConnectionEnum>> vertexImageShapeFunction = new VertexIconShapeTransformer<Entity<FieldEnum, ConnectionEnum>>( new EllipseVertexShapeTransformer<Entity<FieldEnum, ConnectionEnum>>()); final DefaultVertexIconTransformer<Entity<FieldEnum, ConnectionEnum>> vertexIconFunction = new DefaultVertexIconTransformer<Entity<FieldEnum, ConnectionEnum>>(); vertexImageShapeFunction.setIconMap(iconMap); vertexIconFunction.setIconMap(iconMap); vv.getRenderContext().setVertexShapeTransformer(vertexImageShapeFunction); vv.getRenderContext().setVertexIconTransformer(vertexIconFunction); // Get the pickedState and add a listener that will decorate the // Vertex images with a checkmark icon when they are picked PickedState<Entity<FieldEnum, ConnectionEnum>> ps = vv.getPickedVertexState(); ps.addItemListener(new PickWithIconListener(vertexIconFunction)); // add a listener for ToolTips vv.setVertexToolTipTransformer(new Transformer<Entity<FieldEnum, ConnectionEnum>, String>() { @Override public String transform(Entity<FieldEnum, ConnectionEnum> entity) { return entity.getDescription(); } }); Container content = getContentPane(); final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv); content.add(panel); final DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse(); vv.setGraphMouse(graphMouse); final ScalingControl scaler = new CrossoverScalingControl(); JButton plus = new JButton("+"); plus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { scaler.scale(vv, 1.1f, vv.getCenter()); } }); JButton minus = new JButton("-"); minus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { scaler.scale(vv, 1 / 1.1f, vv.getCenter()); } }); JComboBox modeBox = graphMouse.getModeComboBox(); JPanel modePanel = new JPanel(); modePanel.setBorder(BorderFactory.createTitledBorder("Mouse Mode")); modePanel.add(modeBox); JPanel scaleGrid = new JPanel(new GridLayout(1, 0)); scaleGrid.setBorder(BorderFactory.createTitledBorder("Zoom")); JPanel controls = new JPanel(); scaleGrid.add(plus); scaleGrid.add(minus); controls.add(scaleGrid); controls.add(modePanel); content.add(controls, BorderLayout.SOUTH); this.viewSupport = new MagnifyImageLensSupport<Entity<FieldEnum, ConnectionEnum>, EdgeAdapter<ConnectionEnum>>( vv); // new ViewLensSupport<Number,Number>(vv, new HyperbolicShapeTransformer(vv, // vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW)), // new ModalLensGraphMouse()); this.modelSupport = new LayoutLensSupport<Entity<FieldEnum, ConnectionEnum>, EdgeAdapter<ConnectionEnum>>( vv); graphMouse.addItemListener(modelSupport.getGraphMouse().getModeListener()); graphMouse.addItemListener(viewSupport.getGraphMouse().getModeListener()); ButtonGroup radio = new ButtonGroup(); JRadioButton none = new JRadioButton("None"); none.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (viewSupport != null) { viewSupport.deactivate(); } if (modelSupport != null) { modelSupport.deactivate(); } } }); none.setSelected(true); JRadioButton hyperView = new JRadioButton("View"); hyperView.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { viewSupport.activate(e.getStateChange() == ItemEvent.SELECTED); } }); JRadioButton hyperModel = new JRadioButton("Layout"); hyperModel.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { modelSupport.activate(e.getStateChange() == ItemEvent.SELECTED); } }); radio.add(none); radio.add(hyperView); radio.add(hyperModel); JMenuBar menubar = new JMenuBar(); JMenu modeMenu = graphMouse.getModeMenu(); menubar.add(modeMenu); JPanel lensPanel = new JPanel(new GridLayout(2, 0)); lensPanel.setBorder(BorderFactory.createTitledBorder("Lens")); lensPanel.add(none); lensPanel.add(hyperView); lensPanel.add(hyperModel); controls.add(lensPanel); }
From source file:edu.ku.brc.ui.ImageDisplay.java
/** * @param imgIcon/*from w w w . j a v a2 s . c o m*/ * @param isEditMode * @param hasBorder */ public ImageDisplay(final Image imgIcon, boolean isEditMode, boolean hasBorder) { this(imgIcon.getWidth(null), imgIcon.getHeight(null), isEditMode, hasBorder); setImage(imgIcon); }
From source file:edu.stanford.epad.epadws.handlers.dicom.DSOUtil.java
private static BufferedImage imageToBufferedImage(Image image) { BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = bufferedImage.createGraphics(); g2.drawImage(image, 0, 0, null);//from ww w.j ava 2s . co m g2.dispose(); return bufferedImage; }
From source file:com.openbravo.pos.util.ThumbNailBuilder.java
public Image getThumbNailText(Image img, String text) { /*/*from w w w . j a v a 2s . c o m*/ * Create an image containing a thumbnail of the product image, * or default image. * * Then apply the text of the product name. Use text wrapping. * * If the product name is too big for the label, ensure that * the first part is displayed. */ img = getThumbNail(img); BufferedImage imgtext = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = imgtext.createGraphics(); // The text // <p style="width: 100px"> DOES NOT WORK PROPERLY. // use width= instead. String html = "<html><p style=\"text-align:center\" width=\"" + imgtext.getWidth() + "\">" + StringEscapeUtils.escapeHtml(text) + "</p>"; JLabel label = new JLabel(html); label.setOpaque(false); //label.setText("<html><center>Line1<br>Line2"); label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); label.setVerticalAlignment(javax.swing.SwingConstants.TOP); Dimension d = label.getPreferredSize(); label.setBounds(0, 0, imgtext.getWidth(), d.height); // The background Color c1 = new Color(0xff, 0xff, 0xff, 0x40); Color c2 = new Color(0xff, 0xff, 0xff, 0xd0); // Point2D center = new Point2D.Float(imgtext.getWidth() / 2, label.getHeight()); // float radius = imgtext.getWidth() / 3; // float[] dist = {0.1f, 1.0f}; // Color[] colors = {c2, c1}; // Paint gpaint = new RadialGradientPaint(center, radius, dist, colors); Paint gpaint = new GradientPaint(new Point(0, 0), c1, new Point(label.getWidth() / 2, 0), c2, true); g2d.drawImage(img, 0, 0, null); int ypos = imgtext.getHeight() - label.getHeight(); int ypos_min = -4; // todo: configurable if (ypos < ypos_min) ypos = ypos_min; // Clamp label g2d.translate(0, ypos); g2d.setPaint(gpaint); g2d.fillRect(0, 0, imgtext.getWidth(), label.getHeight()); label.paint(g2d); g2d.dispose(); return imgtext; }
From source file:com.actionbazaar.controller.SellController.java
/** * Saves the uploaded file into a folder for the user. * @param imageFile - image file to be saved * @return image id//from w ww .j a v a2s. c o m */ private String save(UploadedFile imageFile) { try { File saveFld = new File(imageFolder + File.separator + userDisplay.getUser().getUsername()); if (!saveFld.exists()) { if (!saveFld.mkdir()) { logger.log(Level.INFO, "Unable to create folder: {0}", saveFld.getAbsolutePath()); return null; } } File tmp = File.createTempFile("img", "img"); IOUtils.copy(imageFile.getInputstream(), new FileOutputStream(tmp)); File thumbnailImage = new File(saveFld + File.separator + UUID.randomUUID().toString() + ".png"); File fullResolution = new File(saveFld + File.separator + UUID.randomUUID().toString() + ".png"); // Create the thumbnail BufferedImage image = ImageIO.read(tmp); Image thumbnailIm = image.getScaledInstance(310, 210, Image.SCALE_SMOOTH); // Convert the thumbnail java.awt.Image into a rendered image which we can save BufferedImage thumbnailBi = new BufferedImage(thumbnailIm.getWidth(null), thumbnailIm.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics bg = thumbnailBi.getGraphics(); bg.drawImage(thumbnailIm, 0, 0, null); bg.dispose(); ImageIO.write(thumbnailBi, "png", thumbnailImage); // Write out the full resolution image as a thumbnail ImageIO.write(image, "png", fullResolution); if (!tmp.delete()) { logger.log(Level.INFO, "Unable to delete: {0}", tmp.getAbsolutePath()); } String imageId = UUID.randomUUID().toString(); imageBean.addImage(imageId, new ImageRecord(imageFile.getFileName(), fullResolution.getAbsolutePath(), thumbnailImage.getAbsolutePath(), userDisplay.getUser().getUsername())); return imageId; } catch (Throwable t) { logger.log(Level.SEVERE, "Unable to save the image.", t); return null; } }
From source file:com.greenline.guahao.biz.manager.image.codes.gif.GifEncoder.java
/** * Convenience constructor for class <CODE>GIFEncoder</CODE>. The argument * will be converted to an indexed color array. <B>This may take some * time.</B>/*from ww w . j a v a 2s. c o m*/ * * @param image The image to encode. The image <B>must</B> be completely * loaded. * @exception AWTException Will be thrown if the pixel grab fails. This can * happen if Java runs out of memory. It may also indicate * that the image contains more than 256 colors. */ public GifEncoder(Image image) throws AWTException { this.imageWidth = (short) image.getWidth(null); this.imageHeight = (short) image.getHeight(null); int values[] = new int[this.imageWidth * this.imageHeight]; PixelGrabber grabber = new PixelGrabber(image, 0, 0, this.imageWidth, this.imageHeight, values, 0, this.imageWidth); try { if (grabber.grabPixels() != true) { log.error("GifEncoder#GifEncoder Grabber returned false: " + grabber.status()); throw new AWTException("Grabber returned false: " + grabber.status()); } } // ends try catch (InterruptedException ie) { log.error("GifEncoder#GifEncoder " + ie.getMessage(), ie); } byte[][] r = new byte[this.imageWidth][this.imageHeight]; byte[][] g = new byte[this.imageWidth][this.imageHeight]; byte[][] b = new byte[this.imageWidth][this.imageHeight]; int index = 0; for (int y = 0; y < this.imageHeight; y++) { for (int x = 0; x < this.imageWidth; x++, index++) { r[x][y] = (byte) ((values[index] >> 16) & 0xFF); g[x][y] = (byte) ((values[index] >> 8) & 0xFF); b[x][y] = (byte) ((values[index]) & 0xFF); } // ends for } // ends for this.toIndexColor(r, g, b); }