Example usage for java.awt.image BufferedImage BufferedImage

List of usage examples for java.awt.image BufferedImage BufferedImage

Introduction

In this page you can find the example usage for java.awt.image BufferedImage BufferedImage.

Prototype

public BufferedImage(int width, int height, int imageType) 

Source Link

Document

Constructs a BufferedImage of one of the predefined image types.

Usage

From source file:com.eryansky.common.web.servlet.ValidateCodeServlet.java

private void createImage(HttpServletRequest request, HttpServletResponse response) throws IOException {

    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");

    /*//  w  w  w.  j av a 2 s . c om
     * ??
     */
    String width = request.getParameter("width");
    String height = request.getParameter("height");
    if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) {
        w = NumberUtils.toInt(width);
        h = NumberUtils.toInt(height);
    }

    BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();

    /*
     * ?
     */
    createBackground(g);

    /*
     * ?
     */
    String s = createCharacter(g);
    request.getSession().setAttribute(SysConstants.SESSION_VALIDATE_CODE, s);

    g.dispose();
    OutputStream out = response.getOutputStream();
    ImageIO.write(image, "JPEG", out);
    out.close();

}

From source file:de.laures.cewolf.util.ImageHelper.java

public static BufferedImage createImage(int width, int height) {
    // return GRAPHICS_CONV.createCompatibleImage(width, height);
    return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
}

From source file:jmbench.plots.UtilPlotPdf.java

protected static BufferedImage draw(JFreeChart chart, int width, int height) {
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = img.createGraphics();

    chart.draw(g2, new Rectangle2D.Double(0, 0, width, height));

    g2.dispose();//  w w w .ja va  2s. co  m
    return img;
}

From source file:ConvertUtil.java

/**
 * Converts the source image to 8-bit colour using the default 256-colour
 * palette. No transparency./*from w ww  .j a v  a  2  s . c om*/
 * 
 * @param src
 *            the source image to convert
 * @return a copy of the source image with an 8-bit colour depth
 */
public static BufferedImage convert8(BufferedImage src) {
    BufferedImage dest = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
    ColorConvertOp cco = new ColorConvertOp(src.getColorModel().getColorSpace(),
            dest.getColorModel().getColorSpace(), null);
    cco.filter(src, dest);
    return dest;
}

From source file:org.jrecruiter.service.impl.DataServiceImpl.java

/** {@inheritDoc} */
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public Image getGoogleMapImage(final BigDecimal latitude, final BigDecimal longitude, final Integer zoomLevel) {

    if (longitude == null) {
        throw new IllegalArgumentException("Longitude cannot be null.");
    }/*from w w w  . j  a v  a 2s .co m*/

    if (latitude == null) {
        throw new IllegalArgumentException("Latitude cannot be null.");
    }

    if (zoomLevel == null) {
        throw new IllegalArgumentException("ZoomLevel cannot be null.");
    }

    final URI url = GoogleMapsUtils.buildGoogleMapsStaticUrl(latitude, longitude, zoomLevel);

    BufferedImage img;
    try {
        URLConnection conn = url.toURL().openConnection();
        img = ImageIO.read(conn.getInputStream());
    } catch (UnknownHostException e) {
        LOGGER.error("Google static MAPS web service is not reachable (UnknownHostException).", e);
        img = new BufferedImage(GoogleMapsUtils.defaultWidth, 100, BufferedImage.TYPE_INT_RGB);

        final Graphics2D graphics = img.createGraphics();

        final Map<Object, Object> renderingHints = CollectionUtils.getHashMap();
        renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        graphics.addRenderingHints(renderingHints);
        graphics.setBackground(Color.WHITE);
        graphics.setColor(Color.GRAY);
        graphics.clearRect(0, 0, GoogleMapsUtils.defaultWidth, 100);

        graphics.drawString("Not Available", 30, 30);

    } catch (IOException e) {
        throw new IllegalStateException(e);
    }

    return img;
}

From source file:com.igormaznitsa.mindmap.swing.panel.utils.ScalableIcon.java

public synchronized Image getImage(final double scale) {
    if (Double.compare(this.currentScaleFactor, scale) != 0) {
        this.scaledCachedImage = null;
    }//w ww.  j  a v  a2s.  c om

    if (this.scaledCachedImage == null) {
        this.currentScaleFactor = scale;

        final int imgw = this.baseImage.getWidth(null);
        final int imgh = this.baseImage.getHeight(null);
        final int scaledW = (int) Math.round(imgw * this.baseScaleX * scale);
        final int scaledH = (int) Math.round(imgh * this.baseScaleY * scale);

        final BufferedImage img = new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_INT_ARGB);
        final Graphics2D g = (Graphics2D) img.getGraphics();

        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);

        g.drawImage(this.baseImage, 0, 0, scaledW, scaledH, null);
        g.dispose();

        this.scaledCachedImage = img;
    }
    return this.scaledCachedImage;
}

From source file:org.n52.oxf.render.sos.TimeSeriesChartRenderer.java

/**
 * The resulting IVisualization shows a chart which consists a TimeSeries for each FeatureOfInterest
 * contained in the observationCollection.
 *///from w  ww .ja  v a 2 s .c  om
public IVisualization renderChart(OXFFeatureCollection observationCollection, ParameterContainer paramCon,
        int width, int height) {
    JFreeChart chart = renderChart(observationCollection, paramCon);

    Plot plot = chart.getPlot();

    // draw plot into image:

    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    Graphics2D g = image.createGraphics();

    g.setColor(Color.white);
    g.fillRect(0, 0, width, height);

    plot.draw(g, new Rectangle2D.Float(0, 0, width, height), null, null, null);

    return new StaticVisualization(image);
}

From source file:edu.cudenver.bios.chartsvc.representation.LegendImageRepresentation.java

/**
 * Called internally by Restlet library to write the image as the HTTP
 * response.//  ww w.  ja v a2  s .  c  om
 * @param out output stream
 */
@Override
public void write(OutputStream out) throws IOException {
    // build the legend from the plot, and write it to a jpeg image
    if (plot != null) {
        LegendTitle legend = new LegendTitle(plot, new ColumnArrangement(), new ColumnArrangement());
        legend.setFrame(BlockBorder.NONE);
        //legend.setMargin(new RectangleInsets(2.0, 2.0, 2.0, 2.0));
        legend.setBackgroundPaint(Color.white);
        legend.setPosition(RectangleEdge.BOTTOM);
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        Rectangle2D.Double legendArea = new Rectangle2D.Double(0, 0, width, height);
        g.clip(legendArea);
        legend.arrange(g, new RectangleConstraint(width, height));
        legend.draw(g, legendArea);
        g.dispose();
        EncoderUtil.writeBufferedImage(image, ImageFormat.JPEG, out);
    }
}

From source file:org.n52.oxf.render.sos.TimeSeriesChartRenderer4xPhenomenons.java

/**
 * The resulting IVisualization shows a chart which consists a TimeSeries for each FeatureOfInterest
 * contained in the observationCollection.
 *//* w  w  w  . j ava 2s .c  o m*/
public IVisualization renderChart(OXFFeatureCollection observationCollection, ParameterContainer paramCon,
        int width, int height) {
    JFreeChart chart = renderChart(observationCollection, paramCon);

    // draw plot into image:
    Plot plot = chart.getPlot();
    BufferedImage chartImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D chartGraphics = chartImage.createGraphics();
    chartGraphics.setColor(Color.white);
    chartGraphics.fillRect(0, 0, width, height);
    plot.draw(chartGraphics, new Rectangle2D.Float(0, 0, width, height), null, null, null);

    // draw legend into image:
    LegendTitle legend = chart.getLegend();
    BufferedImage legendImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D legendGraphics = legendImage.createGraphics();
    legendGraphics.setColor(Color.white);
    legendGraphics.fillRect(0, 0, (int) legend.getWidth(), (int) legend.getHeight());
    legend.draw(legendGraphics, new Rectangle2D.Float(0, 0, width, height));

    return new StaticVisualization(chartImage, legendImage);
}

From source file:com.igormaznitsa.jhexed.swing.editor.ui.exporters.PNGImageExporter.java

public BufferedImage generateImage() throws IOException {
    final int DEFAULT_CELL_WIDTH = 48;
    final int DEFAULT_CELL_HEIGHT = 48;

    final int imgWidth = this.docOptions.getImage() == null ? DEFAULT_CELL_WIDTH * this.docOptions.getColumns()
            : Math.round(this.docOptions.getImage().getSVGWidth());
    final int imgHeight = this.docOptions.getImage() == null ? DEFAULT_CELL_HEIGHT * this.docOptions.getRows()
            : Math.round(this.docOptions.getImage().getSVGHeight());

    final BufferedImage result;
    if (exportData.isBackgroundImageExport() && this.docOptions.getImage() != null) {
        result = this.docOptions.getImage().rasterize(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
    } else {//w  ww .j  a  va  2  s .c om
        result = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
    }

    final Graphics2D gfx = result.createGraphics();
    gfx.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    gfx.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    final HexEngine<Graphics2D> engine = new HexEngine<Graphics2D>(DEFAULT_CELL_WIDTH, DEFAULT_CELL_HEIGHT,
            this.docOptions.getHexOrientation());

    final List<HexFieldLayer> reversedNormalizedStack = new ArrayList<HexFieldLayer>();
    for (int i = this.exportData.getLayers().size() - 1; i >= 0; i--) {
        final LayerExportRecord rec = this.exportData.getLayers().get(i);
        if (rec.isAllowed()) {
            reversedNormalizedStack.add(rec.getLayer());
        }
    }

    if (Thread.currentThread().isInterrupted())
        return null;

    final HexFieldValue[] stackOfValues = new HexFieldValue[reversedNormalizedStack.size()];

    engine.setModel(new HexEngineModel<HexFieldValue[]>() {

        @Override
        public int getColumnNumber() {
            return docOptions.getColumns();
        }

        @Override
        public int getRowNumber() {
            return docOptions.getRows();
        }

        @Override
        public HexFieldValue[] getValueAt(final int col, final int row) {
            Arrays.fill(stackOfValues, null);

            for (int index = 0; index < reversedNormalizedStack.size(); index++) {
                stackOfValues[index] = reversedNormalizedStack.get(index).getHexValueAtPos(col, row);
            }
            return stackOfValues;
        }

        @Override
        public HexFieldValue[] getValueAt(final HexPosition pos) {
            return this.getValueAt(pos.getColumn(), pos.getRow());
        }

        @Override
        public void setValueAt(int col, int row, HexFieldValue[] value) {
        }

        @Override
        public void setValueAt(HexPosition pos, HexFieldValue[] value) {
        }

        @Override
        public boolean isPositionValid(final int col, final int row) {
            return col >= 0 && col < docOptions.getColumns() && row >= 0 && row < docOptions.getRows();
        }

        @Override
        public boolean isPositionValid(final HexPosition pos) {
            return this.isPositionValid(pos.getColumn(), pos.getRow());
        }

        @Override
        public void attachedToEngine(final HexEngine<?> engine) {
        }

        @Override
        public void detachedFromEngine(final HexEngine<?> engine) {
        }
    });

    final HexRect2D visibleSize = engine.getVisibleSize();
    final float xcoeff = (float) result.getWidth() / visibleSize.getWidth();
    final float ycoeff = (float) result.getHeight() / visibleSize.getHeight();
    engine.setScale(xcoeff, ycoeff);

    final Image[][] cachedIcons = new Image[this.exportData.getLayers().size()][];
    engine.setRenderer(new ColorHexRender() {

        private final Stroke stroke = new BasicStroke(docOptions.getLineWidth());

        @Override
        public Stroke getStroke() {
            return this.stroke;
        }

        @Override
        public Color getFillColor(HexEngineModel<?> model, int col, int row) {
            return null;
        }

        @Override
        public Color getBorderColor(HexEngineModel<?> model, int col, int row) {
            return exportData.isExportHexBorders() ? docOptions.getColor() : null;
        }

        @Override
        public void drawExtra(HexEngine<Graphics2D> engine, Graphics2D g, int col, int row, Color borderColor,
                Color fillColor) {
        }

        @Override
        public void drawUnderBorder(final HexEngine<Graphics2D> engine, final Graphics2D g, final int col,
                final int row, final Color borderColor, final Color fillColor) {
            final HexFieldValue[] stackValues = (HexFieldValue[]) engine.getModel().getValueAt(col, row);
            for (int i = 0; i < stackValues.length; i++) {
                final HexFieldValue valueToDraw = stackValues[i];
                if (valueToDraw == null) {
                    continue;
                }
                g.drawImage(cachedIcons[i][valueToDraw.getIndex()], 0, 0, null);
            }
        }

    });

    final Path2D hexShape = ((ColorHexRender) engine.getRenderer()).getHexPath();
    final int cellWidth = hexShape.getBounds().width;
    final int cellHeight = hexShape.getBounds().height;

    for (int layerIndex = 0; layerIndex < reversedNormalizedStack.size()
            && !Thread.currentThread().isInterrupted(); layerIndex++) {
        final HexFieldLayer theLayer = reversedNormalizedStack.get(layerIndex);
        final Image[] cacheLineForLayer = new Image[theLayer.getHexValuesNumber()];
        for (int valueIndex = 1; valueIndex < theLayer.getHexValuesNumber(); valueIndex++) {
            cacheLineForLayer[valueIndex] = theLayer.getHexValueForIndex(valueIndex).makeIcon(cellWidth,
                    cellHeight, hexShape, true);
        }
        cachedIcons[layerIndex] = cacheLineForLayer;
    }

    engine.drawWithThreadInterruptionCheck(gfx);
    if (Thread.currentThread().isInterrupted())
        return null;

    if (this.exportData.isCellCommentariesExport()) {
        final Iterator<Entry<HexPosition, String>> iterator = this.cellComments.iterator();
        gfx.setFont(new Font("Arial", Font.BOLD, 12));
        while (iterator.hasNext() && !Thread.currentThread().isInterrupted()) {
            final Entry<HexPosition, String> item = iterator.next();
            final HexPosition pos = item.getKey();
            final String text = item.getValue();
            final float x = engine.calculateX(pos.getColumn(), pos.getRow());
            final float y = engine.calculateY(pos.getColumn(), pos.getRow());

            final Rectangle2D textBounds = gfx.getFontMetrics().getStringBounds(text, gfx);

            final float dx = x - ((float) textBounds.getWidth() - engine.getCellWidth()) / 2;

            gfx.setColor(Color.BLACK);
            gfx.drawString(text, dx, y);
            gfx.setColor(Color.WHITE);
            gfx.drawString(text, dx - 2, y - 2);
        }
    }

    gfx.dispose();

    return result;
}