Example usage for java.awt RenderingHints VALUE_ANTIALIAS_ON

List of usage examples for java.awt RenderingHints VALUE_ANTIALIAS_ON

Introduction

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

Prototype

Object VALUE_ANTIALIAS_ON

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

Click Source Link

Document

Antialiasing hint value -- rendering is done with antialiasing.

Usage

From source file:net.fenyo.gnetwatch.GUI.BasicComponent.java

/**
 * Creates a backing store.//from   w ww. j  av a2  s. com
 * @param none.
 * @return void.
 */
private void newBackingElts() {
    dimension = getSize();
    backing_store = createImage(dimension.width, dimension.height);
    backing_g = (Graphics2D) backing_store.getGraphics();
    backing_g.setBackground(Color.BLACK);
    backing_g.setColor(Color.WHITE);
    backing_g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    backing_g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}

From source file:com.github.lucapino.sheetmaker.renderer.JavaTemplateRenderer.java

private ImagePanel drawTemplate(Element drawImageTemplateElement) throws Exception {
    // OutputImageSettings
    logger.info("reading ImageDrawTemlate attributes...");
    Element outputImageSettingsElement = drawImageTemplateElement.getChild(OUTPUT_IMAGE_SETTINGS);
    String colorDepth = outputImageSettingsElement.getAttributeValue("ColorDepth");
    String imageForat = outputImageSettingsElement.getAttributeValue("ImageFormat");
    String jpegCompressionLevel = outputImageSettingsElement.getAttributeValue("JpegCompressionLevel");
    String dpi = outputImageSettingsElement.getAttributeValue("Dpi");
    logger.info("Reading Canvas attributes...");
    // Canvas/*from   w w  w.  ja  v  a  2  s . c o m*/
    Element canvasElement = drawImageTemplateElement.getChild(CANVAS);
    String autoSize = canvasElement.getAttributeValue("AutoSize");
    String centerElements = canvasElement.getAttributeValue("CenterElements");
    int width = Integer.valueOf(canvasElement.getAttributeValue("Width"));
    int height = Integer.valueOf(canvasElement.getAttributeValue("Height"));
    String fill = canvasElement.getAttributeValue("Fill");

    // create image of specified dimensions
    logger.info("Creating working image...");
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = image.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    // Elements
    logger.info("Processing elements...");
    Element elementsElement = drawImageTemplateElement.getChild("Elements");
    for (Element element : elementsElement.getChildren()) {
        switch (element.getName()) {
        case "ImageElement":
            processImageElement(g2, element);
            break;
        case "TextElement":
            processTextElement(g2, element);
            break;
        }
    }

    return new ImagePanel(image);
}

From source file:org.esa.snap.graphbuilder.rcp.dialogs.support.GraphPanel.java

/**
 * Paints the panel component//from  ww w.ja  va 2  s  .c  o  m
 *
 * @param g The Graphics
 */
@Override
protected void paintComponent(java.awt.Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    DrawGraph(g2, graphEx.GetGraphNodes());
}

From source file:com.fluidops.iwb.deepzoom.ImageLoader.java

private void generateIDCard(URI uri, Map<URI, Set<Value>> facets, String url, File file) {
    int width = 200;
    int height = 200;

    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    Graphics2D ig2 = bi.createGraphics();
    ig2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    ig2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    /* Special ID card handling for certain entity types */

    /*  TODO: special images based on type
    if(facets.containsKey(RDF.TYPE)) {/*from   ww  w.j  av a2  s  . com*/
    Set<Value> facet = facets.get(RDF.TYPE);
            
    for(Value v : facet)
    {
        if(v.equals(Vocabulary.DCAT_DATASET))
        {
            
            Image img = null;
            try
            {
                img = ImageIO.read( new File( "webapps/ROOT/images/rdf.jpg" ) );
            }
            catch (MalformedURLException e)
            {
                logger.error(e.getMessage(), e);
            }
            catch (IOException e)
            {
                logger.error("Could not get image");
            }
            
            ig2.drawImage( img, 0, 0, null );        
            break;
        }
    }
    } */

    String label = EndpointImpl.api().getDataManager().getLabel(uri);
    Font font = new Font(Font.SANS_SERIF, Font.BOLD, 20);
    ig2.setFont(font);

    FontMetrics fontMetrics = ig2.getFontMetrics();
    int labelwidth = fontMetrics.stringWidth(label);
    if (labelwidth >= width) {
        int fontsize = 20 * width / labelwidth;
        font = new Font(Font.SANS_SERIF, Font.BOLD, fontsize);
        ig2.setFont(font);
        fontMetrics = ig2.getFontMetrics();
    }

    int x = (width - fontMetrics.stringWidth(label)) / 2;
    int y = (fontMetrics.getAscent() + (height - (fontMetrics.getAscent() + fontMetrics.getDescent())) / 2);

    ig2.setPaint(Color.black);

    ig2.drawString(label, x, y);

    BufferedOutputStream out;
    try {
        out = new BufferedOutputStream(new FileOutputStream(file));
        ImageIO.write(bi, "PNG", out);
        out.flush();
        out.close();

    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:fr.fg.server.core.TerritoryManager.java

private static BufferedImage createTerritoryMap(int idSector) {
    List<Area> areas = new ArrayList<Area>(DataAccess.getAreasBySector(idSector));

    float[][] points = new float[areas.size()][2];
    int[] dominatingAllies = new int[areas.size()];
    int i = 0;//from  w  w w .j a v  a  2 s. c om
    for (Area area : areas) {
        points[i][0] = area.getX() * MAP_SCALE;
        points[i][1] = area.getY() * MAP_SCALE;
        dominatingAllies[i] = area.getIdDominatingAlly();
        i++;
    }

    Hull hull = new Hull(points);
    MPolygon hullPolygon = hull.getRegion();
    float[][] newPoints = new float[points.length + hullPolygon.count()][2];
    System.arraycopy(points, 0, newPoints, 0, points.length);

    float[][] hullCoords = hullPolygon.getCoords();

    for (i = 0; i < hullPolygon.count(); i++) {
        double angle = Math.atan2(hullCoords[i][1], hullCoords[i][0]);
        double length = Math.sqrt(hullCoords[i][0] * hullCoords[i][0] + hullCoords[i][1] * hullCoords[i][1]);

        newPoints[i + points.length][0] = (float) (Math.cos(angle) * (length + 8 * MAP_SCALE));
        newPoints[i + points.length][1] = (float) (Math.sin(angle) * (length + 8 * MAP_SCALE));
    }

    points = newPoints;

    Voronoi voronoi = new Voronoi(points);
    Delaunay delaunay = new Delaunay(points);

    // Dcoupage en rgions
    MPolygon[] regions = voronoi.getRegions();

    // Calcule le rayon de la galaxie
    int radius = 0;

    for (Area area : areas) {
        radius = Math.max(radius, area.getX() * area.getX() + area.getY() * area.getY());
    }

    radius = (int) Math.floor(Math.sqrt(radius) * MAP_SCALE) + 10 * MAP_SCALE;
    int diameter = 2 * radius + 1;

    // Construit l'image avec les quadrants
    BufferedImage territoriesImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g = (Graphics2D) territoriesImage.getGraphics();

    // Affecte une couleur  chaque alliance
    HashMap<Integer, Color> alliesColors = new HashMap<Integer, Color>();

    for (Area area : areas) {
        int idDominatingAlly = area.getIdDominatingAlly();
        if (idDominatingAlly != 0)
            alliesColors.put(idDominatingAlly,
                    Ally.TERRITORY_COLORS[DataAccess.getAllyById(idDominatingAlly).getColor()]);
    }

    Polygon[] polygons = new Polygon[regions.length];
    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] != 0) {
            polygons[i] = createPolygon(regions[i].getCoords(), radius + 1, 3);
        }
    }

    // Dessine tous les secteurs
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0)
            continue;

        Polygon p = polygons[i];

        // Dessine le polygone
        g.setColor(alliesColors.get(dominatingAllies[i]));
        g.fill(p);

        // Rempli les espaces entre les polygones adjacents qui
        // correspondent au territoire d'une mme alliance
        int[] linkedRegions = delaunay.getLinked(i);
        for (int j = 0; j < linkedRegions.length; j++) {
            int linkedRegion = linkedRegions[j];

            if (linkedRegion >= areas.size())
                continue;

            if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                if (linkedRegion <= i)
                    continue;

                float[][] coords1 = regions[i].getCoords();
                float[][] coords2 = regions[linkedRegion].getCoords();

                int junctionIndex = 0;
                int[][] junctions = new int[2][2];

                search: for (int k = 0; k < coords1.length; k++) {
                    for (int l = 0; l < coords2.length; l++) {
                        if (coords1[k][0] == coords2[l][0] && coords1[k][1] == coords2[l][1]) {
                            junctions[junctionIndex][0] = k;
                            junctions[junctionIndex][1] = l;

                            junctionIndex++;

                            if (junctionIndex == 2) {
                                int[] xpts = new int[] { polygons[i].xpoints[junctions[0][0]],
                                        polygons[linkedRegion].xpoints[junctions[0][1]],
                                        polygons[linkedRegion].xpoints[junctions[1][1]],
                                        polygons[i].xpoints[junctions[1][0]], };
                                int[] ypts = new int[] { polygons[i].ypoints[junctions[0][0]],
                                        polygons[linkedRegion].ypoints[junctions[0][1]],
                                        polygons[linkedRegion].ypoints[junctions[1][1]],
                                        polygons[i].ypoints[junctions[1][0]], };

                                Polygon border = new Polygon(xpts, ypts, 4);
                                g.setStroke(new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
                                g.fill(border);
                                g.draw(border);
                                break search;
                            }
                            break;
                        }
                    }
                }
            }
        }
    }

    // Dessine des lignes de contours des territoires
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0)
            continue;

        g.setStroke(new BasicStroke(1.5f));
        g.setColor(alliesColors.get(dominatingAllies[i]).brighter().brighter());

        float[][] coords1 = regions[i].getCoords();

        lines: for (int j = 0; j < coords1.length; j++) {
            int[] linkedRegions = delaunay.getLinked(i);
            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size())
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                    float[][] coords2 = regions[linkedRegion].getCoords();

                    for (int m = 0; m < coords2.length; m++) {
                        if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1]
                                && ((coords1[(j + 1) % coords1.length][0] == coords2[(m + 1)
                                        % coords2.length][0]
                                        && coords1[(j + 1) % coords1.length][1] == coords2[(m + 1)
                                                % coords2.length][1])
                                        || (coords1[(j + 1)
                                                % coords1.length][0] == coords2[(m - 1 + coords2.length)
                                                        % coords2.length][0]
                                                && coords1[(j + 1)
                                                        % coords1.length][1] == coords2[(m - 1 + coords2.length)
                                                                % coords2.length][1]))) {
                            continue lines;
                        }
                    }
                }
            }

            g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]),
                    Math.round(polygons[i].xpoints[(j + 1) % coords1.length]),
                    Math.round(polygons[i].ypoints[(j + 1) % coords1.length]));
        }

        for (int j = 0; j < coords1.length; j++) {
            int neighbours = 0;
            int lastNeighbourRegion = -1;
            int neighbourCoordsIndex = -1;

            int[] linkedRegions = delaunay.getLinked(i);
            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size())
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                    float[][] coords2 = regions[linkedRegion].getCoords();

                    for (int m = 0; m < coords2.length; m++) {
                        if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1]) {
                            neighbours++;
                            lastNeighbourRegion = linkedRegion;
                            neighbourCoordsIndex = m;
                            break;
                        }
                    }
                }
            }

            if (neighbours == 1) {
                g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]),
                        Math.round(polygons[lastNeighbourRegion].xpoints[neighbourCoordsIndex]),
                        Math.round(polygons[lastNeighbourRegion].ypoints[neighbourCoordsIndex]));
            }
        }
    }

    BufferedImage finalImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB);

    g = (Graphics2D) finalImage.getGraphics();

    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .15f));
    g.drawImage(territoriesImage, 0, 0, null);
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .5f));

    // Charge la police pour afficher le nom des alliances
    try {
        Font textFont = Font.createFont(Font.TRUETYPE_FONT,
                Action.class.getClassLoader().getResourceAsStream("fr/fg/server/resources/TinDog.ttf"));
        textFont = textFont.deriveFont(12f).deriveFont(Font.BOLD);
        g.setFont(textFont);
    } catch (Exception e) {
        LoggingSystem.getServerLogger().warn("Could not load quadrant map font.", e);
    }
    FontMetrics fm = g.getFontMetrics();

    ArrayList<Integer> closedRegions = new ArrayList<Integer>();

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0 || closedRegions.contains(i))
            continue;

        ArrayList<Integer> allyRegions = new ArrayList<Integer>();
        ArrayList<Integer> openRegions = new ArrayList<Integer>();

        openRegions.add(i);

        while (openRegions.size() > 0) {
            int currentRegion = openRegions.remove(0);
            allyRegions.add(currentRegion);
            closedRegions.add(currentRegion);

            int[] linkedRegions = delaunay.getLinked(currentRegion);

            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size() || openRegions.contains(linkedRegion)
                        || allyRegions.contains(linkedRegion))
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion])
                    openRegions.add(linkedRegion);
            }
        }

        Area area = areas.get(i);
        long xsum = 0;
        long ysum = 0;

        for (int k = 0; k < allyRegions.size(); k++) {
            int allyRegion = allyRegions.get(k);
            area = areas.get(allyRegion);

            xsum += area.getX();
            ysum += area.getY();
        }

        int x = (int) (xsum / allyRegions.size()) * MAP_SCALE + radius + 1;
        int y = (int) (-ysum / allyRegions.size()) * MAP_SCALE + radius + 1;
        ;

        Point point = new Point(x, y);
        boolean validLocation = false;
        for (int k = 0; k < allyRegions.size(); k++) {
            int allyRegion = allyRegions.get(k);

            if (polygons[allyRegion].contains(point)) {
                validLocation = true;
                break;
            }
        }

        if (validLocation) {
            if (allyRegions.size() == 1)
                y -= 14;
        } else {
            int xmid = (int) (xsum / allyRegions.size());
            int ymid = (int) (ysum / allyRegions.size());

            area = areas.get(i);
            int dx = area.getX() - xmid;
            int dy = area.getY() - ymid;
            int distance = dx * dx + dy * dy;

            int nearestAreaIndex = i;
            int nearestDistance = distance;

            for (int k = 0; k < allyRegions.size(); k++) {
                int allyRegion = allyRegions.get(k);

                area = areas.get(allyRegion);
                dx = area.getX() - xmid;
                dy = area.getY() - ymid;
                distance = dx * dx + dy * dy;

                if (distance < nearestDistance) {
                    nearestAreaIndex = allyRegion;
                    nearestDistance = distance;
                }
            }

            area = areas.get(nearestAreaIndex);
            x = area.getX() * MAP_SCALE + radius + 1;
            y = -area.getY() * MAP_SCALE + radius - 13;
        }

        // Dessine le tag de l'alliance
        String allyTag = "[ " + DataAccess.getAllyById(dominatingAllies[i]).getTag() + " ]";
        g.setColor(Color.BLACK);
        g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2 + 1, y);
        g.setColor(alliesColors.get(dominatingAllies[i]));
        g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2, y);
    }

    return finalImage;
}

From source file:VASSAL.counters.Labeler.java

public static void drawLabel(Graphics g, String text, int x, int y, Font f, int hAlign, int vAlign,
        Color fgColor, Color bgColor, Color borderColor) {
    g.setFont(f);//from ww w  .ja  va 2s .c  om
    final int width = g.getFontMetrics().stringWidth(text + "  ");
    final int height = g.getFontMetrics().getHeight();
    int x0 = x;
    int y0 = y;
    switch (hAlign) {
    case CENTER:
        x0 = x - width / 2;
        break;
    case LEFT:
        x0 = x - width;
        break;
    }
    switch (vAlign) {
    case CENTER:
        y0 = y - height / 2;
        break;
    case BOTTOM:
        y0 = y - height;
        break;
    }
    if (bgColor != null) {
        g.setColor(bgColor);
        g.fillRect(x0, y0, width, height);
    }
    if (borderColor != null) {
        g.setColor(borderColor);
        g.drawRect(x0, y0, width, height);
    }
    g.setColor(fgColor);
    ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.drawString(" " + text + " ", x0, y0 + g.getFontMetrics().getHeight() - g.getFontMetrics().getDescent());
}

From source file:ch.entwine.weblounge.preview.jai.JAIPreviewGenerator.java

/**
 * Resizes the given image to what is defined by the image style and writes
 * the result to the output stream./*w  w w . j av  a2s  .  c  o  m*/
 * 
 * @param is
 *          the input stream
 * @param os
 *          the output stream
 * @param format
 *          the image format
 * @param style
 *          the style
 * @throws IllegalArgumentException
 *           if the image is in an unsupported format
 * @throws IllegalArgumentException
 *           if the input stream is empty
 * @throws IOException
 *           if reading from or writing to the stream fails
 * @throws OutOfMemoryError
 *           if the image is too large to be processed in memory
 */
private void style(InputStream is, OutputStream os, String format, ImageStyle style)
        throws IllegalArgumentException, IOException, OutOfMemoryError {

    // Does the input stream contain any data?
    if (is.available() == 0)
        throw new IllegalArgumentException("Empty input stream was passed to image styling");

    // Do we need to do any work at all?
    if (style == null || ImageScalingMode.None.equals(style.getScalingMode())) {
        logger.trace("No scaling needed, performing a noop stream copy");
        IOUtils.copy(is, os);
        return;
    }

    SeekableStream seekableInputStream = null;
    RenderedOp image = null;
    try {
        // Load the image from the given input stream
        seekableInputStream = new FileCacheSeekableStream(is);
        image = JAI.create("stream", seekableInputStream);
        if (image == null)
            throw new IOException("Error reading image from input stream");

        // Get the original image size
        int imageWidth = image.getWidth();
        int imageHeight = image.getHeight();

        // Resizing
        float scale = ImageStyleUtils.getScale(imageWidth, imageHeight, style);

        RenderingHints scaleHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        scaleHints.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        scaleHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        scaleHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

        int scaledWidth = Math.round(scale * image.getWidth());
        int scaledHeight = Math.round(scale * image.getHeight());
        int cropX = 0;
        int cropY = 0;

        // If either one of scaledWidth or scaledHeight is < 1.0, then
        // the scale needs to be adapted to scale to 1.0 exactly and accomplish
        // the rest by cropping.

        if (scaledWidth < 1.0f) {
            scale = 1.0f / imageWidth;
            scaledWidth = 1;
            cropY = imageHeight - scaledHeight;
            scaledHeight = Math.round(imageHeight * scale);
        } else if (scaledHeight < 1.0f) {
            scale = 1.0f / imageHeight;
            scaledHeight = 1;
            cropX = imageWidth - scaledWidth;
            scaledWidth = Math.round(imageWidth * scale);
        }

        if (scale > 1.0) {
            ParameterBlock scaleParams = new ParameterBlock();
            scaleParams.addSource(image);
            scaleParams.add(scale).add(scale).add(0.0f).add(0.0f);
            scaleParams.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC_2));
            image = JAI.create("scale", scaleParams, scaleHints);
        } else if (scale < 1.0) {
            ParameterBlock subsampleAverageParams = new ParameterBlock();
            subsampleAverageParams.addSource(image);
            subsampleAverageParams.add(Double.valueOf(scale));
            subsampleAverageParams.add(Double.valueOf(scale));
            image = JAI.create("subsampleaverage", subsampleAverageParams, scaleHints);
        }

        // Cropping
        cropX = (int) Math.max(cropX,
                (float) Math.ceil(ImageStyleUtils.getCropX(scaledWidth, scaledHeight, style)));
        cropY = (int) Math.max(cropY,
                (float) Math.ceil(ImageStyleUtils.getCropY(scaledWidth, scaledHeight, style)));

        if ((cropX > 0 && Math.floor(cropX / 2.0f) > 0) || (cropY > 0 && Math.floor(cropY / 2.0f) > 0)) {

            ParameterBlock cropTopLeftParams = new ParameterBlock();
            cropTopLeftParams.addSource(image);
            cropTopLeftParams.add(cropX > 0 ? ((float) Math.floor(cropX / 2.0f)) : 0.0f);
            cropTopLeftParams.add(cropY > 0 ? ((float) Math.floor(cropY / 2.0f)) : 0.0f);
            cropTopLeftParams.add(scaledWidth - Math.max(cropX, 0.0f)); // width
            cropTopLeftParams.add(scaledHeight - Math.max(cropY, 0.0f)); // height

            RenderingHints croppingHints = new RenderingHints(JAI.KEY_BORDER_EXTENDER,
                    BorderExtender.createInstance(BorderExtender.BORDER_COPY));

            image = JAI.create("crop", cropTopLeftParams, croppingHints);
        }

        // Write resized/cropped image encoded as JPEG to the output stream
        ParameterBlock encodeParams = new ParameterBlock();
        encodeParams.addSource(image);
        encodeParams.add(os);
        encodeParams.add("jpeg");
        JAI.create("encode", encodeParams);

    } catch (Throwable t) {
        if (t.getClass().getName().contains("ImageFormat")) {
            throw new IllegalArgumentException(t.getMessage());
        }
    } finally {
        IOUtils.closeQuietly(seekableInputStream);
        if (image != null)
            image.dispose();
    }
}

From source file:net.sf.maltcms.common.charts.api.overlay.SelectionOverlay.java

/**
 *
 * @param g2//from   w w  w  . j  av a2s  .c  om
 * @param chartPanel
 */
@Override
public void paintOverlay(Graphics2D g2, ChartPanel chartPanel) {
    if (chartPanel.getChart().getAntiAlias()) {
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    }
    boolean isXYPlot = true;
    if (chartPanel.getChart().getPlot() instanceof XYPlot) {
        isXYPlot = true;
    } else if (chartPanel.getChart().getPlot() instanceof CategoryPlot) {
        isXYPlot = false;
    } else {
        throw new IllegalArgumentException("Can only handle XYPlot and CategoryPlot!");
    }
    if (isVisible()) {
        for (ISelection selection : mouseClickSelection) {
            if (selection.isVisible()) {
                Shape selectedEntity = null;
                if (isXYPlot) {
                    selectedEntity = chartPanel.getChart().getXYPlot().getRenderer()
                            .getItemShape(selection.getSeriesIndex(), selection.getItemIndex());
                } else {
                    selectedEntity = chartPanel.getChart().getCategoryPlot().getRenderer()
                            .getItemShape(selection.getSeriesIndex(), selection.getItemIndex());
                }
                if (selectedEntity == null) {
                    selectedEntity = generate(selection.getDataset(), selection.getSeriesIndex(),
                            selection.getItemIndex());
                }
                updateCrosshairs(selection.getDataset(), selection.getSeriesIndex(), selection.getItemIndex());
                Shape transformed = toView(selectedEntity, chartPanel, selection.getDataset(),
                        selection.getSeriesIndex(), selection.getItemIndex());
                drawEntity(transformed, g2, selectionFillColor, chartPanel, false);
            }
        }
        if (this.drawFlashSelection) {
            for (ISelection selection : flashSelection) {
                Shape selectedEntity = null;
                if (isXYPlot) {
                    selectedEntity = chartPanel.getChart().getXYPlot().getRenderer()
                            .getItemShape(selection.getSeriesIndex(), selection.getItemIndex());
                } else {
                    selectedEntity = chartPanel.getChart().getCategoryPlot().getRenderer()
                            .getItemShape(selection.getSeriesIndex(), selection.getItemIndex());
                }
                if (selectedEntity == null) {
                    selectedEntity = generate(selection.getDataset(), selection.getSeriesIndex(),
                            selection.getItemIndex());
                }
                Shape transformed = toView(selectedEntity, chartPanel, selection.getDataset(),
                        selection.getSeriesIndex(), selection.getItemIndex());
                drawEntity(transformed, g2, selectionFillColor.darker(), chartPanel, true);
            }
        }
        if (this.mouseHoverSelection != null && this.mouseHoverSelection.isVisible()) {
            Shape entity = null;
            if (isXYPlot) {
                entity = chartPanel.getChart().getXYPlot().getRenderer()
                        .getItemShape(mouseHoverSelection.getSeriesIndex(), mouseHoverSelection.getItemIndex());
            } else {
                entity = chartPanel.getChart().getCategoryPlot().getRenderer()
                        .getItemShape(mouseHoverSelection.getSeriesIndex(), mouseHoverSelection.getItemIndex());
            }
            if (entity == null) {
                entity = generate(mouseHoverSelection.getDataset(), mouseHoverSelection.getSeriesIndex(),
                        mouseHoverSelection.getItemIndex());
            }
            Shape transformed = toView(entity, chartPanel, mouseHoverSelection.getDataset(),
                    mouseHoverSelection.getSeriesIndex(), mouseHoverSelection.getItemIndex());
            drawEntity(transformed, g2, hoverFillColor, chartPanel, true);
        }
    }
    if (isXYPlot) {
        crosshairOverlay.paintOverlay(g2, chartPanel);
    }
}

From source file:org.forumj.web.servlet.post.SetAvatar.java

private BufferedImage renderImage(ImageSize destSize, int imgType, Image image) {
    BufferedImage thumbsImage = new BufferedImage(destSize.getWidth(), destSize.getHeight(), imgType);
    Graphics2D graphics2D = thumbsImage.createGraphics();
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    graphics2D.drawImage(image, 0, 0, destSize.getWidth(), destSize.getHeight(), null);
    return thumbsImage;
}

From source file:org.apache.fop.render.bitmap.AbstractBitmapDocumentHandler.java

/** {@inheritDoc} */
public IFPainter startPageContent() throws IFException {
    int bitmapWidth;
    int bitmapHeight;
    double scale;
    Point2D offset = null;//from  w ww .j  a  va 2 s.  co  m
    if (targetBitmapSize != null) {
        //Fit the generated page proportionally into the given rectangle (in pixels)
        double scale2w = 1000 * targetBitmapSize.width / this.currentPageDimensions.getWidth();
        double scale2h = 1000 * targetBitmapSize.height / this.currentPageDimensions.getHeight();
        bitmapWidth = targetBitmapSize.width;
        bitmapHeight = targetBitmapSize.height;

        //Centering the page in the given bitmap
        offset = new Point2D.Double();
        if (scale2w < scale2h) {
            scale = scale2w;
            double h = this.currentPageDimensions.height * scale / 1000;
            offset.setLocation(0, (bitmapHeight - h) / 2.0);
        } else {
            scale = scale2h;
            double w = this.currentPageDimensions.width * scale / 1000;
            offset.setLocation((bitmapWidth - w) / 2.0, 0);
        }
    } else {
        //Normal case: just scale according to the target resolution
        scale = scaleFactor * getUserAgent().getTargetResolution()
                / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION;
        bitmapWidth = (int) ((this.currentPageDimensions.width * scale / 1000f) + 0.5f);
        bitmapHeight = (int) ((this.currentPageDimensions.height * scale / 1000f) + 0.5f);
    }

    //Set up bitmap to paint on
    this.currentImage = createBufferedImage(bitmapWidth, bitmapHeight);
    Graphics2D graphics2D = this.currentImage.createGraphics();

    // draw page background
    if (!getSettings().hasTransparentPageBackground()) {
        graphics2D.setBackground(getSettings().getPageBackgroundColor());
        graphics2D.setPaint(getSettings().getPageBackgroundColor());
        graphics2D.fillRect(0, 0, bitmapWidth, bitmapHeight);
    }

    //Set rendering hints
    graphics2D.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
            RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    if (getSettings().isAntiAliasingEnabled() && this.currentImage.getColorModel().getPixelSize() > 1) {
        graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    } else {
        graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
        graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
    }
    if (getSettings().isQualityRenderingEnabled()) {
        graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    } else {
        graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
    }
    graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);

    //Set up initial coordinate system for the page
    if (offset != null) {
        graphics2D.translate(offset.getX(), offset.getY());
    }
    graphics2D.scale(scale / 1000f, scale / 1000f);

    return new Java2DPainter(graphics2D, getContext(), getFontInfo());
}