Example usage for java.awt.geom AffineTransform getRotateInstance

List of usage examples for java.awt.geom AffineTransform getRotateInstance

Introduction

In this page you can find the example usage for java.awt.geom AffineTransform getRotateInstance.

Prototype

public static AffineTransform getRotateInstance(double theta, double anchorx, double anchory) 

Source Link

Document

Returns a transform that rotates coordinates around an anchor point.

Usage

From source file:net.sf.mcf2pdf.mcfelements.util.ImageUtil.java

/**
 * Rotates the given buffered image by the given angle, and returns a newly
 * created image, containing the rotated image.
 *
 * @param img Image to rotate.//from  w  w  w . j a  va2 s.  c o m
 * @param angle Angle, in radians, by which to rotate the image.
 * @param drawOffset Receives the offset which is required to draw the image,
 * relative to the original (0,0) corner, so that the center of the image is
 * still on the same position.
 *
 * @return A newly created image containing the rotated image.
 */
public static BufferedImage rotateImage(BufferedImage img, float angle, Point drawOffset) {
    int w = img.getWidth();
    int h = img.getHeight();

    AffineTransform tf = AffineTransform.getRotateInstance(angle, w / 2.0, h / 2.0);

    // get coordinates for all corners to determine real image size
    Point2D[] ptSrc = new Point2D[4];
    ptSrc[0] = new Point(0, 0);
    ptSrc[1] = new Point(w, 0);
    ptSrc[2] = new Point(w, h);
    ptSrc[3] = new Point(0, h);

    Point2D[] ptTgt = new Point2D[4];
    tf.transform(ptSrc, 0, ptTgt, 0, ptSrc.length);

    Rectangle rc = new Rectangle(0, 0, w, h);

    for (Point2D p : ptTgt) {
        if (p.getX() < rc.x) {
            rc.width += rc.x - p.getX();
            rc.x = (int) p.getX();
        }
        if (p.getY() < rc.y) {
            rc.height += rc.y - p.getY();
            rc.y = (int) p.getY();
        }
        if (p.getX() > rc.x + rc.width)
            rc.width = (int) (p.getX() - rc.x);
        if (p.getY() > rc.y + rc.height)
            rc.height = (int) (p.getY() - rc.y);
    }

    BufferedImage imgTgt = new BufferedImage(rc.width, rc.height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = imgTgt.createGraphics();

    // create a NEW rotation transformation around new center
    tf = AffineTransform.getRotateInstance(angle, rc.getWidth() / 2, rc.getHeight() / 2);
    g2d.setTransform(tf);
    g2d.drawImage(img, -rc.x, -rc.y, null);
    g2d.dispose();

    drawOffset.x += rc.x;
    drawOffset.y += rc.y;

    return imgTgt;
}

From source file:com.xuggle.xuggler.UtilsTest.java

@SuppressWarnings("deprecation")
@Test//from   ww  w . ja  va 2s  . co  m
public void testPictureToPictureWithRotate() {
    // note that the image is square in this test to make rotation
    // easier to handle

    int size = 50;
    int black = Color.BLACK.getRGB();
    int white = Color.WHITE.getRGB();

    // construct an image with black and white stripped columns

    BufferedImage image1 = new BufferedImage(size, size, BufferedImage.TYPE_3BYTE_BGR);
    for (int x = 0; x < size; ++x)
        for (int y = 0; y < size; ++y) {
            int color = x % 2 == 0 ? black : white;
            image1.setRGB(x, y, color);
        }

    // convert image1 to a picture and then back to image2

    BufferedImage image2 = Utils.videoPictureToImage(Utils.imageToVideoPicture(image1, 0));

    // rotae image2

    AffineTransform t = AffineTransform.getRotateInstance(Math.PI / 2, image2.getWidth() / 2,
            image2.getHeight() / 2);
    AffineTransformOp ato = new AffineTransformOp(t, AffineTransformOp.TYPE_BICUBIC);
    BufferedImage image3 = new BufferedImage(size, size, BufferedImage.TYPE_3BYTE_BGR);
    ato.filter(image2, image3);

    // convert image2 to a picture and then back to image3

    BufferedImage image4 = Utils.videoPictureToImage(Utils.imageToVideoPicture(image3, 0));

    // test that image4 now contains stripped rows (not columns)

    for (int x = 0; x < size; ++x)
        for (int y = 0; y < size; ++y) {
            int pixel = image4.getRGB(x, y);
            int color = y % 2 == 0 ? black : white;
            assertTrue("color value missmatch", pixel == color);
        }
}

From source file:br.gov.jfrj.itextpdf.Documento.java

public static byte[] stamp(byte[] abPdf, String sigla, boolean rascunho, boolean cancelado, boolean semEfeito,
        boolean internoProduzido, String qrCode, String mensagem, Integer paginaInicial, Integer paginaFinal,
        Integer cOmitirNumeracao, String instancia, String orgaoUsu) throws DocumentException, IOException {

    PdfReader pdfIn = new PdfReader(abPdf);
    Document doc = new Document(PageSize.A4, 0, 0, 0, 0);
    // final SimpleDateFormat sdf = new SimpleDateFormat(
    // "EEE MMM dd HH:mm:ss zzz yyyy");
    // doc.add(new Meta("creationdate", sdf.format(new Date(0L))));
    final ByteArrayOutputStream boA4 = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(doc, boA4);
    doc.open();//from w  w w. jav a 2s  .  c  om
    PdfContentByte cb = writer.getDirectContent();

    // Resize every page to A4 size
    //
    // double thetaRotation = 0.0;
    for (int i = 1; i <= pdfIn.getNumberOfPages(); i++) {
        int rot = pdfIn.getPageRotation(i);
        float left = pdfIn.getPageSize(i).getLeft();
        float bottom = pdfIn.getPageSize(i).getBottom();
        float top = pdfIn.getPageSize(i).getTop();
        float right = pdfIn.getPageSize(i).getRight();

        PdfImportedPage page = writer.getImportedPage(pdfIn, i);
        float w = page.getWidth();
        float h = page.getHeight();

        // Logger.getRootLogger().error("----- dimensoes: " + rot + ", " + w
        // + ", " + h);

        doc.setPageSize((rot != 0 && rot != 180) ^ (w > h) ? PageSize.A4.rotate() : PageSize.A4);
        doc.newPage();

        cb.saveState();

        if (rot != 0 && rot != 180) {
            float swap = w;
            w = h;
            h = swap;
        }

        float pw = doc.getPageSize().getWidth();
        float ph = doc.getPageSize().getHeight();
        double scale = Math.min(pw / w, ph / h);

        // do my transformations :
        cb.transform(AffineTransform.getScaleInstance(scale, scale));

        if (!internoProduzido) {
            cb.transform(AffineTransform.getTranslateInstance(pw * SAFETY_MARGIN, ph * SAFETY_MARGIN));
            cb.transform(AffineTransform.getScaleInstance(1.0f - 2 * SAFETY_MARGIN, 1.0f - 2 * SAFETY_MARGIN));
        }

        if (rot != 0) {
            double theta = -rot * (Math.PI / 180);
            if (rot == 180) {
                cb.transform(AffineTransform.getRotateInstance(theta, w / 2, h / 2));
            } else {
                cb.transform(AffineTransform.getRotateInstance(theta, h / 2, w / 2));
            }
            if (rot == 90) {
                cb.transform(AffineTransform.getTranslateInstance((w - h) / 2, (w - h) / 2));
            } else if (rot == 270) {
                cb.transform(AffineTransform.getTranslateInstance((h - w) / 2, (h - w) / 2));
            }
        }

        // Logger.getRootLogger().error(
        // "----- dimensoes: " + rot + ", " + w + ", " + h);
        // Logger.getRootLogger().error("----- page: " + pw + ", " + ph);

        // cb.transform(AffineTransform.getTranslateInstance(
        // ((pw / scale) - w) / 2, ((ph / scale) - h) / 2));

        // put the page
        cb.addTemplate(page, 0, 0);

        // draw a red rectangle at the page borders
        //
        // cb.saveState();
        // cb.setColorStroke(Color.red);
        // cb.rectangle(pdfIn.getPageSize(i).getLeft(), pdfIn.getPageSize(i)
        // .getBottom(), pdfIn.getPageSize(i).getRight(), pdfIn
        // .getPageSize(i).getTop());
        // cb.stroke();
        // cb.restoreState();

        cb.restoreState();
    }
    doc.close();

    abPdf = boA4.toByteArray();

    final ByteArrayOutputStream bo2 = new ByteArrayOutputStream();

    final PdfReader reader = new PdfReader(abPdf);

    final int n = reader.getNumberOfPages();
    final PdfStamper stamp = new PdfStamper(reader, bo2);

    // adding content to each page
    int i = 0;
    PdfContentByte under;
    PdfContentByte over;
    final BaseFont helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);

    // Image img = Image.getInstance("watermark.jpg");
    final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);

    byte maskr[] = { (byte) 0xff };
    Image mask = Image.getInstance(1, 1, 1, 1, maskr);
    mask.makeMask();
    mask.setInverted(true);

    while (i < n) {
        i++;
        // watermark under the existing page
        under = stamp.getUnderContent(i);
        over = stamp.getOverContent(i);

        final Barcode39 code39 = new Barcode39();
        // code39.setCode(doc.getCodigo());
        code39.setCode(sigla.replace("-", "").replace("/", "").replace(".", ""));
        code39.setStartStopText(false);
        final Image image39 = code39.createImageWithBarcode(over, null, null);
        Rectangle r = stamp.getReader().getPageSizeWithRotation(i);

        image39.setInitialRotation((float) Math.PI / 2.0f);
        image39.setAbsolutePosition(
                r.getWidth() - image39.getHeight() + (STAMP_BORDER_IN_CM - PAGE_BORDER_IN_CM) * CM_UNIT,
                BARCODE_HEIGHT_IN_CM * CM_UNIT);

        image39.setBackgroundColor(Color.green);
        image39.setBorderColor(Color.RED);
        image39.setBorderWidth(0.5f * CM_UNIT);

        image39.setImageMask(mask);

        over.setRGBColorFill(255, 255, 255);
        mask.setAbsolutePosition(r.getWidth() - image39.getHeight() - (PAGE_BORDER_IN_CM) * CM_UNIT,
                (BARCODE_HEIGHT_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT);
        mask.scaleAbsolute(image39.getHeight() + 2 * STAMP_BORDER_IN_CM * CM_UNIT,
                image39.getWidth() + 2 * STAMP_BORDER_IN_CM * CM_UNIT);
        over.addImage(mask);

        over.setRGBColorFill(0, 0, 0);
        over.addImage(image39);

        // over.addImage(mask, mask.getScaledWidth() * 8, 0, 0,
        // mask.getScaledHeight() * 8, 100, 450);

        if (qrCode != null) {
            java.awt.Image imgQRCode = createQRCodeImage(qrCode);
            Image imageQRCode = Image.getInstance(imgQRCode, Color.BLACK, true);
            imageQRCode.scaleAbsolute(QRCODE_SIZE_IN_CM * CM_UNIT, QRCODE_SIZE_IN_CM * CM_UNIT);
            imageQRCode.setAbsolutePosition(QRCODE_LEFT_MARGIN_IN_CM * CM_UNIT, PAGE_BORDER_IN_CM * CM_UNIT);

            over.setRGBColorFill(255, 255, 255);
            mask.setAbsolutePosition((QRCODE_LEFT_MARGIN_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT,
                    (PAGE_BORDER_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT);
            mask.scaleAbsolute((QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT,
                    (QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT);
            over.addImage(mask);

            over.setRGBColorFill(0, 0, 0);
            over.addImage(imageQRCode);
        }

        if (mensagem != null) {
            PdfPTable table = new PdfPTable(1);
            table.setTotalWidth(r.getWidth() - image39.getHeight() - (QRCODE_LEFT_MARGIN_IN_CM
                    + QRCODE_SIZE_IN_CM + 4 * STAMP_BORDER_IN_CM + PAGE_BORDER_IN_CM) * CM_UNIT);
            PdfPCell cell = new PdfPCell(new Paragraph(mensagem,
                    FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, Color.BLACK)));
            cell.setBorderWidth(0);
            table.addCell(cell);

            over.setRGBColorFill(255, 255, 255);
            mask.setAbsolutePosition(
                    (QRCODE_LEFT_MARGIN_IN_CM + QRCODE_SIZE_IN_CM + STAMP_BORDER_IN_CM) * CM_UNIT,
                    (PAGE_BORDER_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT);
            mask.scaleAbsolute(2 * STAMP_BORDER_IN_CM * CM_UNIT + table.getTotalWidth(),
                    2 * STAMP_BORDER_IN_CM * CM_UNIT + table.getTotalHeight());
            over.addImage(mask);

            over.setRGBColorFill(0, 0, 0);
            table.writeSelectedRows(0, -1,
                    (QRCODE_LEFT_MARGIN_IN_CM + QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT,
                    table.getTotalHeight() + PAGE_BORDER_IN_CM * CM_UNIT, over);
        }

        if (cancelado) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "CANCELADO", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        } else if (rascunho) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "MINUTA", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        } else if (semEfeito) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "SEM EFEITO", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        }

        // if (!rascunho
        // && request.getRequestURL().indexOf("http://laguna/") == -1) {

        if (!rascunho && !cancelado && !semEfeito && ((!Contexto.resource("isVersionTest").equals("false"))
                || (!Contexto.resource("isBaseTest").equals("false")))) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "INVLIDO", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        }

        // Imprime um circulo com o numero da pagina dentro.

        if (paginaInicial != null) {
            String sFl = String.valueOf(paginaInicial + i - 1);
            // Se for a ultima pagina e o numero nao casar, acrescenta "-" e
            // pagina final
            if (n == i) {
                if (paginaFinal != paginaInicial + n - 1) {
                    sFl = sFl + "-" + String.valueOf(paginaFinal);
                }
            }
            if (i > cOmitirNumeracao) {

                // Raio do circulo interno
                final float radius = 18f;

                // Distancia entre o circulo interno e o externo
                final float circleInterspace = Math.max(helv.getAscentPoint(instancia, TEXT_HEIGHT),
                        helv.getAscentPoint(orgaoUsu, TEXT_HEIGHT))
                        - Math.min(helv.getDescentPoint(instancia, TEXT_HEIGHT),
                                helv.getDescentPoint(orgaoUsu, TEXT_HEIGHT))
                        + 2 * TEXT_TO_CIRCLE_INTERSPACE;

                // Centro do circulo
                float xCenter = r.getWidth() - 1.8f * (radius + circleInterspace);
                float yCenter = r.getHeight() - 1.8f * (radius + circleInterspace);

                over.saveState();
                final PdfGState gs = new PdfGState();
                gs.setFillOpacity(1f);
                over.setGState(gs);
                over.setColorFill(Color.BLACK);

                over.saveState();
                over.setColorStroke(Color.black);
                over.setLineWidth(1f);
                over.setColorFill(Color.WHITE);

                // Circulo externo
                over.circle(xCenter, yCenter, radius + circleInterspace);
                over.fill();
                over.circle(xCenter, yCenter, radius + circleInterspace);
                over.stroke();

                // Circulo interno
                over.circle(xCenter, yCenter, radius);
                over.stroke();
                over.restoreState();

                {
                    over.saveState();
                    over.beginText();
                    over.setFontAndSize(helv, TEXT_HEIGHT);

                    // Escreve o texto superior do carimbo
                    float fDescent = helv.getDescentPoint(instancia, TEXT_HEIGHT);
                    showTextOnArc(over, instancia, helv, TEXT_HEIGHT, xCenter, yCenter,
                            radius - fDescent + TEXT_TO_CIRCLE_INTERSPACE, true);

                    // Escreve o texto inferior
                    float fAscent = helv.getAscentPoint(orgaoUsu, TEXT_HEIGHT);
                    showTextOnArc(over, orgaoUsu, helv, TEXT_HEIGHT, xCenter, yCenter,
                            radius + fAscent + TEXT_TO_CIRCLE_INTERSPACE, false);
                    over.endText();
                    over.restoreState();
                }

                over.beginText();
                int textHeight = 23;

                // Diminui o tamanho do font ate que o texto caiba dentro do
                // circulo interno
                while (helv.getWidthPoint(sFl, textHeight) > (2 * (radius - TEXT_TO_CIRCLE_INTERSPACE)))
                    textHeight--;
                float fAscent = helv.getAscentPoint(sFl, textHeight) + helv.getDescentPoint(sFl, textHeight);
                over.setFontAndSize(helv, textHeight);
                over.showTextAligned(Element.ALIGN_CENTER, sFl, xCenter, yCenter - 0.5f * fAscent, 0);
                over.endText();
                over.restoreState();
            }
        }

    }
    stamp.close();
    return bo2.toByteArray();
}

From source file:com.flexive.shared.media.impl.FxMediaNativeEngine.java

/**
 * Rotate an image using the requested angle
 *
 * @param bufferedImage imeg to rotate// w  w w  .  j a  v a2  s .com
 * @param angle         angle to rotate
 * @return BufferedImage containing the rotation
 */
@SuppressWarnings({ "UnusedAssignment" })
private static BufferedImage rotate(BufferedImage bufferedImage, int angle) {
    angle = angle % 360;
    if (angle == 0)
        return bufferedImage;
    if (angle < 0)
        angle += 360;
    switch (angle) {
    case 90:
        BufferedImageOp rot90 = new AffineTransformOp(AffineTransform.getRotateInstance(Math.PI / 2.0,
                bufferedImage.getHeight() / 2.0, bufferedImage.getHeight() / 2.0),
                AffineTransformOp.TYPE_BILINEAR);
        BufferedImage img90 = new BufferedImage(bufferedImage.getHeight(), bufferedImage.getWidth(),
                bufferedImage.getType());
        return rot90.filter(bufferedImage, img90);
    case 180:
        BufferedImageOp rot180 = new AffineTransformOp(AffineTransform.getRotateInstance(Math.PI,
                bufferedImage.getWidth() / 2.0, bufferedImage.getHeight() / 2.0),
                AffineTransformOp.TYPE_BILINEAR);
        BufferedImage img180 = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(),
                bufferedImage.getType());
        return rot180.filter(bufferedImage, img180);
    case 270:
        BufferedImageOp rot270 = new AffineTransformOp(AffineTransform.getRotateInstance(-Math.PI / 2.0,
                bufferedImage.getWidth() / 2.0, bufferedImage.getWidth() / 2.0),
                AffineTransformOp.TYPE_BILINEAR);
        BufferedImage img270 = new BufferedImage(bufferedImage.getHeight(), bufferedImage.getWidth(),
                bufferedImage.getType());
        return rot270.filter(bufferedImage, img270);
    default:
        //rotate using a non-standard angle (have to draw a box around the image that can fit it)
        int box = (int) Math.sqrt(bufferedImage.getHeight() * bufferedImage.getHeight()
                + bufferedImage.getWidth() * bufferedImage.getWidth());
        BufferedImage imgFree = new BufferedImage(box, box, bufferedImage.getType());
        BufferedImage imgRet = new BufferedImage(box, box, bufferedImage.getType());
        Graphics2D g = imgFree.createGraphics();
        if (bufferedImage.getTransparency() == Transparency.OPAQUE) {
            //draw a white background on opaque images since they dont support transparency
            g.setBackground(Color.WHITE);
            g.clearRect(0, 0, box, box);
            Graphics2D gr = imgRet.createGraphics();
            gr.setBackground(Color.WHITE);
            gr.clearRect(0, 0, box, box);
            gr = null;
        }
        g.drawImage(bufferedImage, box / 2 - bufferedImage.getWidth() / 2,
                box / 2 - bufferedImage.getHeight() / 2, bufferedImage.getWidth(), bufferedImage.getHeight(),
                null);
        g = null;
        AffineTransform at = new AffineTransform();
        at.rotate(angle * Math.PI / 180.0, box / 2.0, box / 2.0);
        BufferedImageOp bio;
        bio = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
        return bio.filter(imgFree, imgRet);
    }
}

From source file:acmi.l2.clientmod.l2smr.Controller.java

@FXML
private void exportSM() {
    List<Actor> actors = this.table.getSelectionModel().getSelectedItems().stream().map(Actor::clone)
            .collect(Collectors.toList());

    if (actors.isEmpty())
        return;/*from w w  w .ja v  a  2  s  .c o  m*/

    int xy = 18 | (20 << 8);
    try {
        xy = getXY(getMapsDir(), this.unrChooser.getSelectionModel().getSelectedItem());
    } catch (IOException e) {
        showAlert(Alert.AlertType.WARNING, "Export", null, "Couldn't read map coords, using default 18_20");
    }
    ImportExportDialog dlg = new ImportExportDialog(xy & 0xff, (xy >> 8) & 0xff);
    ButtonType response = dlg.showAndWait().orElse(null);
    if (response != ButtonType.OK)
        return;

    FileChooser fileChooser = new FileChooser();
    fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("JSON", "*.json"));
    fileChooser.setTitle("Save");
    File file = fileChooser.showSaveDialog(getStage());
    if (file == null)
        return;

    longTask(progress -> {
        float x = dlg.getX(), y = dlg.getY(), z = dlg.getZ();
        double angle = dlg.getAngle();
        AffineTransform rotate = AffineTransform.getRotateInstance(Math.PI * angle / 180, x, y);
        AffineTransform translate = AffineTransform.getTranslateInstance(-x, -y);

        for (int i = 0; i < actors.size(); i++) {
            progress.accept((double) i / actors.size());
            Actor o = actors.get(i);
            Point2D.Float point = new Point2D.Float(o.getX(), o.getY());
            rotate.transform(point, point);
            translate.transform(point, point);

            o.setX(point.x);
            o.setY(point.y);
            o.setZ(o.getZ() - z);
            if (o.getYaw() == null)
                o.setYaw(0);
            o.setYaw(((int) (o.getYaw() + angle * 0xFFFF / 360)) & 0xFFFF);
        }
        progress.accept(-1.0);

        L2Map map = new L2Map(x, y, z, actors);
        ObjectMapper objectMapper = new ObjectMapper();

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            objectMapper.writeValue(baos, map);

            try (OutputStream fos = new FileOutputStream(file)) {
                baos.writeTo(fos);
            }
        }
    }, e -> onException("Export failed", e));
}

From source file:nl.b3p.viewer.stripes.OntbrandingsActionBean.java

private void createSafetyDistances(JSONArray gs, Geometry audience, Geometry ignition, Geometry safetyZone)
        throws TransformException {
    // Create safetydistances
    // 1. afstand tussen rand afsteekzone en safetyzone: loodrecht op publiek
    Point audienceCentroid = audience.getCentroid();
    Point ignitionCentroid = ignition.getCentroid();
    Coordinate[] coords = { audienceCentroid.getCoordinate(), ignitionCentroid.getCoordinate() };
    LineString audience2ignition = gf.createLineString(coords);

    double dx = ignitionCentroid.getX() - audienceCentroid.getX();
    double dy = ignitionCentroid.getY() - audienceCentroid.getY();
    double length = audience2ignition.getLength();
    double ratioX = (dx / length);
    double ratioY = (dy / length);
    double fanX = ratioX * 1000;
    double fanY = ratioY * 1000;

    Point eindLoodlijn = gf/*from w  ww. j a  va2 s.co m*/
            .createPoint(new Coordinate(ignitionCentroid.getX() + fanX, ignitionCentroid.getY() + fanY));
    Coordinate ancorPoint = ignitionCentroid.getCoordinate();

    double angleRad = Math.toRadians(90);
    AffineTransform affineTransform = AffineTransform.getRotateInstance(angleRad, ancorPoint.x, ancorPoint.y);
    MathTransform mathTransform = new AffineTransform2D(affineTransform);

    Geometry rotatedPoint = JTS.transform(eindLoodlijn, mathTransform);
    Coordinate[] loodLijnCoords = { ignitionCentroid.getCoordinate(), rotatedPoint.getCoordinate() };
    LineString loodLijn = gf.createLineString(loodLijnCoords);
    Geometry cutoffLoodlijn = loodLijn.intersection(safetyZone);
    cutoffLoodlijn = cutoffLoodlijn.difference(ignition);
    gs.put(createFeature(cutoffLoodlijn, "safetyDistance", (int) cutoffLoodlijn.getLength() + " m"));

    // 2. afstand tussen rand afsteekzone en safetyzone: haaks op publiek

    Coordinate[] endContinuousLine = { ignitionCentroid.getCoordinate(), eindLoodlijn.getCoordinate() };
    LineString continuousLine = gf.createLineString(endContinuousLine);
    Geometry cutoffContLine = continuousLine.intersection(safetyZone);
    cutoffContLine = cutoffContLine.difference(ignition);

    gs.put(createFeature(cutoffContLine, "safetyDistance", (int) cutoffContLine.getLength() + " m"));
}

From source file:org.nuxeo.pdf.service.PDFTransformationServiceImpl.java

public Point2D computeTranslationVector(double pageWidth, double watermarkWidth, double pageHeight,
        double watermarkHeight, WatermarkProperties properties) {
    double xTranslation;
    double yTranslation;
    double xRotationOffset = 0;
    double yRotationOffset = 0;

    if (properties.getTextRotation() != 0) {
        Rectangle2D rectangle2D = new Rectangle2D.Double(0, -watermarkHeight, watermarkWidth, watermarkHeight);
        AffineTransform at = AffineTransform.getRotateInstance(-Math.toRadians(properties.getTextRotation()), 0,
                0);/*from w w  w. j ava2 s. c o m*/
        Shape shape = at.createTransformedShape(rectangle2D);
        Rectangle2D rotated = shape.getBounds2D();

        watermarkWidth = rotated.getWidth();
        if (!properties.isInvertX() || properties.isRelativeCoordinates()) {
            xRotationOffset = -rotated.getX();
        } else {
            xRotationOffset = rotated.getX();
        }

        watermarkHeight = rotated.getHeight();
        if (!properties.isInvertY() || properties.isRelativeCoordinates()) {
            yRotationOffset = rotated.getY() + rotated.getHeight();
        } else {
            yRotationOffset = -(rotated.getY() + rotated.getHeight());
        }

    }

    if (properties.isRelativeCoordinates()) {
        xTranslation = (pageWidth - watermarkWidth) * properties.getxPosition() + xRotationOffset;
        yTranslation = (pageHeight - watermarkHeight) * properties.getyPosition() + yRotationOffset;
    } else {
        xTranslation = properties.getxPosition() + xRotationOffset;
        yTranslation = properties.getyPosition() + yRotationOffset;
        if (properties.isInvertX())
            xTranslation = pageWidth - watermarkWidth - xTranslation;
        if (properties.isInvertY())
            yTranslation = pageHeight - watermarkHeight - yTranslation;
    }
    return new Point2D.Double(xTranslation, yTranslation);
}

From source file:org.springframework.cloud.stream.app.pose.estimation.processor.PoseEstimateOutputMessageBuilder.java

private void drawPartOval(Part part, int radius, Graphics2D g) {
    int partX = part.getNormalizedX();
    int partY = part.getNormalizedY();

    g.setColor(GraphicsUtils.LIMBS_COLORS[part.getPartType().getId()]);
    g.fillOval(partX - radius, partY - radius, 2 * radius, 2 * radius);

    if (this.poseProperties.isDrawPartLabels()) {
        String label = part.getPartType().getId() + ":" + part.getPartType().name();
        FontMetrics fm = g.getFontMetrics();
        int labelX = partX + 5;
        int labelY = partY - 5;
        AffineTransform t = g.getTransform();
        g.setTransform(AffineTransform.getRotateInstance(Math.toRadians(-35), labelX, labelY));

        g.drawString(label, labelX, labelY);
        g.setTransform(t);//from   w w  w  . j av a  2  s. com
    }

}

From source file:org.tros.logo.swing.LogoPanel.java

/**
 * Paint.//from ww  w  .  j a  v a2  s . c  o m
 *
 * @param g
 */
@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g;

    turtleState.width = getWidth();
    turtleState.height = getHeight();

    draw(g2d, turtleState);

    if (turtleState.showTurtle && turtle != null) {
        double x = turtleState.penX - (turtle.getWidth() / 2.0);
        double y = turtleState.penY - (turtle.getHeight() / 2.0);
        AffineTransform translateInstance = AffineTransform
                .getRotateInstance(turtleState.angle + (Math.PI / 2.0), turtleState.penX, turtleState.penY);
        AffineTransform saveXform = g2d.getTransform();
        g2d.transform(translateInstance);
        g2d.drawImage(turtle, (int) x, (int) y, null);
        g2d.setTransform(saveXform);
    }
}

From source file:org.tros.logo.swing.LogoPanel.java

@Override
public void drawString(final String message) {
    Drawable command = new Drawable() {

        @Override/*from  w  w  w.j  a va2  s. c  om*/
        public void draw(Graphics2D g2, TurtleState turtleState) {
            if (!turtleState.penup) {
                AffineTransform saveXform = g2.getTransform();
                //double offsetAngle = (Math.PI / 2.0);
                double offsetAngle = 0;
                g2.setTransform(AffineTransform.getRotateInstance(turtleState.angle + offsetAngle,
                        turtleState.penX, turtleState.penY));
                g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                        RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
                g2.drawString(message, (int) turtleState.penX, (int) turtleState.penY);
                g2.setTransform(saveXform);
            }
        }

        @Override
        public void addListener(DrawListener listener) {
        }

        @Override
        public void removeListener(DrawListener listener) {
        }

        @Override
        public Drawable cloneDrawable() {
            return this;
        }
    };
    submitCommand(command);
}