Example usage for java.awt.image BufferedImage createGraphics

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

Introduction

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

Prototype

public Graphics2D createGraphics() 

Source Link

Document

Creates a Graphics2D , which can be used to draw into this BufferedImage .

Usage

From source file:org.n52.io.img.ChartRenderer.java

private BufferedImage drawChartToImage() {
    int width = getChartStyleDefinitions().getWidth();
    int height = getChartStyleDefinitions().getHeight();
    BufferedImage chartImage = new BufferedImage(width, height, TYPE_INT_RGB);
    Graphics2D chartGraphics = chartImage.createGraphics();
    chartGraphics.fillRect(0, 0, width, height);
    chartGraphics.setColor(WHITE);/*www . j  a v  a 2  s  .  c  om*/

    chart.setTextAntiAlias(true);
    chart.setAntiAlias(true);
    chart.draw(chartGraphics, new Rectangle2D.Float(0, 0, width, height));
    return chartImage;
}

From source file:com.toughland.helpmechoose.common.Helper.java

private String blendImages(List<String> fileNames, String path, Integer userId) {

    int chunkWidth, chunkHeight;
    int type;/* ww w  . j  a v a2  s .c om*/
    String newFileName = path + userId + "_final.jpg";

    //fetching image files  
    File[] imgFiles = new File[fileNames.size()];
    for (int i = 0; i < fileNames.size(); i++) {
        imgFiles[i] = new File(fileNames.get(i));
    }

    //creating a bufferd image array from image files  
    BufferedImage[] buffImages = new BufferedImage[fileNames.size()];
    for (int i = 0; i < fileNames.size(); i++) {
        try {
            buffImages[i] = ImageIO.read(imgFiles[i]);
        } catch (IOException ex) {
            Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    type = buffImages[0].getType();
    chunkWidth = buffImages[0].getWidth();
    chunkHeight = buffImages[0].getHeight();

    //Initializing the final image  
    BufferedImage finalImg = new BufferedImage(chunkWidth * 2, chunkHeight * 2, type);

    int num = 0;
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            finalImg.createGraphics().drawImage(buffImages[num], chunkWidth * j, chunkHeight * i, null);
            num++;
        }
    }

    System.out.println("Image concatenated.....");

    try {
        ImageIO.write(finalImg, "jpeg", new File(newFileName));
    } catch (IOException ex) {
        Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, ex);
    }

    return userId.toString() + "_final.jpg";
}

From source file:eu.udig.style.advanced.points.PointStyleManager.java

private TableViewer createStylesTableViewer(Composite parent) {
    final StyleFilter filter = new StyleFilter();
    final Text searchText = new Text(parent, SWT.BORDER | SWT.SEARCH);
    searchText.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
    searchText.addKeyListener(new KeyAdapter() {
        public void keyReleased(KeyEvent ke) {
            filter.setSearchText(searchText.getText());
            stylesViewer.refresh();/*from  ww  w. jav a  2s  .c o  m*/
        }

    });

    stylesViewer = new TableViewer(parent, SWT.SINGLE | SWT.BORDER);
    Table table = stylesViewer.getTable();
    GridData tableGD = new GridData(SWT.FILL, SWT.FILL, true, true);
    tableGD.heightHint = 200;
    table.setLayoutData(tableGD);

    stylesViewer.addFilter(filter);
    stylesViewer.setContentProvider(new IStructuredContentProvider() {
        public Object[] getElements(Object inputElement) {
            if (inputElement instanceof List<?>) {
                List<?> styles = (List<?>) inputElement;
                StyleWrapper[] array = (StyleWrapper[]) styles.toArray(new StyleWrapper[styles.size()]);
                return array;
            }
            return null;
        }

        public void dispose() {
        }

        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
        }
    });

    stylesViewer.setLabelProvider(new LabelProvider() {
        public Image getImage(Object element) {
            if (element instanceof StyleWrapper) {
                StyleWrapper styleWrapper = (StyleWrapper) element;
                List<FeatureTypeStyleWrapper> featureTypeStyles = styleWrapper
                        .getFeatureTypeStylesWrapperList();
                int iconSize = 48;
                BufferedImage image = new BufferedImage(iconSize, iconSize, BufferedImage.TYPE_INT_ARGB);
                Graphics2D g2d = image.createGraphics();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                for (FeatureTypeStyleWrapper featureTypeStyle : featureTypeStyles) {
                    List<RuleWrapper> rulesWrapperList = featureTypeStyle.getRulesWrapperList();
                    BufferedImage tmpImage = Utilities.pointRulesWrapperToImage(rulesWrapperList, iconSize,
                            iconSize);
                    g2d.drawImage(tmpImage, 0, 0, null);
                }
                g2d.dispose();
                Image convertToSWTImage = AWTSWTImageUtils.convertToSWTImage(image);
                return convertToSWTImage;
            }
            return null;
        }

        public String getText(Object element) {
            if (element instanceof StyleWrapper) {
                StyleWrapper styleWrapper = (StyleWrapper) element;
                String styleName = styleWrapper.getName();
                if (styleName == null || styleName.length() == 0) {
                    styleName = Utilities.DEFAULT_STYLENAME;
                    styleName = Utilities.checkSameNameStyle(getStyles(), styleName);
                    styleWrapper.setName(styleName);
                }
                return styleName;
            }
            return ""; //$NON-NLS-1$
        }
    });

    stylesViewer.addSelectionChangedListener(new ISelectionChangedListener() {

        public void selectionChanged(SelectionChangedEvent event) {
            ISelection selection = event.getSelection();
            if (!(selection instanceof IStructuredSelection)) {
                return;
            }
            IStructuredSelection sel = (IStructuredSelection) selection;
            if (sel.isEmpty()) {
                return;
            }

            Object selectedItem = sel.getFirstElement();
            if (selectedItem == null) {
                // unselected, show empty panel
                return;
            }

            if (selectedItem instanceof StyleWrapper) {
                currentSelectedStyleWrapper = (StyleWrapper) selectedItem;
            }
        }

    });
    return stylesViewer;
}

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

private Image renderLegend(ObservationSeriesCollection obsValues, String observedProperty) {

    double lowestValue = (Double) obsValues.getMinimum(0);
    double highestValue = (Double) obsValues.getMaximum(0);

    double classDistance = (highestValue - lowestValue) / (NUMBER_OF_CLASSES - 2);
    int dotSizeDistance = (MAX_DOT_SIZE - MIN_DOT_SIZE) / (NUMBER_OF_CLASSES - 2);

    BufferedImage image = new BufferedImage(LEGEND_WIDTH, LEGEND_HEIGHT, BufferedImage.TYPE_INT_RGB);

    Graphics2D g = image.createGraphics();

    // draw white background:
    g.setColor(Color.WHITE);/* w w  w.j a v a  2  s.  c o  m*/
    g.fillRect(0, 0, LEGEND_WIDTH, LEGEND_HEIGHT);

    // draw information:
    observedProperty = observedProperty.split(":")[observedProperty.split(":").length - 1];
    g.setColor(Color.BLACK);
    g.drawString("Observed Property:   '" + observedProperty + "'", 25, 25);

    for (int i = 1; i <= NUMBER_OF_CLASSES; i++) {
        // draw text:
        int x_stringLocation = 100;
        int y_location = i * 60;
        g.setColor(Color.BLACK);

        DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.GERMAN);
        df.applyPattern("#,###,##0.00");

        double lowerBorder = lowestValue + classDistance * (i - 1);
        double upperBorder = lowestValue + classDistance * i;

        g.drawString(i + ". class: " + df.format(lowerBorder) + " - " + df.format(upperBorder),
                x_stringLocation, y_location + 10);

        // draw symbol:
        int x_symbolLocation = 30;
        g.setColor(POINT_INNER_COLOR);
        g.fillOval(x_symbolLocation, y_location, i * dotSizeDistance, i * dotSizeDistance);
    }

    return image;
}

From source file:ddf.catalog.transformer.input.tika.TikaInputTransformer.java

private void createThumbnail(InputStream input, Metacard metacard) {
    try {//from w  w  w  . j  ava  2  s  . c  om
        Image image = ImageIO.read(new CloseShieldInputStream(input));

        if (null != image) {
            BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = bufferedImage.createGraphics();
            graphics.drawImage(image, null, null);
            graphics.dispose();

            BufferedImage thumb = Scalr.resize(bufferedImage, 200);

            try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                ImageIO.write(thumb, "jpeg", out);

                byte[] thumbBytes = out.toByteArray();
                metacard.setAttribute(new AttributeImpl(Metacard.THUMBNAIL, thumbBytes));
            }
        } else {
            LOGGER.warn("Unable to read image from input stream to create thumbnail.");
        }
    } catch (Exception e) {
        LOGGER.warn("Unable to read image from input stream to create thumbnail.", e);
    }
}

From source file:dk.dma.msinm.web.OsmStaticMap.java

public BufferedImage createBaseMap(MapImageCtx ctx) {
    BufferedImage image = new BufferedImage(ctx.width, ctx.height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    int startX = (int) Math.floor(ctx.centerX - (ctx.width / ctx.tileSize) / 2.0);
    int startY = (int) Math.floor(ctx.centerY - (ctx.height / ctx.tileSize) / 2.0);
    int endX = (int) Math.ceil(ctx.centerX + (ctx.width / ctx.tileSize) / 2.0);
    int endY = (int) Math.ceil(ctx.centerY + (ctx.height / ctx.tileSize) / 2.0);
    ctx.offsetX = -Math.floor((ctx.centerX - Math.floor(ctx.centerX)) * ctx.tileSize);
    ctx.offsetY = -Math.floor((ctx.centerY - Math.floor(ctx.centerY)) * ctx.tileSize);
    ctx.offsetX += Math.floor(ctx.width / 2.0);
    ctx.offsetY += Math.floor(ctx.height / 2.0);
    ctx.offsetX += Math.floor(startX - Math.floor(ctx.centerX)) * ctx.tileSize;
    ctx.offsetY += Math.floor(startY - Math.floor(ctx.centerY)) * ctx.tileSize;

    for (int x = startX; x <= endX; x++) {
        for (int y = startY; y <= endY; y++) {
            String url = String.format(OSM_URL, ctx.zoom, x, y);
            log.info("Fetching " + url);
            try {
                BufferedImage tileImage = fetchTile(url);
                double destX = (x - startX) * ctx.tileSize + ctx.offsetX;
                double destY = (y - startY) * ctx.tileSize + ctx.offsetY;
                g2.drawImage(tileImage, (int) destX, (int) destY, ctx.tileSize, ctx.tileSize, null);
                image.flush();/*from w ww.  j  ava 2s.  c o  m*/
            } catch (Exception e) {
                log.warn("Failed loading image " + url);
            }
        }
    }
    return image;
}

From source file:org.n52.io.measurement.img.ChartIoHandler.java

private BufferedImage createImage() {
    int width = getChartStyleDefinitions().getWidth();
    int height = getChartStyleDefinitions().getHeight();
    BufferedImage chartImage = new BufferedImage(width, height, TYPE_INT_RGB);
    Graphics2D chartGraphics = chartImage.createGraphics();
    chartGraphics.fillRect(0, 0, width, height);
    chartGraphics.setColor(WHITE);//ww w . j  a  v  a  2 s .com

    chart.setTextAntiAlias(true);
    chart.setAntiAlias(true);
    if (chart.getLegend() != null) {
        chart.getLegend().setFrame(BlockBorder.NONE);
    }
    chart.draw(chartGraphics, new Rectangle2D.Float(0, 0, width, height));
    return chartImage;
}

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

/**
 * renders one frame of the animation./*w  w w.  ja  va 2 s.co m*/
 */
private Image renderFrame(ITimePosition[] sortedTimeArray, int currentTimeIndex, int screenW, int screenH,
        IBoundingBox bbox, Set<OXFFeature> selectedFeatures, ObservationSeriesCollection obsValues) {
    ContextBoundingBox contextBBox = new ContextBoundingBox(bbox);

    BufferedImage image = new BufferedImage(screenW, screenH, BufferedImage.TYPE_INT_RGB);

    Graphics2D g = image.createGraphics();

    ITimePosition currentTimePos = sortedTimeArray[currentTimeIndex];

    // draw white background:
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, screenW, screenH);

    // draw time-string into map:
    g.setColor(Color.BLACK);
    g.drawString(currentTimePos.toString(), 20, 20);

    for (OXFFeature dotFeature : selectedFeatures) {

        //
        // draw the points into the image at the georeferenced position of the corresponding feature:
        //
        Point pRealWorld = (Point) dotFeature.getGeometry();

        java.awt.Point pScreen = ContextBoundingBox.realworld2Screen(contextBBox.getActualBBox(), screenW,
                screenH, new Point2D.Double(pRealWorld.getCoordinate().x, pRealWorld.getCoordinate().y));

        ObservedValueTuple tuple = obsValues.getTuple(dotFeature, currentTimePos);

        // if there wasn't a tuple for the current time position go backwards through the sortedTimeArray and take the most recent one:
        int j = currentTimeIndex - 1;
        while (tuple == null && j >= 0) {
            tuple = obsValues.getTuple(dotFeature, sortedTimeArray[j]);
            j--;
        }

        // if a tuple was found -> draw the dot:
        if (tuple != null) {
            int dotSize = computeDotSize((Double) tuple.getValue(0), (Double) obsValues.getMinimum(0),
                    (Double) obsValues.getMaximum(0));
            g.setColor(POINT_INNER_COLOR);
            g.fillOval(pScreen.x - (dotSize / 2), pScreen.y - (dotSize / 2), dotSize, dotSize);
        }
        // otherwise draw "no data available"
        else {
            g.setColor(Color.BLACK);

            // draw point of feature:
            g.fillOval(pScreen.x - (FeatureGeometryRenderer.DOT_SIZE_POINT / 2),
                    pScreen.y - (FeatureGeometryRenderer.DOT_SIZE_POINT / 2),
                    FeatureGeometryRenderer.DOT_SIZE_POINT, FeatureGeometryRenderer.DOT_SIZE_POINT);

            g.drawString("No data available", pScreen.x + X_SHIFT, pScreen.y + Y_SHIFT);
        }
    }

    return image;
}

From source file:org.osjava.reportrunner_plugins.renderers.jfreechart.creators.TexturedBarRenderer.java

public java.awt.Paint getSeriesPaint(int row) {
    BufferedImage bufferedImage = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB);
    Graphics2D big = bufferedImage.createGraphics();
    TexturePaint texture = null;/* w  ww  .jav a2  s  . co  m*/
    int rowNum = row + 1;
    int patNum = 13;
    int formula = rowNum - ((rowNum / patNum) * patNum);

    if (formula == 0) {
        big.setColor(Color.orange);
        big.fillRect(0, 0, 5, 5);
        big.fillRect(1, 0, 5, 5);
        Rectangle r = new Rectangle(0, 0, 5, 5);
        texture = new TexturePaint(bufferedImage, r);

    } else if (formula == 1) {
        big.setColor(Color.red);
        big.fillRect(0, 0, 5, 5);
        big.fillRect(1, 0, 5, 5);
        Rectangle r = new Rectangle(0, 0, 5, 5);
        texture = new TexturePaint(bufferedImage, r);
    } else if (formula == 2) {
        Color color = Color.blue;
        big.setColor(Color.white);
        big.fillRect(0, 0, 5, 5);
        big.setColor(color);
        big.fillRect(0, 1, 5, 5);
        Rectangle r = new Rectangle(0, 0, 5, 5);

        texture = new TexturePaint(bufferedImage, r);
    } else if (formula == 3) {
        Color color = Color.yellow;
        big.setColor(Color.orange);
        big.fillRect(0, 0, 5, 5);
        big.setColor(color);
        big.fillRect(1, 1, 4, 4);
        Rectangle r = new Rectangle(0, 0, 5, 5);

        texture = new TexturePaint(bufferedImage, r);
    } else if (formula == 4) {
        big.setColor(Color.green);
        big.fillRect(0, 0, 5, 5);
        big.fillRect(1, 0, 5, 5);
        Rectangle r = new Rectangle(0, 0, 5, 5);
        texture = new TexturePaint(bufferedImage, r);
    } else if (formula == 5) {
        big.setColor(Color.magenta);
        big.fillRect(0, 0, 5, 5);
        big.setColor(Color.pink);
        big.fillRect(0, 0, 4, 4);

        Rectangle r = new Rectangle(0, 0, 5, 5);
        texture = new TexturePaint(bufferedImage, r);
    } else if (formula == 6) {
        float[] x = { .5f, 1.5f, 2.0f, 2.5f, 3.0f, 3.5f, 4.0f, 4.5f, 5.0f };
        float[] y = { .5f, 1.5f, 2.0f, 2.5f, 3.0f, 3.5f, 4.0f, 4.5f, 5.0f };
        GeneralPath path = new GeneralPath();
        path.moveTo(x[0], y[0]);
        for (int j = 1; j < x.length; j++) {
            path.lineTo(x[j], y[j]);
        }

        big.setColor(new Color(226, 199, 252));
        big.fillRect(0, 0, 5, 5);
        big.setColor(Color.blue);
        big.setStroke(new BasicStroke(1.0f));

        big.draw(path);
        Rectangle r = new Rectangle(0, 0, 5, 5);
        texture = new TexturePaint(bufferedImage, r);
    } else if (formula == 7) {
        big.setColor(Color.lightGray);
        big.fillRect(0, 0, 5, 5);
        big.setColor(Color.red);
        big.fillRect(1, 0, 5, 5);
        Rectangle r = new Rectangle(0, 0, 5, 5);
        texture = new TexturePaint(bufferedImage, r);
    } else if (formula == 8) {
        float[] x = { .5f, 1.5f, 2.0f, 2.5f, 3.0f, 3.5f, 4.0f, 4.5f, 5.0f };
        float[] y = { .5f, 1.5f, 2.0f, 2.5f, 3.0f, 3.5f, 4.0f, 4.5f, 5.0f };
        GeneralPath path = new GeneralPath();
        path.moveTo(x[0], y[0]);
        for (int j = 1; j < x.length; j++) {
            path.lineTo(x[j], y[j]);

        }
        big.setColor(Color.blue);
        big.fillRect(0, 0, 5, 5);
        big.setColor(Color.cyan);
        big.setStroke(new BasicStroke(2.0f));
        big.draw(path);
        Rectangle r = new Rectangle(0, 0, 5, 5);
        texture = new TexturePaint(bufferedImage, r);
    } else if (formula == 9) {
        Color color = new Color(0xBBBBDD);
        big.setColor(color);
        big.fillRect(0, 0, 5, 5);
        big.setColor(new Color(199, 201, 230));
        big.fillRect(1, 0, 5, 5);
        Rectangle r = new Rectangle(0, 0, 5, 5);
        texture = new TexturePaint(bufferedImage, r);
    } else if (formula == 10) {
        float[] x = { 1, 2, 3, 4, 5 };
        float[] y = { 1, 2, 3, 4, 5 };
        GeneralPath path = new GeneralPath();
        path.moveTo(x[0], y[1]);
        path.lineTo(x[1], y[0]);
        path.moveTo(x[0], y[2]);
        path.lineTo(x[2], y[0]);
        path.moveTo(x[0], y[3]);
        path.lineTo(x[3], y[0]);
        path.moveTo(x[0], y[4]);
        path.lineTo(x[4], y[0]);
        big.setColor(Color.red);
        big.fillRect(0, 0, 5, 5);
        big.setColor(new Color(242, 242, 193));
        big.setStroke(new BasicStroke(3.0f));
        big.draw(path);
        Rectangle r = new Rectangle(0, 0, 5, 5);
        texture = new TexturePaint(bufferedImage, r);
    } else if (formula == 11) {
        big.setColor(new Color(252, 169, 171));
        big.fillOval(0, 0, 5, 6);
        big.setColor(new Color(252, 230, 230));
        big.fillOval(0, 0, 3, 3);
        Rectangle r = new Rectangle(0, 0, 5, 5);
        texture = new TexturePaint(bufferedImage, r);
    } else if (formula == 12) {
        big.setColor(Color.green);
        big.fillRect(0, 0, 5, 5);
        big.setColor(new Color(20, 178, 38));
        big.fillRect(2, 2, 5, 5);
        Rectangle r = new Rectangle(0, 0, 5, 5);
        texture = new TexturePaint(bufferedImage, r);
    }
    return texture;

}

From source file:it.smartcommunitylab.parking.management.web.manager.MarkerIconStorage.java

private void generateMarkerWithFlag(String basePath, String company, String entity, String color)
        throws IOException {
    BufferedImage templateIcon = ImageIO.read(new File(getIconFolder(basePath, ICON_FOLDER) + TEMPLATE_FILE));
    BufferedImage icon = new BufferedImage(templateIcon.getWidth(), templateIcon.getHeight() + ICON_INCR_HEIGHT,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = icon.createGraphics();
    graphics.setColor(new Color(Integer.parseInt(color, 16)));
    graphics.drawRect(0, 0, icon.getWidth(), COLOR_RECT_HEIGHT);
    graphics.fillRect(0, 0, icon.getWidth(), COLOR_RECT_HEIGHT);
    graphics.drawImage(templateIcon, 0, ICON_INCR_HEIGHT, null);
    graphics.dispose();//from  w  w w  .  ja v a2 s .  c  om
    ImageIO.write(icon, ICON_TYPE, new File(getIconFolder(basePath, ICON_FOLDER_CACHE) + company + "-" + entity
            + "-" + color + ICON_EXTENSION));
}