Example usage for java.awt.geom AffineTransform scale

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

Introduction

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

Prototype

@SuppressWarnings("fallthrough")
public void scale(double sx, double sy) 

Source Link

Document

Concatenates this transform with a scaling transformation.

Usage

From source file:org.hydroponics.dao.JDBCHydroponicsDaoImpl.java

public byte[] getThumbnail(BufferedImage buffImage) throws IOException {
    BufferedImage pDestImage = new BufferedImage(Constants.THUMBNAIL_WIDTH, Constants.THUMBNAIL_HEIGHT,
            BufferedImage.TYPE_3BYTE_BGR);

    AffineTransform transform = new AffineTransform();
    transform.scale((float) Constants.THUMBNAIL_WIDTH / (float) buffImage.getWidth(),
            (float) Constants.THUMBNAIL_HEIGHT / (float) buffImage.getHeight());

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

    //set the rendering hints for a good thumbnail image
    Map m = g.getRenderingHints();
    m.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    m.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    m.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    m.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g.setRenderingHints(m);/*from w w w  . ja  va 2s . co  m*/

    g.drawImage(buffImage, transform, null);
    g.dispose();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ImageIO.write(pDestImage, "JPEG", out);
    return out.toByteArray();
}

From source file:org.apache.hadoop.chukwa.hicc.ImageSlicer.java

public BufferedImage tile(BufferedImage image, int level, XYData quadrant, XYData size, boolean efficient)
        throws Exception {
    double scale = Math.pow(2, level);
    if (efficient) {
        /* efficient: crop out the area of interest first, then scale and copy it */
        XYData inverSize = new XYData((int) (image.getWidth(null) / (size.getX() * scale)),
                (int) (image.getHeight(null) / (size.getY() * scale)));
        XYData topLeft = new XYData(quadrant.getX() * size.getX() * inverSize.getX(),
                quadrant.getY() * size.getY() * inverSize.getY());
        XYData newSize = new XYData((size.getX() * inverSize.getX()), (size.getY() * inverSize.getY()));
        if (inverSize.getX() < 1.0 || inverSize.getY() < 1.0) {
            throw new Exception("Requested zoom level (" + level + ") is too high.");
        }//from w  w  w . ja  va2 s. c o  m
        image = image.getSubimage(topLeft.getX(), topLeft.getY(), newSize.getX(), newSize.getY());
        BufferedImage zoomed = new BufferedImage(size.getX(), size.getY(), BufferedImage.TYPE_INT_RGB);
        zoomed.getGraphics().drawImage(image, 0, 0, size.getX(), size.getY(), null);
        if (level > maxLevel) {
            maxLevel = level;
        }
        return zoomed;
    } else {
        /* inefficient: copy the whole image, scale it and then crop out the area of interest */
        XYData newSize = new XYData((int) (size.getX() * scale), (int) (size.getY() * scale));
        XYData topLeft = new XYData(quadrant.getX() * size.getX(), quadrant.getY() * size.getY());
        if (newSize.getX() > image.getWidth(null) || newSize.getY() > image.getHeight(null)) {
            throw new Exception("Requested zoom level (" + level + ") is too high.");
        }
        AffineTransform tx = new AffineTransform();
        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
        tx.scale(scale, scale);
        image = op.filter(image, null);
        BufferedImage zoomed = image.getSubimage(topLeft.getX(), topLeft.getY(), newSize.getX(),
                newSize.getY());
        if (level > maxLevel) {
            maxLevel = level;
        }
        return zoomed;
    }
}

From source file:pl.edu.icm.visnow.lib.utils.ImageUtilities.java

public static BufferedImage resizeImage(BufferedImage img, double xScale, double yScale, int type) {
    if (img == null) {
        return null;
    }//w w  w  . j  a v  a  2  s.  com

    if (xScale <= 0 || yScale <= 0) {
        return null;
    }

    int w = img.getWidth();
    int h = img.getHeight();

    int neww = (int) (((double) w) * xScale);
    int newh = (int) (((double) h) * yScale);

    BufferedImage out = new BufferedImage(neww, newh, img.getType());

    AffineTransform tr = new AffineTransform();
    tr.scale(xScale, yScale);
    BufferedImageOp op = new AffineTransformOp(tr, type);
    op.filter(img, out);
    return out;
}

From source file:org.evors.rs.ui.sandpit.SandPitCamera.java

/**
 * Get the value of transform/*w  w  w  .  ja va  2 s.c  om*/
 *
 * @return the value of transform
 */
public AffineTransform getTransform() {
    AffineTransform returnTransform = new AffineTransform();
    Vector2D currentPosScreenCoord = new Vector2D(getScale(), getCurrentPosWorldCoord());
    Vector2D halfWindow = getHalfWindowSize();
    returnTransform.translate(currentPosScreenCoord.getX() + halfWindow.getX(),
            currentPosScreenCoord.getY() + halfWindow.getY());
    returnTransform.scale(getScale(), -getScale());

    return returnTransform;
}

From source file:org.apache.fop.render.pdf.PDFDocumentHandler.java

/** {@inheritDoc} */
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException {
    this.pdfResources = this.pdfDoc.getResources();

    PageBoundaries boundaries = new PageBoundaries(size, getContext().getForeignAttributes());

    Rectangle trimBox = boundaries.getTrimBox();
    Rectangle bleedBox = boundaries.getBleedBox();
    Rectangle mediaBox = boundaries.getMediaBox();
    Rectangle cropBox = boundaries.getCropBox();

    // set scale attributes
    double scaleX = 1;
    double scaleY = 1;
    String scale = (String) getContext().getForeignAttribute(PageScale.EXT_PAGE_SCALE);
    Point2D scales = PageScale.getScale(scale);
    if (scales != null) {
        scaleX = scales.getX();/*from   w  ww .  j a v a  2s.com*/
        scaleY = scales.getY();
    }

    //PDF uses the lower left as origin, need to transform from FOP's internal coord system
    AffineTransform boxTransform = new AffineTransform(scaleX / 1000, 0, 0, -scaleY / 1000, 0,
            scaleY * size.getHeight() / 1000);

    this.currentPage = this.pdfDoc.getFactory().makePage(this.pdfResources, index,
            toPDFCoordSystem(mediaBox, boxTransform), toPDFCoordSystem(cropBox, boxTransform),
            toPDFCoordSystem(bleedBox, boxTransform), toPDFCoordSystem(trimBox, boxTransform));
    if (accessEnabled) {
        logicalStructureHandler.startPage(currentPage);
    }

    pdfUtil.generatePageLabel(index, name);

    currentPageRef = new PageReference(currentPage, size);
    this.pageReferences.put(Integer.valueOf(index), currentPageRef);

    this.generator = new PDFContentGenerator(this.pdfDoc, this.outputStream, this.currentPage);
    // Transform the PDF's default coordinate system (0,0 at lower left) to the PDFPainter's
    AffineTransform basicPageTransform = new AffineTransform(1, 0, 0, -1, 0, (scaleY * size.height) / 1000f);
    basicPageTransform.scale(scaleX, scaleY);
    generator.saveGraphicsState();
    generator.concatenate(basicPageTransform);
}

From source file:VASSAL.tools.image.svg.SVGRenderer.java

public BufferedImage render(double angle, double scale) {
    // The renderer needs the bounds unscaled---scaling comes from the
    // width and height hints.
    AffineTransform px = AffineTransform.getRotateInstance(angle * DEGTORAD, defaultW / 2.0, defaultH / 2.0);
    r.setTransform(px);/* w w  w .j  a va  2s .c o m*/

    px = new AffineTransform(px);
    px.scale(scale, scale);

    final Rectangle2D rect = new Rectangle2D.Float(0, 0, defaultW, defaultH);
    final Rectangle2D b = px.createTransformedShape(rect).getBounds2D();

    r.addTranscodingHint(Rasterizer.KEY_WIDTH, (float) b.getWidth());
    r.addTranscodingHint(Rasterizer.KEY_HEIGHT, (float) b.getHeight());

    try {
        r.transcode(new TranscoderInput(doc), null);
        return r.getBufferedImage();
    }
    // FIXME: review error message
    catch (BridgeException e) {
        logger.error("", e);
    } catch (TranscoderException e) {
        logger.error("", e);
    }

    return null;
}

From source file:VASSAL.tools.image.svg.SVGRenderer.java

public BufferedImage render(double angle, double scale, Rectangle2D aoi) {
    // The renderer needs the bounds unscaled---scaling comes from the
    // width and height hints.
    AffineTransform px = AffineTransform.getRotateInstance(angle * DEGTORAD, defaultW / 2.0, defaultH / 2.0);
    r.setTransform(px);/*from   w  ww .  j  a v a 2 s.com*/

    px = new AffineTransform(px);
    px.scale(scale, scale);

    final Rectangle2D rect = new Rectangle2D.Float(0, 0, defaultW, defaultH);

    r.addTranscodingHint(Rasterizer.KEY_WIDTH, (float) aoi.getWidth());
    r.addTranscodingHint(Rasterizer.KEY_HEIGHT, (float) aoi.getHeight());
    r.addTranscodingHint(Rasterizer.KEY_AOI, aoi);

    try {
        r.transcode(new TranscoderInput(doc), null);
        return r.getBufferedImage();
    }
    // FIXME: review error message
    catch (BridgeException e) {
        logger.error("", e);
    } catch (TranscoderException e) {
        logger.error("", e);
    }

    return null;
}

From source file:org.apache.fop.render.pdf.PDFImageHandlerSVG.java

/** {@inheritDoc} */
public void handleImage(RenderingContext context, // CSOK: MethodLength
        Image image, Rectangle pos) throws IOException {
    PDFRenderingContext pdfContext = (PDFRenderingContext) context;
    PDFContentGenerator generator = pdfContext.getGenerator();
    ImageXMLDOM imageSVG = (ImageXMLDOM) image;

    FOUserAgent userAgent = context.getUserAgent();
    final float deviceResolution = userAgent.getTargetResolution();
    if (log.isDebugEnabled()) {
        log.debug("Generating SVG at " + deviceResolution + "dpi.");
    }/*from   w  w  w .  j av a2  s . c  om*/

    final float uaResolution = userAgent.getSourceResolution();
    SVGUserAgent ua = new SVGUserAgent(userAgent, new AffineTransform());

    GVTBuilder builder = new GVTBuilder();

    //Controls whether text painted by Batik is generated using text or path operations
    boolean strokeText = false;
    //TODO connect with configuration elsewhere.

    BridgeContext ctx = new PDFBridgeContext(ua, (strokeText ? null : pdfContext.getFontInfo()),
            userAgent.getFactory().getImageManager(), userAgent.getImageSessionContext(),
            new AffineTransform());

    //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine)
    //to it.
    Document clonedDoc = BatikUtil.cloneSVGDocument(imageSVG.getDocument());

    GraphicsNode root;
    try {
        root = builder.build(ctx, clonedDoc);
        builder = null;
    } catch (Exception e) {
        SVGEventProducer eventProducer = SVGEventProducer.Provider
                .get(context.getUserAgent().getEventBroadcaster());
        eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI());
        return;
    }
    // get the 'width' and 'height' attributes of the SVG document
    float w = image.getSize().getWidthMpt();
    float h = image.getSize().getHeightMpt();

    float sx = pos.width / w;
    float sy = pos.height / h;

    //Scaling and translation for the bounding box of the image
    AffineTransform scaling = new AffineTransform(sx, 0, 0, sy, pos.x / 1000f, pos.y / 1000f);
    double sourceScale = UnitConv.IN2PT / uaResolution;
    scaling.scale(sourceScale, sourceScale);

    //Scale for higher resolution on-the-fly images from Batik
    AffineTransform resolutionScaling = new AffineTransform();
    double targetScale = uaResolution / deviceResolution;
    resolutionScaling.scale(targetScale, targetScale);
    resolutionScaling.scale(1.0 / sx, 1.0 / sy);

    //Transformation matrix that establishes the local coordinate system for the SVG graphic
    //in relation to the current coordinate system
    AffineTransform imageTransform = new AffineTransform();
    imageTransform.concatenate(scaling);
    imageTransform.concatenate(resolutionScaling);

    if (log.isTraceEnabled()) {
        log.trace("nat size: " + w + "/" + h);
        log.trace("req size: " + pos.width + "/" + pos.height);
        log.trace("source res: " + uaResolution + ", targetRes: " + deviceResolution + " --> target scaling: "
                + targetScale);
        log.trace(image.getSize());
        log.trace("sx: " + sx + ", sy: " + sy);
        log.trace("scaling: " + scaling);
        log.trace("resolution scaling: " + resolutionScaling);
        log.trace("image transform: " + resolutionScaling);
    }

    /*
     * Clip to the svg area.
     * Note: To have the svg overlay (under) a text area then use
     * an fo:block-container
     */
    if (log.isTraceEnabled()) {
        generator.comment("SVG setup");
    }
    generator.saveGraphicsState();
    if (context.getUserAgent().isAccessibilityEnabled()) {
        MarkedContentInfo mci = pdfContext.getMarkedContentInfo();
        generator.beginMarkedContentSequence(mci.tag, mci.mcid);
    }
    generator.updateColor(Color.black, false, null);
    generator.updateColor(Color.black, true, null);

    if (!scaling.isIdentity()) {
        if (log.isTraceEnabled()) {
            generator.comment("viewbox");
        }
        generator.add(CTMHelper.toPDFString(scaling, false) + " cm\n");
    }

    //SVGSVGElement svg = ((SVGDocument)doc).getRootElement();

    PDFGraphics2D graphics = new PDFGraphics2D(true, pdfContext.getFontInfo(), generator.getDocument(),
            generator.getResourceContext(), pdfContext.getPage().referencePDF(), "", 0);
    graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());

    if (!resolutionScaling.isIdentity()) {
        if (log.isTraceEnabled()) {
            generator.comment("resolution scaling for " + uaResolution + " -> " + deviceResolution);
        }
        generator.add(CTMHelper.toPDFString(resolutionScaling, false) + " cm\n");
        graphics.scale(1.0 / resolutionScaling.getScaleX(), 1.0 / resolutionScaling.getScaleY());
    }

    if (log.isTraceEnabled()) {
        generator.comment("SVG start");
    }

    //Save state and update coordinate system for the SVG image
    generator.getState().save();
    generator.getState().concatenate(imageTransform);

    //Now that we have the complete transformation matrix for the image, we can update the
    //transformation matrix for the AElementBridge.
    PDFAElementBridge aBridge = (PDFAElementBridge) ctx.getBridge(SVGDOMImplementation.SVG_NAMESPACE_URI,
            SVGConstants.SVG_A_TAG);
    aBridge.getCurrentTransform().setTransform(generator.getState().getTransform());

    graphics.setPaintingState(generator.getState());
    graphics.setOutputStream(generator.getOutputStream());
    try {
        root.paint(graphics);
        ctx.dispose();
        generator.add(graphics.getString());
    } catch (Exception e) {
        SVGEventProducer eventProducer = SVGEventProducer.Provider
                .get(context.getUserAgent().getEventBroadcaster());
        eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI());
    }
    generator.getState().restore();
    if (context.getUserAgent().isAccessibilityEnabled()) {
        generator.restoreGraphicsStateAccess();
    } else {
        generator.restoreGraphicsState();
    }
    if (log.isTraceEnabled()) {
        generator.comment("SVG end");
    }
}

From source file:lu.lippmann.cdb.graph.mouse.CadralEditingGraphMousePlugin.java

/**
 * Function to create the edge shape while drawing
 * @param down//from   w  w w .j ava2 s.co  m
 * @param out
 */
private void transformEdgeShape(Point2D down, Point2D out) {
    float x1 = (float) down.getX();
    float y1 = (float) down.getY();
    float x2 = (float) out.getX();
    float y2 = (float) out.getY();
    AffineTransform xform = AffineTransform.getTranslateInstance(x1, y1);
    float dx = x2 - x1;
    float dy = y2 - y1;
    float thetaRadians = (float) Math.atan2(dy, dx);
    xform.rotate(thetaRadians);
    float dist = (float) Math.sqrt(dx * dx + dy * dy);
    xform.scale((double) dist / rawEdge.getBounds().getWidth(), 1.0d);
    edgeShape = xform.createTransformedShape(rawEdge);
}

From source file:org.uva.itast.blended.omr.pages.PageImage.java

/**
 * Scaled graphics for drawing on a small version of the page.
 * Transform is set for drawing in pixels refered to the original scanned image
 * @return//from w w  w  .  j  a v  a2 s .co m
 */
public Graphics2D getReportingGraphics() {
    // TODO: Crear una transformacion equivalente a la de la pgina para la imagen reducida
    BufferedImage reportingImage = this.getReportingImage();
    Graphics2D g = reportingImage.createGraphics();

    //      AffineTransform origTransf=getAllignmentInfo();
    //
    //      AffineTransform trans=(AffineTransform) origTransf.clone();
    //      trans.scale(reportingImage.getWidth()/(getImage().getWidth()),
    //         reportingImage.getHeight()/(getImage().getHeight()));
    //      AffineTransform trans=g.getTransform();
    //      trans.scale(reportingImage.getWidth()/(getPreferredHorizontalResolution()*PageImage.a4width),
    //            reportingImage.getHeight()/(getPreferredVerticalResolution()*PageImage.a4height));
    double scaleX = ((double) reportingImage.getWidth()) / (getImage().getWidth());
    double scaleY = ((double) reportingImage.getHeight()) / (getImage().getHeight());
    AffineTransform trans = g.getTransform();
    trans.scale(scaleX, scaleY);
    g.setTransform(trans);
    return g;
}