Example usage for java.awt.geom AffineTransform getScaleInstance

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

Introduction

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

Prototype

public static AffineTransform getScaleInstance(double sx, double sy) 

Source Link

Document

Returns a transform representing a scaling transformation.

Usage

From source file:AppSpringLayout.java

protected BufferedImage mirrorImage(BufferedImage imageToFlip) {

    // Flip the image horizontally
    AffineTransform tx = AffineTransform.getScaleInstance(-1, 1);
    tx.translate(-imageToFlip.getWidth(null), 0);
    AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    imageToFlip = op.filter(imageToFlip, null);

    return imageToFlip;
}

From source file:edu.umn.cs.spatialHadoop.operations.HeatMapPlot.java

private static <S extends Shape> void plotHeatMapLocal(Path inFile, Path outFile, OperationsParams params)
        throws IOException {
    int imageWidth = params.getInt("width", 1000);
    int imageHeight = params.getInt("height", 1000);

    Shape shape = params.getShape("shape", new Point());
    Shape plotRange = params.getShape("rect", null);

    boolean keepAspectRatio = params.is("keep-ratio", true);

    InputSplit[] splits;//from   w w  w. ja v  a2  s.  c  o m
    FileSystem inFs = inFile.getFileSystem(params);
    FileStatus inFStatus = inFs.getFileStatus(inFile);
    if (inFStatus != null && !inFStatus.isDir()) {
        // One file, retrieve it immediately.
        // This is useful if the input is a hidden file which is automatically
        // skipped by FileInputFormat. We need to plot a hidden file for the case
        // of plotting partition boundaries of a spatial index
        splits = new InputSplit[] { new FileSplit(inFile, 0, inFStatus.getLen(), new String[0]) };
    } else {
        JobConf job = new JobConf(params);
        ShapeInputFormat<Shape> inputFormat = new ShapeInputFormat<Shape>();
        ShapeInputFormat.addInputPath(job, inFile);
        splits = inputFormat.getSplits(job, 1);
    }

    boolean vflip = params.is("vflip");

    Rectangle fileMBR;
    if (plotRange != null) {
        fileMBR = plotRange.getMBR();
    } else {
        fileMBR = FileMBR.fileMBR(inFile, params);
    }

    if (keepAspectRatio) {
        // Adjust width and height to maintain aspect ratio
        if (fileMBR.getWidth() / fileMBR.getHeight() > (double) imageWidth / imageHeight) {
            // Fix width and change height
            imageHeight = (int) (fileMBR.getHeight() * imageWidth / fileMBR.getWidth());
        } else {
            imageWidth = (int) (fileMBR.getWidth() * imageHeight / fileMBR.getHeight());
        }
    }

    // Create the frequency map
    int radius = params.getInt("radius", 5);
    FrequencyMap frequencyMap = new FrequencyMap(imageWidth, imageHeight);

    for (InputSplit split : splits) {
        ShapeRecordReader<Shape> reader = new ShapeRecordReader<Shape>(params, (FileSplit) split);
        Rectangle cell = reader.createKey();
        while (reader.next(cell, shape)) {
            Rectangle shapeBuffer = shape.getMBR();
            if (shapeBuffer == null)
                continue;
            shapeBuffer = shapeBuffer.buffer(radius, radius);
            if (plotRange == null || shapeBuffer.isIntersected(plotRange)) {
                Point centerPoint = shapeBuffer.getCenterPoint();
                int cx = (int) Math.round((centerPoint.x - fileMBR.x1) * imageWidth / fileMBR.getWidth());
                int cy = (int) Math.round((centerPoint.y - fileMBR.y1) * imageHeight / fileMBR.getHeight());
                frequencyMap.addPoint(cx, cy, radius);
            }
        }
        reader.close();
    }

    // Convert frequency map to an image with colors
    NASAPoint.setColor1(params.getColor("color1", Color.BLUE));
    NASAPoint.setColor2(params.getColor("color2", Color.RED));
    NASAPoint.gradientType = params.getGradientType("gradient", NASAPoint.GradientType.GT_HUE);
    String valueRangeStr = params.get("valuerange");
    MinMax valueRange = null;
    if (valueRangeStr != null) {
        String[] parts = valueRangeStr.contains("..") ? valueRangeStr.split("\\.\\.", 2)
                : valueRangeStr.split(",", 2);
        valueRange = new MinMax(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
    }

    boolean skipZeros = params.getBoolean("skipzeros", false);
    BufferedImage image = frequencyMap.toImage(valueRange, skipZeros);

    if (vflip) {
        AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
        tx.translate(0, -image.getHeight());
        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
        image = op.filter(image, null);
    }
    FileSystem outFs = outFile.getFileSystem(params);
    OutputStream out = outFs.create(outFile, true);
    ImageIO.write(image, "png", out);
    out.close();

}

From source file:com.isti.traceview.common.TraceViewChartPanel.java

/**
 * Paints the component by drawing the chart to fill the entire component, but allowing for the
 * insets (which will be non-zero if a border has been set for this component). To increase
 * performance (at the expense of memory), an off-screen buffer image can be used.
 * /*from w w  w .j  a v a 2 s. c om*/
 * @param g
 *            the graphics device for drawing on.
 */
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (this.chart == null) {
        return;
    }
    Graphics2D g2 = (Graphics2D) g.create();

    // first determine the size of the chart rendering area...
    Dimension size = getSize();
    Insets insets = getInsets();
    Rectangle2D available = new Rectangle2D.Double(insets.left, insets.top,
            size.getWidth() - insets.left - insets.right, size.getHeight() - insets.top - insets.bottom);

    // work out if scaling is required...
    boolean scale = false;
    double drawWidth = available.getWidth();
    double drawHeight = available.getHeight();
    this.scaleX = 1.0;
    this.scaleY = 1.0;

    if (drawWidth < this.minimumDrawWidth) {
        this.scaleX = drawWidth / this.minimumDrawWidth;
        drawWidth = this.minimumDrawWidth;
        scale = true;
    } else if (drawWidth > this.maximumDrawWidth) {
        this.scaleX = drawWidth / this.maximumDrawWidth;
        drawWidth = this.maximumDrawWidth;
        scale = true;
    }

    if (drawHeight < this.minimumDrawHeight) {
        this.scaleY = drawHeight / this.minimumDrawHeight;
        drawHeight = this.minimumDrawHeight;
        scale = true;
    } else if (drawHeight > this.maximumDrawHeight) {
        this.scaleY = drawHeight / this.maximumDrawHeight;
        drawHeight = this.maximumDrawHeight;
        scale = true;
    }

    Rectangle2D chartArea = new Rectangle2D.Double(0.0, 0.0, drawWidth, drawHeight);

    // are we using the chart buffer?
    if (this.useBuffer) {
        // do we need to resize the buffer?
        if ((this.chartBuffer == null) || (this.chartBufferWidth != available.getWidth())
                || (this.chartBufferHeight != available.getHeight())) {
            this.chartBufferWidth = (int) available.getWidth();
            this.chartBufferHeight = (int) available.getHeight();
            this.chartBuffer = new BufferedImage(this.chartBufferWidth, this.chartBufferHeight,
                    BufferedImage.TYPE_INT_RGB);
            //this.chartBuffer = createImage(this.chartBufferWidth, this.chartBufferHeight);  -by Max
            // GraphicsConfiguration gc = g2.getDeviceConfiguration();
            // this.chartBuffer = gc.createCompatibleImage(
            // this.chartBufferWidth, this.chartBufferHeight,
            // Transparency.TRANSLUCENT);
            this.refreshBuffer = true;
        }

        // do we need to redraw the buffer?
        if (this.refreshBuffer) {
            Rectangle2D bufferArea = new Rectangle2D.Double(0, 0, this.chartBufferWidth,
                    this.chartBufferHeight);
            Graphics2D bufferG2 = (Graphics2D) this.chartBuffer.getGraphics();
            if (scale) {
                AffineTransform saved = bufferG2.getTransform();
                AffineTransform st = AffineTransform.getScaleInstance(this.scaleX, this.scaleY);
                bufferG2.transform(st);
                this.chart.draw(bufferG2, chartArea, this.anchor, this.info);
                bufferG2.setTransform(saved);
            } else {
                this.chart.draw(bufferG2, bufferArea, this.anchor, this.info);
            }

            this.refreshBuffer = false;
        }

        // zap the buffer onto the panel...
        g2.drawImage(this.chartBuffer, insets.left, insets.top, this);

    }

    // or redrawing the chart every time...
    else {
        AffineTransform saved = g2.getTransform();
        g2.translate(insets.left, insets.top);
        if (scale) {
            AffineTransform st = AffineTransform.getScaleInstance(this.scaleX, this.scaleY);
            g2.transform(st);
        }
        this.chart.draw(g2, chartArea, this.anchor, this.info);
        g2.setTransform(saved);
    }

    // Redraw the zoom rectangle (if present)
    drawZoomRectangle(g2);

    g2.dispose();
    this.anchor = null;
    this.verticalTraceLine = null;
    this.horizontalTraceLine = null;
}

From source file:org.rdv.viz.chart.ChartPanel.java

/**
 * Paints the component by drawing the chart to fill the entire component,
 * but allowing for the insets (which will be non-zero if a border has been
 * set for this component).  To increase performance (at the expense of
 * memory), an off-screen buffer image can be used.
 *
 * @param g  the graphics device for drawing on.
 *///from w ww  . j a v  a  2s.  c  o  m
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (this.chart == null) {
        return;
    }
    Graphics2D g2 = (Graphics2D) g.create();

    // first determine the size of the chart rendering area...
    Dimension size = getSize();
    Insets insets = getInsets();
    Rectangle2D available = new Rectangle2D.Double(insets.left, insets.top,
            size.getWidth() - insets.left - insets.right, size.getHeight() - insets.top - insets.bottom);

    // work out if scaling is required...
    boolean scale = false;
    double drawWidth = available.getWidth();
    double drawHeight = available.getHeight();
    this.scaleX = 1.0;
    this.scaleY = 1.0;

    if (drawWidth < this.minimumDrawWidth) {
        this.scaleX = drawWidth / this.minimumDrawWidth;
        drawWidth = this.minimumDrawWidth;
        scale = true;
    } else if (drawWidth > this.maximumDrawWidth) {
        this.scaleX = drawWidth / this.maximumDrawWidth;
        drawWidth = this.maximumDrawWidth;
        scale = true;
    }

    if (drawHeight < this.minimumDrawHeight) {
        this.scaleY = drawHeight / this.minimumDrawHeight;
        drawHeight = this.minimumDrawHeight;
        scale = true;
    } else if (drawHeight > this.maximumDrawHeight) {
        this.scaleY = drawHeight / this.maximumDrawHeight;
        drawHeight = this.maximumDrawHeight;
        scale = true;
    }

    Rectangle2D chartArea = new Rectangle2D.Double(0.0, 0.0, drawWidth, drawHeight);

    // are we using the chart buffer?
    if (this.useBuffer) {

        // if buffer is being refreshed, it needs clearing unless it is
        // new - use the following flag to track this...
        boolean clearBuffer = true;

        // do we need to resize the buffer?
        if ((this.chartBuffer == null) || (this.chartBufferWidth != available.getWidth())
                || (this.chartBufferHeight != available.getHeight())) {
            this.chartBufferWidth = (int) available.getWidth();
            this.chartBufferHeight = (int) available.getHeight();
            this.chartBuffer = createImage(this.chartBufferWidth, this.chartBufferHeight);
            //                GraphicsConfiguration gc = g2.getDeviceConfiguration();
            //                this.chartBuffer = gc.createCompatibleImage(
            //                        this.chartBufferWidth, this.chartBufferHeight,
            //                        Transparency.TRANSLUCENT);
            this.refreshBuffer = true;
            clearBuffer = false; // buffer is new, no clearing required
        }

        // do we need to redraw the buffer?
        if (this.refreshBuffer) {

            this.refreshBuffer = false; // clear the flag

            Rectangle2D bufferArea = new Rectangle2D.Double(0, 0, this.chartBufferWidth,
                    this.chartBufferHeight);

            Graphics2D bufferG2 = (Graphics2D) this.chartBuffer.getGraphics();
            if (clearBuffer) {
                bufferG2.clearRect(0, 0, this.chartBufferWidth, this.chartBufferHeight);
            }
            if (scale) {
                AffineTransform saved = bufferG2.getTransform();
                AffineTransform st = AffineTransform.getScaleInstance(this.scaleX, this.scaleY);
                bufferG2.transform(st);
                this.chart.draw(bufferG2, chartArea, this.anchor, this.info);
                bufferG2.setTransform(saved);
            } else {
                this.chart.draw(bufferG2, bufferArea, this.anchor, this.info);
            }

        }

        // zap the buffer onto the panel...
        g2.drawImage(this.chartBuffer, insets.left, insets.top, this);

    }

    // or redrawing the chart every time...
    else {

        AffineTransform saved = g2.getTransform();
        g2.translate(insets.left, insets.top);
        if (scale) {
            AffineTransform st = AffineTransform.getScaleInstance(this.scaleX, this.scaleY);
            g2.transform(st);
        }
        this.chart.draw(g2, chartArea, this.anchor, this.info);
        g2.setTransform(saved);

    }

    // Redraw the zoom rectangle (if present)
    drawZoomRectangle(g2);

    g2.dispose();

    this.anchor = null;
    this.verticalTraceLine = null;
    this.horizontalTraceLine = null;

}

From source file:edu.umn.cs.spatialHadoop.operations.GeometricPlot.java

private static <S extends Shape> void plotLocal(Path inFile, Path outFile, OperationsParams params)
        throws IOException {
    int width = params.getInt("width", 1000);
    int height = params.getInt("height", 1000);

    Color strokeColor = params.getColor("color", Color.BLACK);
    int color = strokeColor.getRGB();

    String hdfDataset = (String) params.get("dataset");
    Shape shape = hdfDataset != null ? new NASARectangle() : (Shape) params.getShape("shape", null);
    Shape plotRange = params.getShape("rect", null);

    boolean keepAspectRatio = params.is("keep-ratio", true);

    String valueRangeStr = (String) params.get("valuerange");
    MinMax valueRange;/*from   w  ww  .  j  av  a2 s .co m*/
    if (valueRangeStr == null) {
        valueRange = null;
    } else {
        String[] parts = valueRangeStr.split(",");
        valueRange = new MinMax(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
    }

    InputSplit[] splits;
    FileSystem inFs = inFile.getFileSystem(params);
    FileStatus inFStatus = inFs.getFileStatus(inFile);
    if (inFStatus != null && !inFStatus.isDir()) {
        // One file, retrieve it immediately.
        // This is useful if the input is a hidden file which is automatically
        // skipped by FileInputFormat. We need to plot a hidden file for the case
        // of plotting partition boundaries of a spatial index
        splits = new InputSplit[] { new FileSplit(inFile, 0, inFStatus.getLen(), new String[0]) };
    } else {
        JobConf job = new JobConf(params);
        ShapeInputFormat<Shape> inputFormat = new ShapeInputFormat<Shape>();
        ShapeInputFormat.addInputPath(job, inFile);
        splits = inputFormat.getSplits(job, 1);
    }

    boolean vflip = params.is("vflip");

    Rectangle fileMbr;
    if (plotRange != null) {
        fileMbr = plotRange.getMBR();
    } else if (hdfDataset != null) {
        // Plotting a NASA file
        fileMbr = new Rectangle(-180, -90, 180, 90);
    } else {
        fileMbr = FileMBR.fileMBR(inFile, params);
    }

    if (keepAspectRatio) {
        // Adjust width and height to maintain aspect ratio
        if (fileMbr.getWidth() / fileMbr.getHeight() > (double) width / height) {
            // Fix width and change height
            height = (int) (fileMbr.getHeight() * width / fileMbr.getWidth());
        } else {
            width = (int) (fileMbr.getWidth() * height / fileMbr.getHeight());
        }
    }

    boolean adaptiveSample = shape instanceof Point && params.getBoolean("sample", false);
    float adaptiveSampleRatio = 0.0f;
    if (adaptiveSample) {
        // Calculate the sample ratio
        long recordCount = FileMBR.fileMBR(inFile, params).recordCount;
        adaptiveSampleRatio = params.getFloat(AdaptiveSampleFactor, 1.0f) * width * height / recordCount;
    }

    boolean gradualFade = !(shape instanceof Point) && params.getBoolean("fade", false);

    if (hdfDataset != null) {
        // Collects some stats about the HDF file
        if (valueRange == null)
            valueRange = Aggregate.aggregate(new Path[] { inFile }, params);
        NASAPoint.minValue = valueRange.minValue;
        NASAPoint.maxValue = valueRange.maxValue;
        NASAPoint.setColor1(params.getColor("color1", Color.BLUE));
        NASAPoint.setColor2(params.getColor("color2", Color.RED));
        NASAPoint.gradientType = params.getGradientType("gradient", NASAPoint.GradientType.GT_HUE);
    }

    double scale2 = (double) width * height / (fileMbr.getWidth() * fileMbr.getHeight());
    double scale = Math.sqrt(scale2);

    // Create an image
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    Color bg_color = params.getColor("bgcolor", new Color(0, 0, 0, 0));
    graphics.setBackground(bg_color);
    graphics.clearRect(0, 0, width, height);
    graphics.setColor(strokeColor);

    for (InputSplit split : splits) {
        if (hdfDataset != null) {
            // Read points from the HDF file
            RecordReader<NASADataset, NASAShape> reader = new HDFRecordReader(params, (FileSplit) split,
                    hdfDataset, true);
            NASADataset dataset = reader.createKey();

            while (reader.next(dataset, (NASAShape) shape)) {
                // Skip with a fixed ratio if adaptive sample is set
                if (adaptiveSample && Math.random() > adaptiveSampleRatio)
                    continue;
                if (plotRange == null || shape.isIntersected(shape)) {
                    shape.draw(graphics, fileMbr, width, height, 0.0);
                }
            }
            reader.close();
        } else {
            RecordReader<Rectangle, Shape> reader = new ShapeRecordReader<Shape>(params, (FileSplit) split);
            Rectangle cell = reader.createKey();
            while (reader.next(cell, shape)) {
                // Skip with a fixed ratio if adaptive sample is set
                if (adaptiveSample && Math.random() > adaptiveSampleRatio)
                    continue;
                Rectangle shapeMBR = shape.getMBR();
                if (shapeMBR != null) {
                    if (plotRange == null || shapeMBR.isIntersected(plotRange)) {
                        if (gradualFade) {
                            double sizeInPixels = (shapeMBR.getWidth() + shapeMBR.getHeight()) * scale;
                            if (sizeInPixels < 1.0 && Math.round(sizeInPixels * 255) < 1.0) {
                                // This shape can be safely skipped as it is too small to be plotted
                                continue;
                            } else {
                                int alpha = (int) Math.round(sizeInPixels * 255);
                                graphics.setColor(new Color((alpha << 24) | color, true));
                            }
                        }
                        shape.draw(graphics, fileMbr, width, height, scale2);
                    }
                }
            }
            reader.close();
        }
    }
    // Write image to output
    graphics.dispose();
    if (vflip) {
        AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
        tx.translate(0, -image.getHeight());
        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
        image = op.filter(image, null);
    }
    FileSystem outFs = outFile.getFileSystem(params);
    OutputStream out = outFs.create(outFile, true);
    ImageIO.write(image, "png", out);
    out.close();

}

From source file:com.rapidminer.gui.plotter.charts.AbstractChartPanel.java

/**
 * Paints the component by drawing the chart to fill the entire component, but allowing for the
 * insets (which will be non-zero if a border has been set for this component). To increase
 * performance (at the expense of memory), an off-screen buffer image can be used.
 * //from w  ww  . ja v  a 2  s .  c  o m
 * @param g
 *            the graphics device for drawing on.
 */

@Override
public void paintComponent(Graphics g) {
    if (this.chart == null) {
        return;
    }
    Graphics2D g2 = (Graphics2D) g.create();

    // first determine the size of the chart rendering area...
    Dimension size = getSize();
    Insets insets = getInsets();
    Rectangle2D available = new Rectangle2D.Double(insets.left, insets.top,
            size.getWidth() - insets.left - insets.right, size.getHeight() - insets.top - insets.bottom);

    // work out if scaling is required...
    boolean scale = false;
    double drawWidth = available.getWidth();
    double drawHeight = available.getHeight();
    this.scaleX = 1.0;
    this.scaleY = 1.0;

    if (drawWidth < this.minimumDrawWidth) {
        this.scaleX = drawWidth / this.minimumDrawWidth;
        drawWidth = this.minimumDrawWidth;
        scale = true;
    } else if (drawWidth > this.maximumDrawWidth) {
        this.scaleX = drawWidth / this.maximumDrawWidth;
        drawWidth = this.maximumDrawWidth;
        scale = true;
    }

    if (drawHeight < this.minimumDrawHeight) {
        this.scaleY = drawHeight / this.minimumDrawHeight;
        drawHeight = this.minimumDrawHeight;
        scale = true;
    } else if (drawHeight > this.maximumDrawHeight) {
        this.scaleY = drawHeight / this.maximumDrawHeight;
        drawHeight = this.maximumDrawHeight;
        scale = true;
    }

    Rectangle2D chartArea = new Rectangle2D.Double(0.0, 0.0, drawWidth, drawHeight);
    // redrawing the chart every time...

    AffineTransform saved = g2.getTransform();
    g2.translate(insets.left, insets.top);
    if (scale) {
        AffineTransform st = AffineTransform.getScaleInstance(this.scaleX, this.scaleY);
        g2.transform(st);
    }
    this.chart.draw(g2, chartArea, this.anchor, this.info);
    g2.setTransform(saved);

    Iterator<Overlay> iterator = this.overlays.iterator();
    while (iterator.hasNext()) {
        Overlay overlay = iterator.next();
        overlay.paintOverlay(g2, this);
    }

    // redraw the zoom rectangle (if present) - if useBuffer is false,
    // we use XOR so we can XOR the rectangle away again without redrawing
    // the chart
    drawSelectionRectangle(g2);

    g2.dispose();

    this.anchor = null;
    this.verticalTraceLine = null;
    this.horizontalTraceLine = null;

}

From source file:opennlp.tools.similarity.apps.utils.Utils.java

public static boolean createResizedCopy(String originalImage, String newImage, int scaledWidth,
        int scaledHeight) {
    boolean retVal = true;
    try {/*from w w w . ja v  a2  s. c  om*/
        File o = new File(originalImage);
        BufferedImage bsrc = ImageIO.read(o);
        BufferedImage bdest = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);

        Graphics2D g = bdest.createGraphics();
        AffineTransform at = AffineTransform.getScaleInstance((double) scaledWidth / bsrc.getWidth(),
                (double) scaledHeight / bsrc.getHeight());
        g.drawRenderedImage(bsrc, at);
        ImageIO.write(bdest, "jpeg", new File(newImage));

    } catch (Exception e) {
        retVal = false;
        LOG.severe("Failed creating thumbnail for image: " + originalImage + e);
    }

    return retVal;
}

From source file:org.apache.fop.render.java2d.Java2DSVGHandler.java

/** {@inheritDoc} */
protected void renderSVGDocument(RendererContext context, Document doc) {
    Java2DInfo info = getJava2DInfo(context);
    if (log.isDebugEnabled()) {
        log.debug("renderSVGDocument(" + context + ", " + doc + ", " + info + ")");
    }//  w  ww.  jav  a2  s .  com

    // fallback paint as bitmap
    if (info.paintAsBitmap) {
        try {
            super.renderSVGDocument(context, doc);
        } catch (IOException ioe) {
            SVGEventProducer eventProducer = SVGEventProducer.Provider
                    .get(context.getUserAgent().getEventBroadcaster());
            eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc));
        }
        return;
    }

    int x = info.currentXPosition;
    int y = info.currentYPosition;

    SVGUserAgent ua = new SVGUserAgent(context.getUserAgent(), new AffineTransform());

    BridgeContext ctx = new BridgeContext(ua);

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

    GraphicsNode root;
    try {
        GVTBuilder builder = new GVTBuilder();
        root = builder.build(ctx, clonedDoc);
    } catch (Exception e) {
        SVGEventProducer eventProducer = SVGEventProducer.Provider
                .get(context.getUserAgent().getEventBroadcaster());
        eventProducer.svgNotBuilt(this, e, getDocumentURI(doc));
        return;
    }

    // If no viewbox is defined in the svg file, a viewbox of 100x100 is
    // assumed, as defined in SVGUserAgent.getViewportSize()
    float iw = (float) ctx.getDocumentSize().getWidth() * 1000f;
    float ih = (float) ctx.getDocumentSize().getHeight() * 1000f;

    float w = info.width;
    float h = info.height;

    AffineTransform origTransform = info.state.getGraph().getTransform();

    // correct integer roundoff
    info.state.getGraph().translate(x / 1000f, y / 1000f);

    //SVGSVGElement svg = ((SVGDocument) doc).getRootElement();
    // Aspect ratio preserved by layout engine, not here
    AffineTransform at = AffineTransform.getScaleInstance(w / iw, h / ih);
    if (!at.isIdentity()) {
        info.state.getGraph().transform(at);
    }

    try {
        root.paint(info.state.getGraph());
    } catch (Exception e) {
        SVGEventProducer eventProducer = SVGEventProducer.Provider
                .get(context.getUserAgent().getEventBroadcaster());
        eventProducer.svgRenderingError(this, e, getDocumentURI(doc));
    }

    info.state.getGraph().setTransform(origTransform);
}

From source file:org.apache.fop.render.pdf.pdfbox.PDFBoxAdapter.java

/**
 * Creates a stream (from FOP's PDF library) from a PDF page parsed with PDFBox.
 * @param sourceDoc the source PDF the given page to be copied belongs to
 * @param page the page to transform into a stream
 * @param key value to use as key for the stream
 * @param atdoc adjustment for stream//from  www.j ava2 s.  c  o  m
 * @param fontinfo fonts
 * @param pos rectangle
 * @return the stream
 * @throws IOException if an I/O error occurs
 */
public String createStreamFromPDFBoxPage(PDDocument sourceDoc, PDPage page, String key, AffineTransform atdoc,
        FontInfo fontinfo, Rectangle pos) throws IOException {
    handleAnnotations(sourceDoc, page, atdoc);
    if (pageNumbers.containsKey(targetPage.getPageIndex())) {
        pageNumbers.get(targetPage.getPageIndex()).set(0, targetPage.makeReference());
    }
    PDResources sourcePageResources = page.getResources();
    PDStream pdStream = getContents(page);

    COSDictionary fonts = (COSDictionary) sourcePageResources.getCOSObject().getDictionaryObject(COSName.FONT);
    COSDictionary fontsBackup = null;
    UniqueName uniqueName = new UniqueName(key, sourcePageResources);
    String newStream = null;
    if (fonts != null && pdfDoc.isMergeFontsEnabled()) {
        fontsBackup = new COSDictionary(fonts);
        MergeFontsPDFWriter m = new MergeFontsPDFWriter(fonts, fontinfo, uniqueName, parentFonts, currentMCID);
        newStream = m.writeText(pdStream);
        //            if (newStream != null) {
        //                for (Object f : fonts.keySet().toArray()) {
        //                    COSDictionary fontdata = (COSDictionary)fonts.getDictionaryObject((COSName)f);
        //                    if (getUniqueFontName(fontdata) != null) {
        //                        fonts.removeItem((COSName)f);
        //                    }
        //                }
        //            }
    }
    if (newStream == null) {
        PDFWriter writer = new PDFWriter(uniqueName, currentMCID);
        newStream = writer.writeText(pdStream);
        currentMCID = writer.getCurrentMCID();

    }
    pdStream = new PDStream(sourceDoc, new ByteArrayInputStream(newStream.getBytes("ISO-8859-1")));
    mergeXObj(sourcePageResources.getCOSObject(), fontinfo, uniqueName);
    PDFDictionary pageResources = (PDFDictionary) cloneForNewDocument(sourcePageResources.getCOSObject());

    PDFDictionary fontDict = (PDFDictionary) pageResources.get("Font");
    if (fontDict != null && pdfDoc.isMergeFontsEnabled()) {
        for (Map.Entry<String, Typeface> fontEntry : fontinfo.getUsedFonts().entrySet()) {
            Typeface font = fontEntry.getValue();
            if (font instanceof FOPPDFFont) {
                FOPPDFFont pdfFont = (FOPPDFFont) font;
                if (pdfFont.getRef() == null) {
                    pdfFont.setRef(new PDFDictionary());
                    pdfDoc.assignObjectNumber(pdfFont.getRef());
                }
                fontDict.put(fontEntry.getKey(), pdfFont.getRef());
            }
        }
    }
    updateXObj(sourcePageResources.getCOSObject(), pageResources);
    if (fontsBackup != null) {
        sourcePageResources.getCOSObject().setItem(COSName.FONT, fontsBackup);
    }

    COSStream originalPageContents = pdStream.getCOSObject();

    bindOptionalContent(sourceDoc);

    PDFStream pageStream;
    Set filter;
    //        if (originalPageContents instanceof COSStreamArray) {
    //            COSStreamArray array = (COSStreamArray)originalPageContents;
    //            pageStream = new PDFStream();
    //            InputStream in = array.getUnfilteredStream();
    //            OutputStream out = pageStream.getBufferOutputStream();
    //            IOUtils.copyLarge(in, out);
    //            filter = FILTER_FILTER;
    //        } else {
    pageStream = (PDFStream) cloneForNewDocument(originalPageContents);
    filter = Collections.EMPTY_SET;
    //        }
    if (pageStream == null) {
        pageStream = new PDFStream();
    }
    if (originalPageContents != null) {
        transferDict(originalPageContents, pageStream, filter);
    }

    transferPageDict(fonts, uniqueName, sourcePageResources);

    PDRectangle mediaBox = page.getMediaBox();
    PDRectangle cropBox = page.getCropBox();
    PDRectangle viewBox = cropBox != null ? cropBox : mediaBox;

    //Handle the /Rotation entry on the page dict
    int rotation = PDFUtil.getNormalizedRotation(page);

    //Transform to FOP's user space
    float w = (float) pos.getWidth() / 1000f;
    float h = (float) pos.getHeight() / 1000f;
    if (rotation == 90 || rotation == 270) {
        float tmp = w;
        w = h;
        h = tmp;
    }
    atdoc.setTransform(AffineTransform.getScaleInstance(w / viewBox.getWidth(), h / viewBox.getHeight()));
    atdoc.translate(0, viewBox.getHeight());
    atdoc.rotate(-Math.PI);
    atdoc.scale(-1, 1);
    atdoc.translate(-viewBox.getLowerLeftX(), -viewBox.getLowerLeftY());

    rotate(rotation, viewBox, atdoc);

    StringBuilder boxStr = new StringBuilder();
    boxStr.append(PDFNumber.doubleOut(mediaBox.getLowerLeftX())).append(' ')
            .append(PDFNumber.doubleOut(mediaBox.getLowerLeftY())).append(' ')
            .append(PDFNumber.doubleOut(mediaBox.getWidth())).append(' ')
            .append(PDFNumber.doubleOut(mediaBox.getHeight())).append(" re W n\n");
    return boxStr.toString() + IOUtils.toString(pdStream.createInputStream(null), "ISO-8859-1");
}

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

public BufferedImage prepare(String filename) {
    try {/*  w  w  w .j a va2s.c  om*/
        src = ImageIO.read(new File(filename));
    } catch (IOException e) {
        log.error("Image file does not exist:" + filename + ", can not render image.");
    }
    XYData fullSize = new XYData(1, 1);
    while (fullSize.getX() < src.getWidth() || fullSize.getY() < src.getHeight()) {
        fullSize.set(fullSize.getX() * 2, fullSize.getY() * 2);
    }
    float scaleX = (float) fullSize.getX() / src.getWidth();
    float scaleY = (float) fullSize.getY() / src.getHeight();
    log.info("Image size: (" + src.getWidth() + "," + src.getHeight() + ")");
    log.info("Scale size: (" + scaleX + "," + scaleY + ")");

    AffineTransform at = AffineTransform.getScaleInstance(scaleX, scaleY);

    //       AffineTransform.getScaleInstance((fullSize.getX()-src.getWidth())/2,(fullSize.getY()-src.getHeight())/2);
    AffineTransformOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
    BufferedImage dest = op.filter(src, null);
    return dest;
}