Example usage for java.awt Rectangle Rectangle

List of usage examples for java.awt Rectangle Rectangle

Introduction

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

Prototype

public Rectangle(int x, int y, int width, int height) 

Source Link

Document

Constructs a new Rectangle whose upper-left corner is specified as (x,y) and whose width and height are specified by the arguments of the same name.

Usage

From source file:cognitivej.vision.overlay.builder.ImageOverlayBuilder.java

@NotNull
private ImageOverlayBuilder outlineOCRWord(@NotNull OCRResult.Word word) {
    OverlayRectangleFilter overlayRectangleFilter = new OverlayRectangleFilter(word.boundingBoxAsAwtRectangle(),
            RectangleType.FULL, BorderWeight.THINNER, CognitiveJColourPalette.randomColour());
    TextOnRectangleFilter textOnRectangleFilter = new TextOnRectangleFilter(
            new Rectangle(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight()),
            word.boundingBoxAsAwtRectangle(), new Insets(0, 0, 0, 0), new Font("Noto Sans", Font.PLAIN, 12),
            CognitiveJColourPalette.TRANS_GRAY, RectangleTextPosition.BOTTOM_OF, word.text);
    bufferedImage = textOnRectangleFilter.applyFilter(overlayRectangleFilter.applyFilter(bufferedImage));
    return this;

}

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

private void processTextElement(Graphics2D g2, Element textElement) {

    int x = Integer.valueOf(textElement.getAttributeValue("X"));
    int y = Integer.valueOf(textElement.getAttributeValue("Y"));
    int width = Integer.valueOf(textElement.getAttributeValue("Width"));
    int height = Integer.valueOf(textElement.getAttributeValue("Height"));
    String alignment = textElement.getAttributeValue("TextAlignment");
    boolean multiline = Boolean.valueOf(textElement.getAttributeValue("Multiline").toLowerCase());
    boolean antiAlias = textElement.getAttributeValue("TextQuality").equalsIgnoreCase("antialias");

    Font font = parseFont(textElement.getAttributeValue("Font"));

    logger.info("Using font " + font);
    // now get the textim4java performance
    String text = textElement.getAttributeValue("Text");
    // if text matches pattern of %VARIABLE%{MODIFIER}
    logger.info("parsing token {}", text);
    Matcher matcher = pattern.matcher(text);
    int start = 0;
    while (matcher.find(start)) {
        // apply modification
        text = text.replace(matcher.group(), applyModifier(matcher.group()));
        start = matcher.end();// w w w  .  j a va 2s.  c o m
    }
    BufferedImage tmpImage;
    if (width > 0 && height > 0) {
        // create a transparent tmpImage
        tmpImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    } else {
        FontMetrics fm = g2.getFontMetrics(font);
        Rectangle outlineBounds = fm.getStringBounds(text, g2).getBounds();
        //         we need to create a transparent image to paint
        tmpImage = new BufferedImage(outlineBounds.width, outlineBounds.height, BufferedImage.TYPE_INT_ARGB);
    }
    Graphics2D g2d = tmpImage.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
    //        }
    g2d.setFont(font);
    Color textColor = new Color(Integer.valueOf(textElement.getAttributeValue("ForeColor")));
    g2d.setColor(textColor);
    Composite comp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .8f);
    g2d.setComposite(comp);
    drawString(g2d, text, new Rectangle(0, 0, width, height), Align.valueOf(alignment), 0, multiline);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
    tmpImage = processActions(textElement, tmpImage);

    ////        Graphics2D g2d = tmpImage.createGraphics();
    //        // set current font
    //        g2.setFont(font);
    ////        g2d.setComposite(AlphaComposite.Clear);
    ////        g2d.fillRect(0, 0, width, height);
    ////        g2d.setComposite(AlphaComposite.Src);
    //        // TODO: we have to parse it
    //        int strokeWidth = Integer.valueOf(textElement.getAttributeValue("StrokeWidth"));
    //        // the color of the outline
    //        if (strokeWidth > 0) {
    ////            Color strokeColor = new Color(Integer.valueOf(textElement.getAttributeValue("StrokeColor")));
    ////            AffineTransform affineTransform;
    ////            affineTransform = g2d.getTransform();
    ////            affineTransform.translate(width / 2 - (outlineBounds.width / 2), height / 2
    ////                    + (outlineBounds.height / 2));
    ////            g2d.transform(affineTransform);
    ////            // backup stroke width and color
    ////            Stroke originalStroke = g2d.getStroke();
    ////            Color originalColor = g2d.getColor();
    ////            g2d.setColor(strokeColor);
    ////            g2d.setStroke(new BasicStroke(strokeWidth));
    ////            g2d.draw(shape);
    ////            g2d.setClip(shape);
    ////            // restore stroke width and color
    ////            g2d.setStroke(originalStroke);
    ////            g2d.setColor(originalColor);
    //        }
    ////        // get the text color
    //        Color textColor = new Color(Integer.valueOf(textElement.getAttributeValue("ForeColor")));
    //        g2.setColor(textColor);
    ////        g2d.setBackground(Color.BLACK);
    ////        g2d.setStroke(new BasicStroke(2));
    ////        g2d.setColor(Color.WHITE);
    //        // draw the text
    //
    //        drawString(g2, text, new Rectangle(x, y, width, height), Align.valueOf(alignment), 0, multiline);
    //        g2.drawString(text, x, y);
    //        Rectangle rect = new Rectangle(x, y, width, height); // defines the desired size and position
    //        FontMetrics fm = g2.getFontMetrics();
    //        FontRenderContext frc = g2.getFontRenderContext();
    //        TextLayout tl = new TextLayout(text, g2.getFont(), frc);
    //        AffineTransform transform = new AffineTransform();
    //        transform.setToTranslation(rect.getX(), rect.getY());
    //        if (Boolean.valueOf(textElement.getAttributeValue("AutoSize").toLowerCase())) {
    //            double scaleY
    //                    = rect.getHeight() / (double) (tl.getOutline(null).getBounds().getMaxY()
    //                    - tl.getOutline(null).getBounds().getMinY());
    //            transform.scale(rect.getWidth() / (double) fm.stringWidth(text), scaleY);
    //        }
    //        Shape shape = tl.getOutline(transform);
    //        g2.setClip(shape);
    //        g2.fill(shape.getBounds());
    //        if (antiAlias) {
    // we need to restore antialias to none
    //            g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
    //        }
    //        g2.drawString(text, x, y);
    // alway resize
    //        BicubicScaleFilter scaleFilter = new BicubicScaleFilter(width, height);
    //        tmpImage = scaleFilter.filter(tmpImage, null);
    // draw the image to the source
    g2.drawImage(tmpImage, x, y, width, height, null);
    try {
        ScreenImage.writeImage(tmpImage, "/tmp/images/" + textElement.getAttributeValue("Name") + ".png");
    } catch (IOException ex) {

    }

}

From source file:fr.amap.commons.javafx.chart.ChartViewer.java

/**
 * A handler for the export to JPEG option in the context menu.
 *//*from  www . ja va 2  s .  co m*/
private void handleExportToJPEG() {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Export to JPEG");
    fileChooser.setSelectedExtensionFilter(new FileChooser.ExtensionFilter("JPEG", "jpg"));
    File file = fileChooser.showSaveDialog(stage);
    if (file != null) {
        try {
            CanvasPositionsAndSize canvasPositionAndSize = getCanvasPositionAndSize();

            BufferedImage image = new BufferedImage((int) canvasPositionAndSize.totalWidth,
                    (int) canvasPositionAndSize.totalHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();

            int index = 0;
            for (ChartCanvas canvas : chartCanvasList) {

                Rectangle2D rectangle2D = canvasPositionAndSize.positionsAndSizes.get(index);

                ((Drawable) canvas.chart).draw(g2, new Rectangle((int) rectangle2D.getX(),
                        (int) rectangle2D.getY(), (int) rectangle2D.getWidth(), (int) rectangle2D.getHeight()));
                index++;
            }

            try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
                ImageIO.write(image, "jpg", out);
            }

            /*ExportUtils.writeAsJPEG(chartCanvasList.get(0).chart, (int)chartCanvasList.get(0).getWidth(),
                (int)chartCanvasList.get(0).getHeight(), file);*/
        } catch (IOException ex) {
            // FIXME: show a dialog with the error
        }
    }
}

From source file:gdsc.core.ij.AlignImagesFFT.java

/**
 * Normalise the correlation matrix using the standard deviation of the region from the reference that is covered by
 * the target// ww  w  . ja  va 2  s.  com
 * 
 * @param subCorrMat
 * @param s
 * @param ss
 * @param targetIp
 */
private void normalise(FloatProcessor subCorrMat, double[] s, double[] ss, ImageProcessor targetIp) {
    int maxx = subCorrMat.getWidth();
    int maxy = subCorrMat.getHeight();
    Rectangle imageBounds = new Rectangle(0, 0, maxx, maxy); //refImageBounds;

    int NU = targetIp.getWidth();
    int NV = targetIp.getHeight();

    // Locate where the target image was inserted when padding
    int x = targetImageBounds.x; // (maxx - NU) / 2;
    int y = targetImageBounds.y; // (maxy - NV) / 2;

    //IJ.log(String.format("maxx=%d,  maxy=%d, NU=%d, NV=%d, x=%d, y=%d", maxx, maxy, NU, NV, x, y));

    // Calculate overlap:
    // Assume a full size target image relative to the reference and then compensate with the insert location
    int halfNU = maxx / 2 - x;
    int halfNV = maxy / 2 - y;

    // Normalise within the bounds of the largest image (i.e. only allow translation 
    // up to half of the longest edge from the reference or target).
    // The further the translation from the half-max translation the more likely there 
    // can be errors in the normalisation score due to floating point summation errors. 
    // This is observed mainly at the very last pixel overlap between images.
    // To see this set: 
    // union = imageBounds;
    // TODO - More analysis to determine under what conditions this occurs.
    Rectangle union = refImageBounds.union(targetImageBounds);

    // Normalise using the denominator
    float[] data = (float[]) subCorrMat.getPixels();
    float[] newData = new float[data.length];
    for (int yyy = union.y; yyy < union.y + union.height; yyy++) {
        int i = yyy * maxx + union.x;
        for (int xxx = union.x; xxx < union.x + union.width; xxx++, i++) {
            double sum = 0;
            double sumSquares = 0;

            int minU = xxx - halfNU - 1;
            int maxU = FastMath.min(minU + NU, maxx - 1);
            int minV = yyy - halfNV - 1;
            int maxV = FastMath.min(minV + NV, maxy - 1);

            // Compute sum from rolling sum using:
            // sum(u,v) = 
            // + s(u+N-1,v+N-1) 
            // - s(u-1,v+N-1)
            // - s(u+N-1,v-1)
            // + s(u-1,v-1)
            // Note: 
            // s(u,v) = 0 when either u,v < 0
            // s(u,v) = s(umax,v) when u>umax
            // s(u,v) = s(u,vmax) when v>vmax
            // s(u,v) = s(umax,vmax) when u>umax,v>vmax
            // Likewise for ss

            // + s(u+N-1,v+N-1) 
            int index = maxV * maxx + maxU;
            sum += s[index];
            sumSquares += ss[index];

            if (minU >= 0) {
                // - s(u-1,v+N-1)
                index = maxV * maxx + minU;
                sum -= s[index];
                sumSquares -= ss[index];
            }
            if (minV >= 0) {
                // - s(u+N-1,v-1)
                index = minV * maxx + maxU;
                sum -= s[index];
                sumSquares -= ss[index];

                if (minU >= 0) {
                    // + s(u-1,v-1)
                    index = minV * maxx + minU;
                    sum += s[index];
                    sumSquares += ss[index];
                }
            }

            // Reset to bounds to calculate the number of pixels
            if (minU < 0)
                minU = 0;
            if (minV < 0)
                minV = 0;

            Rectangle regionBounds = new Rectangle(xxx - halfNU, yyy - halfNV, NU, NV);
            Rectangle r = imageBounds.intersection(regionBounds);

            //int n = (maxU - minU + 1) * (maxV - minV + 1);
            int n = r.width * r.height;

            if (n < 1)
                continue;

            // Get the sum of squared differences
            double residuals = sumSquares - sum * sum / n;

            //            // Check using the original data
            //            double sx = 0;
            //            double ssx = 0;
            //            int nn = 0;
            //            for (int yy = yyy - halfNV; yy < yyy - halfNV + NV; yy++)
            //               for (int xx = xxx - halfNU; xx < xxx - halfNU + NU; xx++)
            //               {
            //                  if (xx >= 0 && xx < maxx && yy >= 0 && yy < maxy)
            //                  {
            //                     float value = normalisedRefIp.getf(xx, yy);
            //                     sx += value;
            //                     ssx += value * value;
            //                     nn++;
            //                  }
            //               }
            //            gdsc.fitting.utils.DoubleEquality eq = new gdsc.fitting.utils.DoubleEquality(8, 1e-16);
            //            if (n != nn)
            //            {
            //               System.out.printf("Wrong @ %d,%d %d <> %d\n", xxx, yyy, n, nn);
            //               residuals = ssx - sx * sx / nn;
            //            }
            //            else if (!eq.almostEqualComplement(sx, sum) || !eq.almostEqualComplement(ssx, sumSquares))
            //            {
            //               System.out.printf("Wrong @ %d,%d %g <> %g : %g <> %g\n", xxx, yyy, sx, sum, ssx, sumSquares);
            //               residuals = ssx - sx * sx / nn;
            //            }

            double normalisation = (residuals > 0) ? Math.sqrt(residuals) : 0;

            if (normalisation > 0) {
                newData[i] = (float) (data[i] / normalisation);
                // Watch out for normalisation errors which cause problems when displaying the image data.
                if (newData[i] < -1.1f)
                    newData[i] = -1.1f;
                if (newData[i] > 1.1f)
                    newData[i] = 1.1f;
            }
        }
    }
    subCorrMat.setPixels(newData);
}