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:algorithm.QRCodeWatermarking.java

/**
 * Creates a PNG image that contains the QR-code with the information from
 * the payload file. The image has the same name as the payload file.
 * /*from   ww w  .j  a v  a 2  s.c o  m*/
 * @param payload
 * @return qr code as png image file
 * @throws IOException
 */
private File createBarcodeFile(File payload, String imageFormat, String usedMethod) throws IOException {
    // Create restoration metadata only for the payload file to spare space.
    PayloadSegment metadata = new PayloadSegment(payload);
    metadata.addOptionalProperty("usedMethod", usedMethod);
    byte[] payloadSegment = metadata.getPayloadSegmentBytes();
    String barcodeInformation = new String(payloadSegment);
    int size = getQRCodeSize();
    String outputFileName = FilenameUtils.removeExtension(getOutputFileName(payload)) + "." + imageFormat;
    File outputFile = new File(outputFileName);
    Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
    hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
    BitMatrix byteMatrix = encodeWithQRCode(barcodeInformation, hintMap, size);
    if (byteMatrix == null) {
        return null;
    }
    BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
    image.createGraphics();
    Graphics2D graphics = (Graphics2D) image.getGraphics();
    graphics.setColor(Color.WHITE);
    graphics.fillRect(0, 0, size, size);
    graphics.setColor(Color.BLACK);
    for (int x = 0; x < size; x++) {
        for (int y = 0; y < size; y++) {
            if (byteMatrix.get(x, y)) {
                graphics.fillRect(x, y, 1, 1);
            }
        }
    }
    ImageIO.write(image, imageFormat, outputFile);
    return outputFile;
}

From source file:org.deegree.graphics.charts.ChartsBuilder.java

/**
 * Creates a BufferedImage instance from a given chart, according to the given additional parameters
 *
 * @param chart//from  w ww  .j  av  a  2 s.  c  o  m
 * @param width
 *            of the generated image
 * @param height
 *            of the generated image
 * @param imageType
 *            ex image/png, image/jpg
 * @return BufferedImage
 */
protected BufferedImage createBufferedImage(JFreeChart chart, int width, int height, String imageType) {

    chart.setTextAntiAlias(true);
    chart.setAntiAlias(true);
    BufferedImage image = new BufferedImage(width, height, mapImageformat(imageType));
    Graphics2D g2 = image.createGraphics();
    chart.draw(g2, new Rectangle(new Dimension(width, height)));
    return image;
}

From source file:edu.ku.brc.specify.utilapps.ERDTable.java

/**
 * Returns the BufferedImage of a background shadow. I creates a large rectangle than the orignal image.
 * @return Returns the BufferedImage of a background shadow. I creates a large rectangle than the orignal image.
 *//*from   w ww .j ava 2  s  .c  o m*/
private BufferedImage getBackgroundImageBuffer() {
    if (shadowBuffer == null) {
        ShadowFactory factory = new ShadowFactory(SHADOW_SIZE, 0.17f, Color.BLACK);

        Dimension size = inner.getSize();
        BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);

        Graphics2D g2 = image.createGraphics();
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, image.getWidth(), image.getHeight());
        g2.dispose();

        shadowBuffer = factory.createShadow(image);
    }
    return shadowBuffer;
}

From source file:org.nekorp.workflow.desktop.servicio.reporte.orden.servicio.OrdenServicioDataFactory.java

private void generaImagenDamage(ShapeView fondo, List<DamageDetailsVB> danios, File outputfile, int width,
        int height) {
    try {//from  w w w . j  av a2 s  .  c  o  m
        Point contexto = new Point((width - fondo.getShapeWidth()) / 2, (height - fondo.getShapeHeight()) / 2);
        BufferedImage off_Image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = off_Image.createGraphics();
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, width, height);
        AffineTransform saveXform = g2.getTransform();
        AffineTransform toCenterAt = new AffineTransform();
        toCenterAt.translate(contexto.getX(), contexto.getY());
        g2.transform(toCenterAt);
        fondo.paint(g2);
        g2.setTransform(saveXform);
        for (DamageDetailsVB x : danios) {
            DamageDetailGraphicsView obj = new DamageDetailGraphicsView();
            obj.setPosicion(new Point(x.getX(), x.getY()));
            obj.setContexto(contexto);
            if (x.getX() <= fondo.getShapeWidth() / 2) {
                if (x.getY() <= fondo.getShapeHeight() / 2) {
                    obj.setOrientacion(DamageDetailGraphicsView.SuperiorIzquierda);
                } else {
                    obj.setOrientacion(DamageDetailGraphicsView.InferiorIzquierda);
                }
            } else {
                if (x.getY() <= fondo.getShapeHeight() / 2) {
                    obj.setOrientacion(DamageDetailGraphicsView.SuperiorDerecha);
                } else {
                    obj.setOrientacion(DamageDetailGraphicsView.InferiorDerecha);
                }
            }
            obj.setCategoria(x.getCategoria());
            obj.setCaracteristica(x.getCaracteristica());
            obj.paint(g2);
        }
        saveJPG(off_Image, outputfile);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:net.sourceforge.processdash.ui.web.CGIChartBase.java

/** Generate CGI chart output. */
@Override/*from  w ww .  ja v  a 2 s.c  o m*/
protected void writeContents() throws IOException {
    buildData(); // get the data for display

    chromeless = (parameters.get("chromeless") != null);
    JFreeChart chart = createChart();

    int width = getIntSetting("width");
    int height = getIntSetting("height");
    Color initGradColor = getColorSetting("initGradColor");
    Color finalGradColor = getColorSetting("finalGradColor");
    chart.setBackgroundPaint(new GradientPaint(0, 0, initGradColor, width, height, finalGradColor));
    if (parameters.get("hideOutline") != null)
        chart.getPlot().setOutlinePaint(INVISIBLE);

    String title = getSetting("title");
    if (chromeless || title == null || title.length() == 0)
        chart.setTitle((TextTitle) null);
    else {
        chart.setTitle(Translator.translate(title));
        String titleFontSize = getSetting("titleFontSize");
        if (titleFontSize != null)
            try {
                float fontSize = Float.parseFloat(titleFontSize);
                TextTitle t = chart.getTitle();
                t.setFont(t.getFont().deriveFont(fontSize));
            } catch (Exception tfe) {
            }
    }

    if (chromeless || parameters.get("hideLegend") != null)
        chart.removeLegend();
    else {
        LegendTitle l = chart.getLegend();
        String legendFontSize = getSetting("legendFontSize");
        if (l != null && legendFontSize != null)
            try {
                float fontSize = Float.parseFloat(legendFontSize);
                l.setItemFont(l.getItemFont().deriveFont(fontSize));
            } catch (Exception lfe) {
            }
    }

    chart.getPlot().setNoDataMessage(resources.getString("No_Data_Message"));

    Axis xAxis = getHorizontalAxis(chart);
    if (xAxis != null) {
        if (parameters.get("hideTickLabels") != null || parameters.get("hideXTickLabels") != null) {
            xAxis.setTickLabelsVisible(false);
        } else if (parameters.get("tickLabelFontSize") != null
                || parameters.get("xTickLabelFontSize") != null) {
            String tfs = getParameter("xTickLabelFontSize");
            if (tfs == null)
                tfs = getParameter("tickLabelFontSize");
            float fontSize = Float.parseFloat(tfs);
            xAxis.setTickLabelFont(xAxis.getTickLabelFont().deriveFont(fontSize));
        }
    }

    Axis yAxis = getVerticalAxis(chart);
    if (yAxis != null) {
        if (parameters.get("hideTickLabels") != null || parameters.get("hideYTickLabels") != null) {
            yAxis.setTickLabelsVisible(false);
        } else if (parameters.get("tickLabelFontSize") != null
                || parameters.get("yTickLabelFontSize") != null) {
            String tfs = getParameter("yTickLabelFontSize");
            if (tfs == null)
                tfs = getParameter("tickLabelFontSize");
            float fontSize = Float.parseFloat(tfs);
            yAxis.setTickLabelFont(yAxis.getTickLabelFont().deriveFont(fontSize));
        }
    }

    String axisFontSize = getSetting("axisLabelFontSize");
    if (axisFontSize != null)
        try {
            float fontSize = Float.parseFloat(axisFontSize);
            if (xAxis != null)
                xAxis.setLabelFont(xAxis.getLabelFont().deriveFont(fontSize));
            if (yAxis != null)
                yAxis.setLabelFont(yAxis.getLabelFont().deriveFont(fontSize));
        } catch (Exception afs) {
        }

    ChartRenderingInfo info = (isHtmlMode() ? new ChartRenderingInfo() : null);
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = img.createGraphics();
    if ("auto".equals(getSetting("titleFontSize")))
        maybeAdjustTitleFontSize(chart, g2, width);
    chart.draw(g2, new Rectangle2D.Double(0, 0, width, height), info);
    g2.dispose();

    String outputFormat = getSetting("outputFormat");
    OutputStream imgOut;
    if (isHtmlMode()) {
        imgOut = PngCache.getOutputStream();
    } else {
        imgOut = outStream;
    }
    ImageIO.write(img, outputFormat, imgOut);
    imgOut.flush();
    imgOut.close();
    if (isHtmlMode())
        writeImageHtml(width, height, imgOut.hashCode(), info);
}

From source file:edu.umn.cs.spatialHadoop.operations.PyramidPlot.java

private static void plotLocal(Path inFile, Path outFile, OperationsParams params) throws IOException {
    int tileWidth = params.getInt("tilewidth", 256);
    int tileHeight = params.getInt("tileheight", 256);

    Color strokeColor = params.getColor("color", Color.BLACK);

    String hdfDataset = (String) params.get("dataset");
    Shape shape = hdfDataset != null ? new NASARectangle() : (Shape) params.getShape("shape", null);
    Shape plotRange = params.getShape("rect", null);

    String valueRangeStr = (String) params.get("valuerange");
    MinMax valueRange;/*from   w ww . ja v a  2 s.  c om*/
    if (valueRangeStr == null) {
        valueRange = null;
    } else {
        String[] parts = valueRangeStr.split(",");
        valueRange = new MinMax(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
    }

    InputSplit[] splits;
    FileSystem inFs = inFile.getFileSystem(params);
    FileStatus inFStatus = inFs.getFileStatus(inFile);
    if (inFStatus != null && !inFStatus.isDir()) {
        // One file, retrieve it immediately.
        // This is useful if the input is a hidden file which is automatically
        // skipped by FileInputFormat. We need to plot a hidden file for the case
        // of plotting partition boundaries of a spatial index
        splits = new InputSplit[] { new FileSplit(inFile, 0, inFStatus.getLen(), new String[0]) };
    } else {
        JobConf job = new JobConf(params);
        ShapeInputFormat<Shape> inputFormat = new ShapeInputFormat<Shape>();
        ShapeInputFormat.addInputPath(job, inFile);
        splits = inputFormat.getSplits(job, 1);
    }

    boolean vflip = params.is("vflip");

    Rectangle fileMBR;
    if (plotRange != null) {
        fileMBR = plotRange.getMBR();
    } else if (hdfDataset != null) {
        // Plotting a NASA file
        fileMBR = new Rectangle(-180, -90, 180, 90);
    } else {
        fileMBR = FileMBR.fileMBR(inFile, params);
    }

    boolean keepAspectRatio = params.is("keep-ratio", true);
    if (keepAspectRatio) {
        // Adjust width and height to maintain aspect ratio
        if (fileMBR.getWidth() > fileMBR.getHeight()) {
            fileMBR.y1 -= (fileMBR.getWidth() - fileMBR.getHeight()) / 2;
            fileMBR.y2 = fileMBR.y1 + fileMBR.getWidth();
        } else {
            fileMBR.x1 -= (fileMBR.getHeight() - fileMBR.getWidth() / 2);
            fileMBR.x2 = fileMBR.x1 + fileMBR.getHeight();
        }
    }

    if (hdfDataset != null) {
        // Collects some stats about the HDF file
        if (valueRange == null)
            valueRange = Aggregate.aggregate(new Path[] { inFile }, params);
        NASAPoint.minValue = valueRange.minValue;
        NASAPoint.maxValue = valueRange.maxValue;
        NASAPoint.setColor1(params.getColor("color1", Color.BLUE));
        NASAPoint.setColor2(params.getColor("color2", Color.RED));
        NASAPoint.gradientType = params.getGradientType("gradient", NASAPoint.GradientType.GT_HUE);
    }

    boolean adaptiveSampling = params.getBoolean("sample", false);

    int numLevels = params.getInt("numlevels", 7);

    float[] levelProb = new float[numLevels];
    double[] scale2 = new double[numLevels];
    double[] scale = new double[numLevels];
    levelProb[0] = params.getFloat(GeometricPlot.AdaptiveSampleRatio, 0.1f);
    // Size of the whole file in pixels at the f

    scale2[0] = (double) tileWidth * tileHeight / (fileMBR.getWidth() * fileMBR.getHeight());
    scale[0] = Math.sqrt(scale2[0]);
    for (int level = 1; level < numLevels; level++) {
        levelProb[level] = levelProb[level - 1] * 4;
        scale2[level] = scale2[level - 1] * (1 << level) * (1 << level);
        scale[level] = scale[level - 1] * (1 << level);
    }

    Map<TileIndex, BufferedImage> tileImages = new HashMap<PyramidPlot.TileIndex, BufferedImage>();

    Map<TileIndex, Graphics2D> tileGraphics = new HashMap<PyramidPlot.TileIndex, Graphics2D>();

    GridInfo bottomGrid = new GridInfo(fileMBR.x1, fileMBR.y1, fileMBR.x2, fileMBR.y2);
    bottomGrid.rows = bottomGrid.columns = (int) Math.round(Math.pow(2, numLevels - 1));

    TileIndex tileIndex = new TileIndex();
    boolean gradualFade = !(shape instanceof Point) && params.getBoolean("fade", false);

    for (InputSplit split : splits) {
        ShapeRecordReader<Shape> reader = new ShapeRecordReader<Shape>(params, (FileSplit) split);
        Rectangle cell = reader.createKey();
        while (reader.next(cell, shape)) {
            Rectangle shapeMBR = shape.getMBR();
            if (shapeMBR != null) {
                int min_level = 0;

                if (adaptiveSampling) {
                    // Special handling for NASA data
                    double p = Math.random();
                    // Skip levels that do not satisfy the probability
                    while (min_level < numLevels && p > levelProb[min_level])
                        min_level++;
                }

                java.awt.Rectangle overlappingCells = bottomGrid.getOverlappingCells(shapeMBR);
                for (tileIndex.level = numLevels - 1; tileIndex.level >= min_level; tileIndex.level--) {
                    if (gradualFade && !(shape instanceof Point)) {
                        double areaInPixels = (shapeMBR.getWidth() + shapeMBR.getHeight())
                                * scale[tileIndex.level];
                        if (areaInPixels < 1.0 && Math.round(areaInPixels * 255) < 1.0) {
                            // This shape can be safely skipped as it is too small to be plotted
                            return;
                        }
                    }

                    for (int i = 0; i < overlappingCells.width; i++) {
                        tileIndex.x = i + overlappingCells.x;
                        for (int j = 0; j < overlappingCells.height; j++) {
                            tileIndex.y = j + overlappingCells.y;
                            // Draw in image associated with this tile
                            Graphics2D g;
                            {
                                g = tileGraphics.get(tileIndex);
                                if (g == null) {
                                    TileIndex key = tileIndex.clone();
                                    BufferedImage image = new BufferedImage(tileWidth, tileHeight,
                                            BufferedImage.TYPE_INT_ARGB);
                                    if (tileImages.put(key, image) != null)
                                        throw new RuntimeException(
                                                "Error! Image is already there but graphics is not "
                                                        + tileIndex);

                                    Color bg_color = new Color(0, 0, 0, 0);

                                    try {
                                        g = image.createGraphics();
                                    } catch (Throwable e) {
                                        g = new SimpleGraphics(image);
                                    }
                                    g.setBackground(bg_color);
                                    g.clearRect(0, 0, tileWidth, tileHeight);
                                    g.setColor(strokeColor);
                                    // Coordinates of this tile in image coordinates
                                    g.translate(-(tileWidth * tileIndex.x), -(tileHeight * tileIndex.y));

                                    tileGraphics.put(key, g);
                                }
                            }

                            shape.draw(g, fileMBR, tileWidth * (1 << tileIndex.level),
                                    tileHeight * (1 << tileIndex.level), scale2[tileIndex.level]);
                        }
                    }
                    // Shrink overlapping cells to match the upper level
                    int updatedX1 = overlappingCells.x / 2;
                    int updatedY1 = overlappingCells.y / 2;
                    int updatedX2 = (overlappingCells.x + overlappingCells.width - 1) / 2;
                    int updatedY2 = (overlappingCells.y + overlappingCells.height - 1) / 2;
                    overlappingCells.x = updatedX1;
                    overlappingCells.y = updatedY1;
                    overlappingCells.width = updatedX2 - updatedX1 + 1;
                    overlappingCells.height = updatedY2 - updatedY1 + 1;
                }
            }
        }
        reader.close();
    }
    // Write image to output
    for (Map.Entry<TileIndex, Graphics2D> tileGraph : tileGraphics.entrySet()) {
        tileGraph.getValue().dispose();
    }
    FileSystem outFS = outFile.getFileSystem(params);
    for (Map.Entry<TileIndex, BufferedImage> tileImage : tileImages.entrySet()) {
        tileIndex = tileImage.getKey();
        BufferedImage image = tileImage.getValue();
        if (vflip) {
            AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
            tx.translate(0, -image.getHeight());
            AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
            image = op.filter(image, null);
            tileIndex.y = ((1 << tileIndex.level) - 1) - tileIndex.y;
        }
        Path imagePath = new Path(outFile, tileIndex.getImageFileName());
        FSDataOutputStream outStream = outFS.create(imagePath);
        ImageIO.write(image, "png", outStream);
        outStream.close();
    }
}

From source file:algo.PlotBar.java

private BufferedImage bufferResize(BufferedImage original, double widthFactor, double heightFactor) {

    // original image width & height
    int w, h;/*  w  w  w . j  a  v  a2s .  co m*/
    w = original.getHeight();
    h = original.getWidth();
    //        System.out.println(original.getHeight());
    //        System.out.println(original.getWidth());

    // new width & height calculated by multiplying factor
    int newWidth = new Double(original.getWidth() * widthFactor).intValue();
    int newHeight = new Double(original.getWidth() * heightFactor).intValue();

    // new resized image
    BufferedImage buffResized = new BufferedImage(newWidth, newHeight, original.getType());

    Graphics2D g = buffResized.createGraphics();

    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.drawImage(original, 0, 0, newWidth, newHeight, 0, 0, w, h, null);
    g.dispose();

    return buffResized;
}

From source file:it.lufraproini.cms.servlet.Upload.java

private Boolean creaThumbnail(Immagine img, String username) {
    String cartella = getServletContext().getInitParameter("system.image_directory");
    String file_img = img.getFile().substring(img.getFile().indexOf("/"));
    String path = getServletContext().getRealPath(cartella);
    int altezza_thumb = 120;
    int larghezza_thumb = 120;
    BufferedImage thumb = new BufferedImage(larghezza_thumb, altezza_thumb, BufferedImage.TYPE_INT_RGB);
    try {/* ww  w .ja va 2s.  c  om*/
        if (ImageIO.read(new File(path + file_img)).getWidth() >= larghezza_thumb) {
            thumb.createGraphics().drawImage(ImageIO.read(new File(path + file_img)).getScaledInstance(-1,
                    altezza_thumb, Image.SCALE_SMOOTH), 0, 0, null);
        } else {
            thumb.createGraphics().drawImage(ImageIO.read(new File(path + file_img))
                    .getScaledInstance(larghezza_thumb, altezza_thumb, Image.SCALE_SMOOTH), 0, 0, null);
        }

        ImageIO.write(thumb, estensione,
                new File(path + File.separatorChar + "thumbnail_" + username + "." + estensione));
    } catch (IOException ex) {
        return false;
    }
    return true;
}

From source file:org.objectweb.proactive.extensions.timitspmd.util.charts.MatrixChart.java

private void buildFinalChart(String title, String subTitle, String filename, String xAxisLabel,
        String yAxisLabel, int width, int height) {
    this.buildMainChart(title, subTitle, xAxisLabel, yAxisLabel, filename);

    this.buildLegendChart(5);

    BufferedImage mainChartImage = this.mainChart.createBufferedImage(width, height);
    BufferedImage legendChartImage = this.legendChart.createBufferedImage(width / 6, height / 3);
    BufferedImage info = null;/*  w  w  w. j a v a 2  s  .  c  o  m*/
    try {
        info = ImageIO.read(MatrixChart.logoFile);
    } catch (IOException ex) {
    }

    BufferedImage total = new BufferedImage(width + (width / 6), height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = total.createGraphics();

    g.drawImage(mainChartImage, 0, 0, null);
    g.drawImage(legendChartImage, width, height / 4, null);
    g.setPaint(Color.WHITE);
    g.fillRect(width, 0, width, height / 4);
    g.fillRect(width, (height / 4) + (height / 3), width, height);
    if (info != null) {
        // g.drawImage(info, (width+(width/6))-info.getWidth(),10, null); //
        // up-right
        g.drawImage(info, (width + (width / 6)) - info.getWidth(), height - info.getHeight(), null); // down-right
    }
    g.dispose();

    try {
        javax.imageio.ImageIO.write(total, "png", XMLHelper.createFileWithDirs(filename));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:PSDReader.java

/**
 * Gets the image contents of frame n. Note that this expands the image to the
 * full frame size (if the layer was smaller) and any subsequent use of
 * getLayer() will return the full image.
 * /*from w  w  w .  ja  va  2  s. c om*/
 * @return BufferedImage representation of frame, or null if n is invalid.
 */
public BufferedImage getFrame(int n) {
    BufferedImage im = null;
    if ((n >= 0) && (n < nLayers)) {
        im = frames[n];
        LayerInfo info = layers[n];
        if ((info.w != width) || (info.h != height)) {
            BufferedImage temp = new BufferedImage(width, height, ImageType);
            Graphics2D gc = temp.createGraphics();
            gc.drawImage(im, info.x, info.y, null);
            gc.dispose();
            im = temp;
            frames[n] = im;
        }
    }
    return im;
}