Example usage for java.awt RenderingHints KEY_RENDERING

List of usage examples for java.awt RenderingHints KEY_RENDERING

Introduction

In this page you can find the example usage for java.awt RenderingHints KEY_RENDERING.

Prototype

Key KEY_RENDERING

To view the source code for java.awt RenderingHints KEY_RENDERING.

Click Source Link

Document

Rendering hint key.

Usage

From source file:com.hmsinc.epicenter.spatial.render.SpatialScanRenderer.java

/**
 * @param context/*from w ww  .j a  v  a2  s. c  o m*/
 * @return
 */
private BufferedImage renderImage(final MapContext context, int width, int height) {

    logger.trace("Image width: {}  height: {}", width, height);

    final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    final Graphics2D graphics2D = (Graphics2D) image.getGraphics();

    final GTRenderer renderer = new StreamingRenderer();
    final RenderingHints h = new RenderingHints(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    h.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    h.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    h.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
    h.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
    renderer.setJava2DHints(h);
    renderer.setContext(context);
    renderer.paint(graphics2D, new Rectangle(width, height), context.getAreaOfInterest());

    return image;
}

From source file:Thumbnail.java

/**
* Reads an image in a file and creates a thumbnail in another file.
* largestDimension is the largest dimension of the thumbnail, the other dimension is scaled accordingly.
* Utilises weighted stepping method to gradually reduce the image size for better results,
* i.e. larger steps to start with then smaller steps to finish with.
* Note: always writes a JPEG because GIF is protected or something - so always make your outFilename end in 'jpg'.
* PNG's with transparency are given white backgrounds
*///from  w  ww  .jav  a  2s  .  com
public String createThumbnail(String inFilename, String outFilename, int largestDimension) {
    try {
        double scale;
        int sizeDifference, originalImageLargestDim;
        if (!inFilename.endsWith(".jpg") && !inFilename.endsWith(".jpeg") && !inFilename.endsWith(".gif")
                && !inFilename.endsWith(".png")) {
            return "Error: Unsupported image type, please only either JPG, GIF or PNG";
        } else {
            Image inImage = Toolkit.getDefaultToolkit().getImage(inFilename);
            if (inImage.getWidth(null) == -1 || inImage.getHeight(null) == -1) {
                return "Error loading file: \"" + inFilename + "\"";
            } else {
                //find biggest dimension       
                if (inImage.getWidth(null) > inImage.getHeight(null)) {
                    scale = (double) largestDimension / (double) inImage.getWidth(null);
                    sizeDifference = inImage.getWidth(null) - largestDimension;
                    originalImageLargestDim = inImage.getWidth(null);
                } else {
                    scale = (double) largestDimension / (double) inImage.getHeight(null);
                    sizeDifference = inImage.getHeight(null) - largestDimension;
                    originalImageLargestDim = inImage.getHeight(null);
                }
                //create an image buffer to draw to
                BufferedImage outImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); //arbitrary init so code compiles
                Graphics2D g2d;
                AffineTransform tx;
                if (scale < 1.0d) //only scale if desired size is smaller than original
                {
                    int numSteps = sizeDifference / 100;
                    int stepSize = sizeDifference / numSteps;
                    int stepWeight = stepSize / 2;
                    int heavierStepSize = stepSize + stepWeight;
                    int lighterStepSize = stepSize - stepWeight;
                    int currentStepSize, centerStep;
                    double scaledW = inImage.getWidth(null);
                    double scaledH = inImage.getHeight(null);
                    if (numSteps % 2 == 1) //if there's an odd number of steps
                        centerStep = (int) Math.ceil((double) numSteps / 2d); //find the center step
                    else
                        centerStep = -1; //set it to -1 so it's ignored later
                    Integer intermediateSize = originalImageLargestDim,
                            previousIntermediateSize = originalImageLargestDim;
                    Integer calculatedDim;
                    for (Integer i = 0; i < numSteps; i++) {
                        if (i + 1 != centerStep) //if this isn't the center step
                        {
                            if (i == numSteps - 1) //if this is the last step
                            {
                                //fix the stepsize to account for decimal place errors previously
                                currentStepSize = previousIntermediateSize - largestDimension;
                            } else {
                                if (numSteps - i > numSteps / 2) //if we're in the first half of the reductions
                                    currentStepSize = heavierStepSize;
                                else
                                    currentStepSize = lighterStepSize;
                            }
                        } else //center step, use natural step size
                        {
                            currentStepSize = stepSize;
                        }
                        intermediateSize = previousIntermediateSize - currentStepSize;
                        scale = (double) intermediateSize / (double) previousIntermediateSize;
                        scaledW = (int) scaledW * scale;
                        scaledH = (int) scaledH * scale;
                        outImage = new BufferedImage((int) scaledW, (int) scaledH, BufferedImage.TYPE_INT_RGB);
                        g2d = outImage.createGraphics();
                        g2d.setBackground(Color.WHITE);
                        g2d.clearRect(0, 0, outImage.getWidth(), outImage.getHeight());
                        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                        tx = new AffineTransform();
                        tx.scale(scale, scale);
                        g2d.drawImage(inImage, tx, null);
                        g2d.dispose();
                        inImage = new ImageIcon(outImage).getImage();
                        previousIntermediateSize = intermediateSize;
                    }
                } else {
                    //just copy the original
                    outImage = new BufferedImage(inImage.getWidth(null), inImage.getHeight(null),
                            BufferedImage.TYPE_INT_RGB);
                    g2d = outImage.createGraphics();
                    g2d.setBackground(Color.WHITE);
                    g2d.clearRect(0, 0, outImage.getWidth(), outImage.getHeight());
                    tx = new AffineTransform();
                    tx.setToIdentity(); //use identity matrix so image is copied exactly
                    g2d.drawImage(inImage, tx, null);
                    g2d.dispose();
                }
                //JPEG-encode the image and write to file.
                OutputStream os = new FileOutputStream(outFilename);
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
                encoder.encode(outImage);
                os.close();
            }
        }
    } catch (Exception ex) {
        String errorMsg = "";
        errorMsg += "<br>Exception: " + ex.toString();
        errorMsg += "<br>Cause = " + ex.getCause();
        errorMsg += "<br>Stack Trace = ";
        StackTraceElement stackTrace[] = ex.getStackTrace();
        for (int traceLine = 0; traceLine < stackTrace.length; traceLine++) {
            errorMsg += "<br>" + stackTrace[traceLine];
        }
        return errorMsg;
    }
    return ""; //success
}

From source file:sernet.verinice.service.commands.LoadAttachmentFile.java

private void drawThumbnail(BufferedImage image, BufferedImage resizedImage) {
    Graphics2D g = resizedImage.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
    g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
    g.drawImage(image, 0, 0, resizedImage.getWidth(), resizedImage.getHeight(), null);
    g.dispose();// w  w  w .  j  ava2s .  com
}

From source file:com.sdk.connector.chart.FrequencyDomainRenderer.java

/**
 * Creates a new demo application./*w  ww .  j  a  v a 2s .c o m*/
 *
 * @param title  the frame title.
 */
public FrequencyDomainRenderer(String title, JPanel panel, String side, String type) {

    this.side = side;
    this.type = type;
    serie.setKey(side);

    dataset.addSeries(serie);
    JFreeChart chart = ChartFactory.createXYAreaChart(title,
            java.util.ResourceBundle.getBundle("com/sdk/connector/chart/Bundle").getString("frequency.xlabel"),
            java.util.ResourceBundle.getBundle("com/sdk/connector/chart/Bundle").getString("frequency.ylabel2"),
            dataset, PlotOrientation.VERTICAL, true, true, false);

    //        TextTitle t1 = new TextTitle( "Espectro de Frequncia Estimado (PSD)", new Font("SansSerif", Font.BOLD, 14)  );
    //        //TextTitle t2 = new TextTitle( "valores atualizados a cada potncia de 2", new Font("SansSerif", Font.PLAIN, 11)      );
    //        chart.addSubtitle(t1);
    chart.getRenderingHints().put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    chart.getRenderingHints().put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    chart.getRenderingHints().put(RenderingHints.KEY_ALPHA_INTERPOLATION,
            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    chart.getRenderingHints().put(RenderingHints.KEY_FRACTIONALMETRICS,
            RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    chart.getRenderingHints().put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    chart.getRenderingHints().put(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
    chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    chart.getRenderingHints().put(RenderingHints.KEY_TEXT_LCD_CONTRAST, 100);
    //chart.addSubtitle(t2);
    plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.WHITE);
    plot.setDomainGridlinePaint(Color.BLUE);
    plot.setRangeGridlinePaint(Color.CYAN);
    plot.getRenderer().setSeriesStroke(0, new BasicStroke(2.0f));
    plot.getRenderer().setSeriesStroke(1, new BasicStroke(2.0f));

    //plot.setRangePannable(true);
    plot.setForegroundAlpha(0.65f);

    //XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    renderer = plot.getRenderer();
    renderer.setSeriesOutlinePaint(0, Color.BLACK);
    if (side.startsWith(
            java.util.ResourceBundle.getBundle("com/sdk/connector/chart/Bundle").getString("side.left"))) {
        renderer.setSeriesPaint(0, Color.BLUE);
    } else {
        renderer.setSeriesPaint(0, Color.RED);
    }
    //        renderer.setSeriesLinesVisible(0, true);
    //        renderer.setSeriesShapesVisible(0, false);
    //        renderer.setSeriesLinesVisible(1, true);
    //        renderer.setSeriesShapesVisible(1, false);
    plot.setRenderer(renderer);
    plot.setBackgroundPaint(Color.WHITE);
    plot.setDomainGridlinePaint(Color.BLACK);
    plot.setRangeGridlinePaint(Color.BLACK);
    plot.setForegroundAlpha(0.5f);

    Color color1 = new Color(0, 0, 0, 24);
    Color color2 = new Color(255, 255, 255, 24);

    GradientPaint gp = new GradientPaint(0, 0, color1, 0, 0, color2);
    plot.setBackgroundPaint(gp);

    final ValueAxis domainAxis = plot.getDomainAxis();
    domainAxis.setTickMarkPaint(Color.black);
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.0);
    NumberAxis numDomainAxis = (NumberAxis) plot.getDomainAxis();
    numDomainAxis.setAutoRangeIncludesZero(true);
    //
    //        final NumberAxis rangeAxis = new LogarithmicAxis("Log(y)");
    //
    //        plot.setRangeAxis(rangeAxis);
    final ValueAxis rangeAxis = plot.getRangeAxis();
    rangeAxis.setTickMarkPaint(Color.black);

    numRangeAxis = (NumberAxis) plot.getRangeAxis();
    numRangeAxis.setAutoRangeIncludesZero(true);

    vlfTarget.setLabel("VLF");
    vlfTarget.setLabelFont(new Font("SansSerif", Font.ITALIC, 9));
    vlfTarget.setLabelAnchor(RectangleAnchor.CENTER);
    vlfTarget.setLabelTextAnchor(TextAnchor.CENTER);
    vlfTarget.setPaint(new Color(0, 100, 255, 128));
    // plot.addRangeMarker(target, Layer.BACKGROUND);
    plot.addDomainMarker(vlfTarget, Layer.BACKGROUND);

    lfTarget.setLabel("LF");
    lfTarget.setLabelFont(new Font("SansSerif", Font.ITALIC, 9));
    lfTarget.setLabelAnchor(RectangleAnchor.CENTER);
    lfTarget.setLabelTextAnchor(TextAnchor.CENTER);
    lfTarget.setPaint(new Color(255, 255, 0, 128));
    // plot.addRangeMarker(target, Layer.BACKGROUND);
    plot.addDomainMarker(lfTarget, Layer.BACKGROUND);

    hfTarget.setLabel("HF");
    hfTarget.setLabelFont(new Font("SansSerif", Font.ITALIC, 9));
    hfTarget.setLabelAnchor(RectangleAnchor.CENTER);
    hfTarget.setLabelTextAnchor(TextAnchor.CENTER);
    hfTarget.setPaint(new Color(255, 0, 255, 128));
    // plot.addRangeMarker(target, Layer.BACKGROUND);
    plot.addDomainMarker(hfTarget, Layer.BACKGROUND);
    plot.setNoDataMessage(
            java.util.ResourceBundle.getBundle("com/sdk/connector/chart/Bundle").getString("message.wait"));

    chartPanel = new ChartPanel(chart);

    panel.setLayout(new GridLayout(0, 1));
    panel.add(chartPanel);
    panel.repaint();
    panel.revalidate();

}

From source file:com.alibaba.simpleimage.ScaleTest.java

public PlanarImage doScaleBicubic(PlanarImage op) throws Exception {
    ParameterBlock pb = new ParameterBlock();
    pb.addSource(op);//from  w  ww.  ja  v a2  s.  c  o  m
    pb.add(scale);
    pb.add(scale);
    pb.add(0.0F);
    pb.add(0.0F);
    pb.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC));
    RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING,
            RenderingHints.VALUE_RENDER_QUALITY);
    op = JAI.create("scale", pb, qualityHints);

    return op;
}

From source file:org.apache.pdfbox.rendering.PageDrawer.java

/**
 * Sets high-quality rendering hints on the current Graphics2D.
 *//*from  w  w w  .  j a v a2s  . c o  m*/
private void setRenderingHints() {
    graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}

From source file:org.jcurl.core.swing.RockLocationDisplayBase.java

public void exportPng(File dst) throws IOException {
    final BufferedImage img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
    final Graphics2D g2 = (Graphics2D) img.getGraphics();
    {//  w w w  .  j av  a2  s .c  o m
        final Map hints = new HashMap();
        hints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        hints.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        hints.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
        hints.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        hints.put(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
        hints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.addRenderingHints(hints);
    }
    this.paintComponent(g2);
    g2.dispose();
    if (!dst.getName().endsWith(".png"))
        dst = new File(dst.getName() + ".png");
    ImageIO.write(img, "png", dst);
}

From source file:com.alibaba.simpleimage.ScaleTest.java

public PlanarImage doScaleBicubic2(PlanarImage op) throws Exception {
    ParameterBlock pb = new ParameterBlock();
    pb.addSource(op);// ww w  .  j  av a  2s  .  c om
    pb.add(scale);
    pb.add(scale);
    pb.add(0.0F);
    pb.add(0.0F);
    pb.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC_2));
    RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING,
            RenderingHints.VALUE_RENDER_QUALITY);
    op = JAI.create("scale", pb, qualityHints);

    return op;
}

From source file:com.piketec.jenkins.plugins.tpt.publisher.PieChart.java

/**
 * Render the pie chart with the given height
 * //from ww w  .  j av a  2 s.co  m
 * @param height
 *          The height of the resulting image
 * @return The pie chart rendered as an image
 */
public BufferedImage render(int height) {
    BufferedImage image = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    g2.scale(zoom, zoom);
    // fill background to white
    g2.setColor(Color.WHITE);
    g2.fill(new Rectangle(totalWidth, totalHeight));
    // prepare render hints
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2.setStroke(new BasicStroke(4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));

    // draw shadow image
    g2.drawImage(pieShadow.getImage(), 0, 0, pieShadow.getImageObserver());

    double start = 0;
    List<Arc2D> pies = new ArrayList<>();
    // pie segmente erzeugen und fuellen
    if (total == 0) {
        g2.setColor(BRIGHT_GRAY);
        g2.fillOval(centerX - radius, centerY - radius, 2 * radius, 2 * radius);
        g2.setColor(Color.WHITE);
        g2.drawOval(centerX - radius, centerY - radius, 2 * radius, 2 * radius);
    } else {
        for (Segment s : segments) {
            double portionDegrees = s.getPortion() / total;
            Arc2D pie = paintPieSegment(g2, start, portionDegrees, s.getColor());
            if (withSubSegments) {
                double smallRadius = radius * s.getSubSegmentRatio();
                paintPieSegment(g2, start, portionDegrees, smallRadius, s.getColor().darker());
            }
            start += portionDegrees;
            // portion degree jetzt noch als String (z.B. "17.3%" oder "20%" zusammenbauen)
            String p = String.format(Locale.ENGLISH, "%.1f", Math.rint(portionDegrees * 1000) / 10.0);
            p = removeSuffix(p, ".0"); // evtl. ".0" bei z.B. "25.0" abschneiden (-> "25")
            s.setPercent(p + "%");
            pies.add(pie);
        }
        // weissen Rahmen um die pie segmente zeichen
        g2.setColor(Color.WHITE);
        for (Arc2D pie : pies) {
            g2.draw(pie);
        }
    }
    // Legende zeichnen
    renderLegend(g2);
    // "xx%" Label direkt auf die pie segmente zeichen
    g2.setColor(Color.WHITE);
    float fontSize = 32f;
    g2.setFont(NORMALFONT.deriveFont(fontSize).deriveFont(Font.BOLD));
    start = 0;
    for (Segment s : segments) {
        if (s.getPortion() < 1E-6) {
            continue; // ignore segments with portions that are extremely small
        }
        double portionDegrees = s.getPortion() / total;
        double angle = start + portionDegrees / 2; // genau in der Mitte des Segments
        double xOffsetForCenteredTxt = 8 * s.getPercent().length(); // assume roughly 8px per char
        int x = (int) (centerX + 0.6 * radius * Math.sin(2 * Math.PI * angle) - xOffsetForCenteredTxt);
        int y = (int) (centerY - 0.6 * radius * Math.cos(2 * Math.PI * angle) + fontSize / 2);
        g2.drawString(s.getPercent(), x, y);
        start += portionDegrees;
    }
    return image;
}

From source file:ClipImage.java

public Graphics2D createDemoGraphics2D(Graphics g) {
    Graphics2D g2 = null;/*w  w w .  j a va  2s. c o  m*/

    if (offImg == null || offImg.getWidth() != w || offImg.getHeight() != h) {
        offImg = (BufferedImage) createImage(w, h);
        newBufferedImage = true;
    }

    if (offImg != null) {
        g2 = offImg.createGraphics();
        g2.setBackground(getBackground());
    }

    // .. set attributes ..
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    // .. clear canvas ..
    g2.clearRect(0, 0, w, h);

    return g2;
}