Example usage for java.awt Image getWidth

List of usage examples for java.awt Image getWidth

Introduction

In this page you can find the example usage for java.awt Image getWidth.

Prototype

public abstract int getWidth(ImageObserver observer);

Source Link

Document

Determines the width of the image.

Usage

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  .  ja va  2s  .  com
            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:org.exist.xquery.modules.image.CropFunction.java

/**
 * evaluate the call to the xquery crop() function,
 * it is really the main entry point of this class
 * /*from w  w  w.  java  2  s.c  o m*/
 * @param args      arguments from the crop() function call
 * @param contextSequence   the Context Sequence to operate on (not used here internally!)
 * @return      A sequence representing the result of the crop() function call
 * 
 * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
 */
@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    //was an image and a mime-type speficifed
    if (args[0].isEmpty() || args[2].isEmpty()) {
        return Sequence.EMPTY_SEQUENCE;
    }

    //get the maximum dimensions to crop to
    int x1 = 0;
    int y1 = 0;
    int x2 = MAXHEIGHT;
    int y2 = MAXWIDTH;

    if (!args[1].isEmpty()) {
        x1 = ((IntegerValue) args[1].itemAt(0)).getInt();
        if (args[1].hasMany()) {
            y1 = ((IntegerValue) args[1].itemAt(1)).getInt();
            x2 = ((IntegerValue) args[1].itemAt(2)).getInt();
            y2 = ((IntegerValue) args[1].itemAt(3)).getInt();
        }
    }

    //get the mime-type
    String mimeType = args[2].itemAt(0).getStringValue();
    String formatName = mimeType.substring(mimeType.indexOf("/") + 1);

    //TODO currently ONLY tested for JPEG!!!
    Image image = null;
    BufferedImage bImage = null;
    try {
        //get the image data
        image = ImageIO.read(((BinaryValue) args[0].itemAt(0)).getInputStream());
        //         image = ImageModule.getImage((Base64BinaryValueType)args[0].itemAt(0));
        //               image = ImageIO.read(new ByteArrayInputStream(getImageData((Base64BinaryValueType)args[0].itemAt(0))));
        if (image == null) {
            logger.error("Unable to read image data!");
            return Sequence.EMPTY_SEQUENCE;
        }

        //crop the image
        Image cropImage = Toolkit.getDefaultToolkit()
                .createImage(new FilteredImageSource(image.getSource(), new CropImageFilter(x1, y1, x2, y2)));
        if (cropImage instanceof BufferedImage) {
            // just in case cropImage is allready an BufferedImage
            bImage = (BufferedImage) cropImage;
        } else {
            bImage = new BufferedImage(cropImage.getHeight(null), cropImage.getWidth(null),
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bImage.createGraphics(); // Paint the image onto the buffered image
            g.drawImage(cropImage, 0, 0, null);
            g.dispose();
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bImage, formatName, os);

        //return the new croped image data
        return BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(),
                new ByteArrayInputStream(os.toByteArray()));

    } catch (Exception e) {
        throw new XPathException(this, e.getMessage());
    }
}

From source file:edu.ku.brc.ui.ImageDisplay.java

/**
 * @param newImage//from  w  w  w  .  j a va2 s .co  m
 */
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 .j a va 2s .  c  om
 * 
 */
@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: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  w ww.j  a  v  a 2  s  . 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);
}

From source file:edu.ku.brc.ui.ImageDisplay.java

/**
 * @param imgIcon/*from   w  w  w  . j  a  v  a2s.co  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 w  w  w  .  j  a  v  a 2 s. co m
    g2.dispose();
    return bufferedImage;
}

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  a  2s  . co  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.openbravo.pos.util.ThumbNailBuilder.java

public Image getThumbNailText(Image img, String text) {
    /*//  www.j av  a  2  s.  c om
     * 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:ImageBouncer.java

public ImageBouncer(Image image) {
    previousTimes = new long[128];
    previousTimes[0] = System.currentTimeMillis();
    previousIndex = 1;/*from  www.j  a v a2  s.  c om*/
    previousFilled = false;

    mOriginalImage = image;
    setImageType("TYPE_INT_RGB");

    Random random = new Random();
    mX = random.nextFloat() * 500;
    mY = random.nextFloat() * 500;
    mWidth = image.getWidth(this);
    mHeight = image.getHeight(this);
    mDeltaX = random.nextFloat() * 3;
    mDeltaY = random.nextFloat() * 3;
    // Make sure points are within range.
    addComponentListener(new ComponentAdapter() {
        public void componentResized(ComponentEvent ce) {
            Dimension d = getSize();
            if (mX < 0)
                mX = 0;
            else if (mX + mWidth >= d.width)
                mX = d.width - mWidth - 1;
            if (mY < 0)
                mY = 0;
            else if (mY + mHeight >= d.height)
                mY = d.height - mHeight - 1;
        }
    });
}