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:com.cubusmail.server.services.RetrieveImageServlet.java

/**
 * @param bufInputStream//from w  w w. j  av  a 2 s  . c o  m
 * @param outputStream
 */
private void writeScaledImage(BufferedInputStream bufInputStream, OutputStream outputStream) {

    long millis = System.currentTimeMillis();
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = bufInputStream.read(buffer, 0, 8192)) != -1) {
            bos.write(buffer, 0, bytesRead);
        }
        bos.close();

        byte[] imageBytes = bos.toByteArray();

        Image image = Toolkit.getDefaultToolkit().createImage(imageBytes);
        MediaTracker mediaTracker = new MediaTracker(new Container());
        mediaTracker.addImage(image, 0);
        mediaTracker.waitForID(0);
        // determine thumbnail size from WIDTH and HEIGHT
        int thumbWidth = 300;
        int thumbHeight = 200;
        double thumbRatio = (double) thumbWidth / (double) thumbHeight;
        int imageWidth = image.getWidth(null);
        int imageHeight = image.getHeight(null);
        double imageRatio = (double) imageWidth / (double) imageHeight;
        if (thumbRatio < imageRatio) {
            thumbHeight = (int) (thumbWidth / imageRatio);
        } else {
            thumbWidth = (int) (thumbHeight * imageRatio);
        }
        // draw original image to thumbnail image object and
        // scale it to the new size on-the-fly
        BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = thumbImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);

        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
        int quality = 70;
        quality = Math.max(0, Math.min(quality, 100));
        param.setQuality((float) quality / 100.0f, false);
        encoder.setJPEGEncodeParam(param);
        encoder.encode(thumbImage);
    } catch (IOException ex) {
        log.error(ex.getMessage(), ex);
    } catch (InterruptedException ex) {
        log.error(ex.getMessage(), ex);
    } finally {
        log.debug("Time for thumbnail: " + (System.currentTimeMillis() - millis) + "ms");
    }
}

From source file:org.apache.fop.afp.AFPGraphics2D.java

/** {@inheritDoc} */
@Override// ww  w .  jav a 2  s. c  om
public boolean drawImage(Image img, int x, int y, ImageObserver observer) {
    return drawImage(img, x, y, img.getWidth(observer), img.getHeight(observer), observer);
}

From source file:org.bigbluebuttonproject.fileupload.document.impl.FileSystemSlideManager.java

/**
 * This method create thumbImage of the image file given and save it in outFile.
 * Compression quality is also given. thumbBounds is used for calculating the size of the thumb.
 * /* w  w w .  j a v  a 2s  . co m*/
 * @param infile slide image to create thumb
 * @param outfile output thumb file
 * @param compressionQuality the compression quality
 * @param thumbBounds the thumb bounds
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void resizeImage(File infile, File outfile, float compressionQuality, int thumbBounds)
        throws IOException {
    // Retrieve jpg image to be resized
    Image image = ImageIO.read(infile);

    // get original image size for thumb size calculation
    int imageWidth = image.getWidth(null);
    int imageHeight = image.getHeight(null);

    float thumbRatio = (float) thumbBounds / Math.max(imageWidth, imageHeight);

    int thumbWidth = (int) (imageWidth * thumbRatio);
    int thumbHeight = (int) (imageHeight * thumbRatio);

    // draw original image to thumbnail image object and
    // scale it to the new size on-the-fly
    BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics2D = thumbImage.createGraphics();
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);

    // Find a jpeg writer
    ImageWriter writer = null;
    Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg");
    if (iter.hasNext()) {
        writer = (ImageWriter) iter.next();
    }

    ImageWriteParam iwp = writer.getDefaultWriteParam();
    iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwp.setCompressionQuality(compressionQuality);

    // Prepare output file
    ImageOutputStream ios = ImageIO.createImageOutputStream(outfile);
    writer.setOutput(ios);
    // write to the thumb image 
    writer.write(thumbImage);

    // Cleanup
    ios.flush();
    writer.dispose();
    ios.close();
}

From source file:org.apache.fop.render.pdf.pdfbox.PSPDFGraphics2D.java

@Override
public boolean drawImage(Image img, int x1, int y1, ImageObserver observer) {
    PSGenerator tmp = gen;//from   ww w .  ja v  a 2s .  co m
    if (gen instanceof PSDocumentHandler.FOPPSGenerator) {
        PSDocumentHandler.FOPPSGenerator fopGen = (PSDocumentHandler.FOPPSGenerator) tmp;
        PSDocumentHandler handler = fopGen.getHandler();
        if (handler.getPSUtil().isOptimizeResources()) {
            try {
                final int width = img.getWidth(observer);
                final int height = img.getHeight(observer);
                if (width == -1 || height == -1) {
                    return false;
                }
                BufferedImage buf = getImage(width, height, img, observer);
                if (buf == null) {
                    return false;
                }
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                DataBufferInt db = (DataBufferInt) buf.getRaster().getDataBuffer();
                DataOutputStream dos = new DataOutputStream(bos);
                dos.writeInt(width);
                dos.writeInt(height);
                for (int i : db.getData()) {
                    dos.writeInt(i);
                }
                String format = DataBufferInt.class.getName();
                int hash = Arrays.hashCode(bos.toByteArray());
                URI uri = fopGen.getImages().get(hash);
                if (uri == null) {
                    uri = new TempResourceURIGenerator("img" + hash + "." + format).generate();
                    fopGen.getImages().put(hash, uri);
                    BufferedOutputStream outputStream = fopGen.getTempStream(uri);
                    outputStream.write(bos.toByteArray());
                    outputStream.close();
                }
                PSResource form = handler.getFormForImage(uri.toASCIIString());
                ImageInfo info = new ImageInfo(uri.toASCIIString(), "image/" + format);
                ImageSize size = new ImageSize(width, height, handler.getUserAgent().getTargetResolution());
                size.calcSizeFromPixels();
                info.setSize(size);
                float res = handler.getUserAgent().getSourceResolution() / 72;
                Rectangle rect = new Rectangle(0, 0, (int) (size.getWidthMpt() * res),
                        (int) (size.getHeightMpt() * res));
                gen.saveGraphicsState();
                gen.concatMatrix(getTransform());
                writeClip(getClip());
                PSImageUtils.drawForm(form, info, rect, gen);
                gen.restoreGraphicsState();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return true;
        }
    }
    return super.drawImage(img, x1, y1, observer);
}

From source file:org.apache.tika.parser.ocr.TesseractOCRParser.java

public void parse(Image image, ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {

    TemporaryResources tmp = new TemporaryResources();
    FileOutputStream fos = null;//from  w  w w . j  a  v a 2 s .co  m
    TikaInputStream tis = null;
    try {
        int w = image.getWidth(null);
        int h = image.getHeight(null);
        BufferedImage bImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        File file = tmp.createTemporaryFile();
        fos = new FileOutputStream(file);
        ImageIO.write(bImage, "png", fos);
        tis = TikaInputStream.get(file);
        parse(tis, handler, metadata, context);

    } finally {
        tmp.dispose();
        if (tis != null)
            tis.close();
        if (fos != null)
            fos.close();
    }

}

From source file:gda.plots.SimpleXYItemRenderer.java

/**
 * Draws the visual representation of a single data item. This mostly reproduces the code of StandardXYItemRenderer
 * but using the line by line information stored in the SimpleXYSeries instead of the series indexed information
 * stored in the Renderer itself./*from  www. jav  a  2s. co  m*/
 * 
 * @param g2
 *            the graphics device.
 * @param state
 *            the renderer state.
 * @param dataArea
 *            the area within which the data is being drawn.
 * @param info
 *            collects information about the drawing.
 * @param plot
 *            the plot (can be used to obtain standard color information etc).
 * @param domainAxis
 *            the domain axis.
 * @param rangeAxis
 *            the range axis.
 * @param dataset
 *            the dataset.
 * @param series
 *            the series index (zero-based).
 * @param item
 *            the item index (zero-based).
 * @param crosshairState
 *            crosshair information for the plot ( <code>null</code> permitted).
 * @param pass
 *            the pass index.
 */
@Override
public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info,
        XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item,
        CrosshairState crosshairState, int pass) {
    SimpleXYSeries sxys = (SimpleXYSeries) ((SimpleXYSeriesCollection) dataset).getSeries(series);

    if (!sxys.isVisible()) {
        return;
    }
    // setup for collecting optional entity info...
    Shape entityArea = null;
    EntityCollection entities = null;
    if (info != null) {
        entities = info.getOwner().getEntityCollection();
    }

    PlotOrientation orientation = plot.getOrientation();
    g2.setPaint(sxys.getPaint());
    g2.setStroke(sxys.getStroke());

    // get the data point
    double x1 = dataset.getXValue(series, item);
    double y1 = dataset.getYValue(series, item);

    // Test
    x1 = xValueTransformer.transformValue(x1);

    if (Double.isNaN(x1) || Double.isNaN(y1)) {
        return;
    }

    RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
    RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
    double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
    double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation);

    if (sxys.isDrawLines()) {
        if (item > 0) {
            // get the previous data point...
            double x0 = dataset.getXValue(series, item - 1);
            double y0 = dataset.getYValue(series, item - 1);

            // Test
            // System.out.print("tranformed " + x0);
            x0 = xValueTransformer.transformValue(x0);
            // Message.debug(" to " + x0);
            if (!Double.isNaN(x0) && !Double.isNaN(y0)) {
                boolean drawLine = true;
                if (getPlotDiscontinuous()) {
                    // only draw a line if the gap between the current and
                    // previous data
                    // point is within the threshold
                    int numX = dataset.getItemCount(series);
                    double minX = dataset.getXValue(series, 0);
                    double maxX = dataset.getXValue(series, numX - 1);
                    drawLine = (x1 - x0) <= ((maxX - minX) / numX * getGapThreshold());
                }
                if (drawLine) {
                    double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation);
                    double transY0 = rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation);

                    // only draw if we have good values
                    if (Double.isNaN(transX0) || Double.isNaN(transY0) || Double.isNaN(transX1)
                            || Double.isNaN(transY1)) {
                        return;
                    }

                    if (orientation == PlotOrientation.HORIZONTAL) {
                        state.workingLine.setLine(transY0, transX0, transY1, transX1);
                    } else if (orientation == PlotOrientation.VERTICAL) {
                        state.workingLine.setLine(transX0, transY0, transX1, transY1);
                    }

                    if (state.workingLine.intersects(dataArea)) {
                        g2.draw(state.workingLine);
                    }
                }
            }
        }
    }

    if (sxys.isDrawMarkers()) {

        Shape shape = sxys.getSymbol();
        if (orientation == PlotOrientation.HORIZONTAL) {
            shape = ShapeUtilities.createTranslatedShape(shape, transY1, transX1);
        } else if (orientation == PlotOrientation.VERTICAL) {
            shape = ShapeUtilities.createTranslatedShape(shape, transX1, transY1);
        }
        if (shape.intersects(dataArea)) {
            g2.setPaint(sxys.getSymbolPaint());
            // Always use full stroke for drawing marker
            g2.setStroke(new BasicStroke());
            if (sxys.getFilled()) {
                g2.fill(shape);
            } else {
                g2.draw(shape);
            }
            g2.setPaint(sxys.getPaint());
            g2.setStroke(sxys.getStroke());
        }
        entityArea = shape;

    }

    if (getPlotImages()) {
        // use shape scale with transform??
        // double scale = getShapeScale(plot, series, item, transX1,
        // transY1);
        Image image = getImage(plot, series, item, transX1, transY1);
        if (image != null) {
            Point hotspot = getImageHotspot(plot, series, item, transX1, transY1, image);
            g2.drawImage(image, (int) (transX1 - hotspot.getX()), (int) (transY1 - hotspot.getY()), null);
            entityArea = new Rectangle2D.Double(transX1 - hotspot.getX(), transY1 - hotspot.getY(),
                    image.getWidth(null), image.getHeight(null));
        }

    }

    // draw the item label if there is one...
    if (isItemLabelVisible(series, item)) {
        drawItemLabel(g2, orientation, dataset, series, item, transX1, transY1, (y1 < 0.0));
    }

    updateCrosshairValues(crosshairState, x1, y1, transX1, transY1, orientation);

    // add an entity for the item...
    if (entities != null) {
        addEntity(entities, entityArea, dataset, series, item, transX1, transY1);
    }

}

From source file:msi.gama.outputs.layers.charts.FastXYItemRenderer.java

/** {@inheritDoc} */
@Override//from w w w  .j  a va 2s . c  om
public void drawItem(final Graphics2D g2, final XYItemRendererState state, final Rectangle2D dataArea,
        final PlotRenderingInfo info, final XYPlot plot, final ValueAxis domainAxis, final ValueAxis rangeAxis,
        final XYDataset dataset, final int series, final int item, final CrosshairState crosshairState,
        final int pass) {

    if (!getItemVisible(series, item)) {
        return;
    }
    // setup for collecting optional entity info...
    boolean bAddEntity = false;
    Shape entityArea = null;
    EntityCollection entities = null;
    if (info != null) {
        entities = info.getOwner().getEntityCollection();
    }

    final PlotOrientation orientation = plot.getOrientation();
    final Paint paint = getItemPaint(series, item);
    final Stroke seriesStroke = getItemStroke(series, item);
    g2.setPaint(paint);
    g2.setStroke(seriesStroke);

    // get the data point...
    final double x1 = dataset.getXValue(series, item);
    final double y1 = dataset.getYValue(series, item);
    if (Double.isNaN(x1) || Double.isNaN(y1)) {
        return;
    }

    final RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
    final RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
    final double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
    final double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation);

    if (getPlotLines()) {
        if (item == 0) {
            if (this.drawSeriesLineAsPath) {
                final State s = (State) state;
                s.seriesPath.reset();
                s.lastPointGood = false;
            }
            previousDrawnItem = 0;
        }

        if (this.drawSeriesLineAsPath) {
            final State s = (State) state;
            // update path to reflect latest point
            if (!Double.isNaN(transX1) && !Double.isNaN(transY1)) {
                float x = (float) transX1;
                float y = (float) transY1;
                if (orientation == PlotOrientation.HORIZONTAL) {
                    x = (float) transY1;
                    y = (float) transX1;
                }
                if (s.isLastPointGood()) {
                    // TODO: check threshold
                    s.seriesPath.lineTo(x, y);
                } else {
                    s.seriesPath.moveTo(x, y);
                }
                s.setLastPointGood(true);
            } else {
                s.setLastPointGood(false);
            }
            if (item == dataset.getItemCount(series) - 1) {
                // draw path
                g2.setStroke(getSeriesStroke(series));
                g2.setPaint(getSeriesPaint(series));
                g2.draw(s.seriesPath);
            }
        }

        else if (item != 0) {
            // get the previous data point...
            final double x0 = dataset.getXValue(series, item - previousDrawnItem);
            final double y0 = dataset.getYValue(series, item - previousDrawnItem);
            if (!Double.isNaN(x0) && !Double.isNaN(y0)) {
                boolean drawLine = true;
                if (getPlotDiscontinuous()) {
                    // only draw a line if the gap between the current and
                    // previous data point is within the threshold
                    final int numX = dataset.getItemCount(series);
                    final double minX = dataset.getXValue(series, 0);
                    final double maxX = dataset.getXValue(series, numX - 1);
                    if (this.gapThresholdType == UnitType.ABSOLUTE) {
                        drawLine = Math.abs(x1 - x0) <= this.gapThreshold;
                    } else {
                        drawLine = Math.abs(x1 - x0) <= (maxX - minX) / numX * getGapThreshold();
                    }
                }
                if (drawLine) {
                    final double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation);
                    final double transY0 = rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation);

                    // only draw if we have good values
                    if (Double.isNaN(transX0) || Double.isNaN(transY0) || Double.isNaN(transX1)
                            || Double.isNaN(transY1)) {
                        return;
                    }

                    // Only draw line if it is more than a pixel away from the previous one
                    if (transX1 - transX0 > 2 || transX1 - transX0 < -2 || transY1 - transY0 > 2
                            || transY1 - transY0 < -2 || 0 == previousDrawnItem) {
                        previousDrawnItem = 1;

                        if (orientation == PlotOrientation.HORIZONTAL) {
                            state.workingLine.setLine(transY0, transX0, transY1, transX1);
                        } else if (orientation == PlotOrientation.VERTICAL) {
                            state.workingLine.setLine(transX0, transY0, transX1, transY1);
                        }

                        if (state.workingLine.intersects(dataArea)) {
                            g2.draw(state.workingLine);
                        }
                    } else {
                        // Increase counter for the previous drawn item.
                        previousDrawnItem++;
                        bAddEntity = false;
                    }
                }
            }
        }
    }

    if (getBaseShapesVisible()) {

        Shape shape = getItemShape(series, item);
        if (orientation == PlotOrientation.HORIZONTAL) {
            shape = ShapeUtilities.createTranslatedShape(shape, transY1, transX1);
        } else if (orientation == PlotOrientation.VERTICAL) {
            shape = ShapeUtilities.createTranslatedShape(shape, transX1, transY1);
        }
        if (shape.intersects(dataArea)) {
            bAddEntity = true;
            if (getItemShapeFilled(series, item)) {
                g2.fill(shape);
            } else {
                g2.draw(shape);
            }
        }
        entityArea = shape;

    }

    if (getPlotImages()) {
        final Image image = getImage(plot, series, item, transX1, transY1);
        if (image != null) {
            final Point hotspot = getImageHotspot(plot, series, item, transX1, transY1, image);
            g2.drawImage(image, (int) (transX1 - hotspot.getX()), (int) (transY1 - hotspot.getY()), null);
            entityArea = new Rectangle2D.Double(transX1 - hotspot.getX(), transY1 - hotspot.getY(),
                    image.getWidth(null), image.getHeight(null));
        }

    }

    // draw the item label if there is one...
    if (isItemLabelVisible(series, item)) {
        double xx = transX1;
        double yy = transY1;
        if (orientation == PlotOrientation.HORIZONTAL) {
            xx = transY1;
            yy = transX1;
        }
        drawItemLabel(g2, orientation, dataset, series, item, xx, yy, y1 < 0.0);
    }

    updateCrosshairValues(crosshairState, x1, y1, transX1, transY1, orientation);

    // add an entity for the item...
    if (entities != null && bAddEntity) {
        addEntity(entities, entityArea, dataset, series, item, transX1, transY1);
    }
}

From source file:com.wet.wired.jsr.player.JPlayer.java

public void showNewImage(final Image image) {
    if (icon == null) {
        icon = new ImageIcon(image);
        JLabel label = new JLabel(icon);

        scrollPane = new JScrollPane(label);
        scrollPane.setSize(image.getWidth(this), image.getHeight(this));

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                getContentPane().add(scrollPane, BorderLayout.CENTER);
                pack();/* w  w w . j  a  v a2s .c om*/
                setSize(getWidth() - 100, 400);
                setVisible(true);
                repaint(0);
            }
        });
    } else {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                icon.setImage(image);
                repaint(0);
            }
        });
    }

}

From source file:org.squale.squaleweb.applicationlayer.action.export.ppt.PPTData.java

private BufferedImage convertImgToBufferedImg(Image limage, String l) {
    if (limage instanceof BufferedImage) {
        return ((BufferedImage) limage);
    } else {/*from w w  w . j a v a2  s. c om*/
        Image lImage = new ImageIcon(limage).getImage();
        BufferedImage bufferedimage = new BufferedImage(lImage.getWidth(null), lImage.getHeight(null),
                BufferedImage.TYPE_INT_RGB);
        Graphics gr = bufferedimage.createGraphics();
        gr.drawImage(lImage, 0, 0, null);
        gr.dispose();
        return (bufferedimage);
    }
}

From source file:org.apache.tika.parser.ocr.TesseractOCRParser.java

public void parse(Image image, ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {
    TemporaryResources tmp = new TemporaryResources();
    FileOutputStream fos = null;/*  w  w  w. ja  va2 s .  c  om*/
    TikaInputStream tis = null;
    try {
        int w = image.getWidth(null);
        int h = image.getHeight(null);
        BufferedImage bImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        File file = tmp.createTemporaryFile();
        fos = new FileOutputStream(file);
        ImageIO.write(bImage, "png", fos);
        tis = TikaInputStream.get(file);
        parse(tis, handler, metadata, context);
    } finally {
        tmp.dispose();
        if (tis != null)
            tis.close();
        if (fos != null)
            fos.close();
    }
}