Example usage for com.lowagie.text Image setAbsolutePosition

List of usage examples for com.lowagie.text Image setAbsolutePosition

Introduction

In this page you can find the example usage for com.lowagie.text Image setAbsolutePosition.

Prototype


public void setAbsolutePosition(float absoluteX, float absoluteY) 

Source Link

Document

Sets the absolute position of the Image.

Usage

From source file:org.jrimum.bopepo.pdf.PDFUtil.java

License:Apache License

/**
 * <p>/*from ww  w . j  av a 2s  .  co  m*/
 * Muda um input field para uma imgem com as dimenses e possio do field.
 * </p>
 * 
 * @param stamper
 * @param rect
 * @param image
 * @return rectanglePDF
 * @throws DocumentException
 * 
 * @since 0.2
 */
public static RectanglePDF changeFieldToImage(PdfStamper stamper, RectanglePDF rect, Image image)
        throws DocumentException {

    // Ajustando o tamanho da imagem de acordo com o tamanho do campo.
    // image.scaleToFit(rect.getWidth(), rect.getHeight());
    image.scaleAbsolute(rect.getWidth(), rect.getHeight());

    // A rotina abaixo tem por objetivo deixar a imagem posicionada no
    // centro
    // do field, tanto na perspectiva horizontal como na vertical.
    // Caso no se queira mais posicionar a imagem no centro do field, basta
    // efetuar a chamada a seguir:
    // "image.setAbsolutePosition
    // (rect.getLowerLeftX(),rect.getLowerLeftY());"
    image.setAbsolutePosition(rect.getLowerLeftX() + (rect.getWidth() - image.getScaledWidth()) / 2,
            rect.getLowerLeftY() + (rect.getHeight() - image.getScaledHeight()) / 2);

    // cb = stamper.getUnderContent(rect.getPage());
    stamper.getOverContent(rect.getPage()).addImage(image);

    return rect;
}

From source file:org.kuali.coeus.common.impl.print.watermark.WatermarkServiceImpl.java

License:Open Source License

/**
 * This method is for setting the properties of watermark Image.
 * /*from w w w .ja v  a 2s .  c o  m*/
 * @param pdfContentByte
 * @param pageWidth
 * @param pageHeight
 * @param watermarkBean
 */
private void decoratePdfWatermarkImage(PdfContentByte pdfContentByte, int pageWidth, int pageHeight,
        WatermarkBean watermarkBean) {
    PdfGState pdfGState = new PdfGState();
    final float OPACITY = 0.3f;
    float absPosX;
    float absPosY;
    try {
        if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_IMAGE)) {
            Image watermarkImage = Image.getInstance(watermarkBean.getFileImage());
            if (watermarkImage != null) {
                pdfGState.setFillOpacity(OPACITY);
                pdfContentByte.setGState(pdfGState);
                float height = watermarkImage.getPlainHeight();
                float width = watermarkImage.getPlainWidth();
                int diagonal = (int) Math.sqrt((pageWidth * pageWidth) + (pageHeight * pageHeight));
                int pivotPoint = (diagonal - (int) width) / 2;
                float angle = (float) Math.atan((float) pageHeight / pageWidth);
                absPosX = (float) (pivotPoint * pageWidth) / diagonal;
                absPosY = (float) (pivotPoint * pageHeight) / diagonal;
                watermarkImage.setAbsolutePosition(absPosX, absPosY);
                if ((pageWidth / 2) < width) {
                    watermarkImage.scaleToFit(pageWidth / 2, pageHeight / 2);
                } else {
                    watermarkImage.scaleToFit(width, height);
                }
                pdfContentByte.addImage(watermarkImage);
            }

        }

    } catch (BadElementException badElementException) {

        LOG.error("WatermarkDecoratorImpl  Error found: " + badElementException.getMessage());
    } catch (DocumentException documentException) {

        LOG.error("WatermarkDecoratorImpl Error found: " + documentException.getMessage());
    }

}

From source file:org.kuali.kra.printing.service.impl.WatermarkServiceImpl.java

License:Educational Community License

/**
 * This method is for setting the properties of watermark Image.
 * //from ww  w. ja  v  a 2 s. co m
 * @param pdfContentByte
 * @param pageWidth
 * @param pageHeight
 * @param watermarkBean
 */
private void decoratePdfWatermarkImage(PdfContentByte pdfContentByte, int pageWidth, int pageHeight,
        WatermarkBean watermarkBean) {
    try {
        if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_IMAGE)) {
            Image watermarkImage = Image.getInstance(watermarkBean.getFileImage());
            if (watermarkImage != null) {
                float height = watermarkImage.getPlainHeight();
                float width = watermarkImage.getPlainWidth();
                watermarkImage.setAbsolutePosition((pageWidth - width) / 2, (pageHeight - height) / 2);
                pdfContentByte.addImage(watermarkImage);
            }

        }

    } catch (BadElementException badElementException) {

        LOG.error("WatermarkDecoratorImpl  Error found: " + badElementException.getMessage());
    } catch (DocumentException documentException) {

        LOG.error("WatermarkDecoratorImpl Error found: " + documentException.getMessage());
    }

}

From source file:org.locationtech.udig.printing.ui.pdf.ExportPDFWizard.java

License:Open Source License

/**
 * double scaleDenom = page1.isCustomScale() ? page1.getCustomScale() : map.getViewportModel().getScaleDenominator(); 
 *
 * @param mapWithRasterLayersOnly a map with only raster layers
 * @param mapBoundsInTemplate a rectangle indicating the coordinates of the top left, width and height 
 * (where the coordinate system has (0,0) in the top left.
 * @param doc the PDF document object/*from w  ww  .ja  v a2s .  com*/
 */
private void writeRasterLayersOnlyToDocument(Map mapWithRasterLayersOnly,
        org.eclipse.swt.graphics.Rectangle mapBoundsInTemplate, Document doc, Dimension pageSize,
        double currentViewportScaleDenom) {

    //set dimensions of the raster image to be the same ratio as
    //the required map bounds within the page, but scaled up so
    //we can achieve a higher DPI when we later insert the image
    //into the page (90 refers to the default DPI) 
    int w = mapBoundsInTemplate.width * page1.getDpi() / 90;
    int h = mapBoundsInTemplate.height * page1.getDpi() / 90;

    BufferedImage imageOfRastersOnly = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = imageOfRastersOnly.createGraphics();

    //define a DrawMapParameter object with a custom BoundsStrategy if a custom scale is set
    DrawMapParameter drawMapParameter = null;

    double scaleDenom = (page1.getScaleOption() == ExportPDFWizardPage1.CUSTOM_MAP_SCALE)
            ? page1.getCustomScale()
            : currentViewportScaleDenom;

    drawMapParameter = new DrawMapParameter(g, new java.awt.Dimension(w, h), mapWithRasterLayersOnly,
            new BoundsStrategy(scaleDenom), page1.getDpi(), SelectionStyle.EXCLUSIVE_ALL, null);

    try {

        //draw the map (at a high resolution as specified above)
        ApplicationGIS.drawMap(drawMapParameter);
        Image img = Image.getInstance(bufferedImage2ByteArray(imageOfRastersOnly));

        //scale the image down to fit into the page
        img.scaleAbsolute(mapBoundsInTemplate.width, mapBoundsInTemplate.height);

        //set the location of the image
        int left = mapBoundsInTemplate.x;
        int bottom = pageSize.height - mapBoundsInTemplate.height - mapBoundsInTemplate.y;
        img.setAbsolutePosition(left, bottom); //(0,0) is bottom left in the PDF coordinate system

        doc.add(img);
        addWhiteMapBorder(img, doc);

    } catch (Exception e) {
        //TODO: fail gracefully.
    }

}

From source file:org.locationtech.udig.printing.ui.pdf.ExportPDFWizard.java

License:Open Source License

/**
 * This function is used to draw very thin white borders over the outer 
 * edge of the raster map.  It's necessary because the map edge "bleeds" into
 * the adjacent pixels, and we need to cover that.
 * //from www.j  a v  a 2 s  .  c o  m
 * I think this quirky behaviour is possibly an iText bug
 */
private void addWhiteMapBorder(Image img, Document doc) {

    try {

        Color color = Color.white;
        int borderWidth = 1;

        BufferedImage bufferedTop = new BufferedImage((int) img.getScaledWidth(), borderWidth,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g1 = bufferedTop.createGraphics();
        g1.setBackground(color);
        g1.clearRect(0, 0, bufferedTop.getWidth(), bufferedTop.getHeight());
        Image top = Image.getInstance(bufferedImage2ByteArray(bufferedTop));
        top.setAbsolutePosition(img.getAbsoluteX(),
                img.getAbsoluteY() + img.getScaledHeight() - bufferedTop.getHeight() / 2);

        BufferedImage bufferedBottom = new BufferedImage((int) img.getScaledWidth(), borderWidth,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bufferedBottom.createGraphics();
        g2.setBackground(color);
        g2.clearRect(0, 0, bufferedBottom.getWidth(), bufferedBottom.getHeight());
        Image bottom = Image.getInstance(bufferedImage2ByteArray(bufferedBottom));
        bottom.setAbsolutePosition(img.getAbsoluteX(), img.getAbsoluteY() - bufferedTop.getHeight() / 2);

        BufferedImage bufferedLeft = new BufferedImage(borderWidth, (int) img.getScaledHeight(),
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g3 = bufferedLeft.createGraphics();
        g3.setBackground(color);
        g3.clearRect(0, 0, bufferedLeft.getWidth(), bufferedLeft.getHeight());
        Image left = Image.getInstance(bufferedImage2ByteArray(bufferedLeft));
        left.setAbsolutePosition(img.getAbsoluteX() - bufferedLeft.getWidth() / 2, img.getAbsoluteY());

        BufferedImage bufferedRight = new BufferedImage(borderWidth, (int) img.getScaledHeight(),
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g4 = bufferedRight.createGraphics();
        g4.setBackground(color);
        g4.clearRect(0, 0, bufferedRight.getWidth(), bufferedRight.getHeight());
        Image right = Image.getInstance(bufferedImage2ByteArray(bufferedRight));
        right.setAbsolutePosition(img.getAbsoluteX() + img.getScaledWidth() - bufferedRight.getWidth() / 2,
                img.getAbsoluteY());

        doc.add(top);
        doc.add(bottom);
        doc.add(left);
        doc.add(right);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.lucee.extension.pdf.tag.PDF.java

License:Open Source License

private void doActionAddWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "addWatermark", "source", source);
    if (copyFrom == null && image == null)
        throw engine.getExceptionUtil().createApplicationException(
                "at least one of the following attributes must be defined " + "[copyFrom,image]");

    if (destination != null && destination.exists() && !overwrite)
        throw engine.getExceptionUtil()
                .createApplicationException("destination file [" + destination + "] already exists");

    // image/*from  ww  w  . j av a  2  s  .  c o  m*/
    Image img = null;
    if (image != null) {
        // TODO lucee.runtime.img.Image ri = lucee.runtime.img.Image.createImage(pageContext,image,false,false,true,null);
        // TODO img=Image.getInstance(ri.getBufferedImage(),null,false);
    }
    // copy From
    else {
        byte[] barr;
        try {
            Resource res = copyFrom instanceof String
                    ? engine.getResourceUtil().toResourceExisting(pageContext, (String) copyFrom)
                    : engine.getCastUtil().toResource(copyFrom);
            barr = PDFUtil.toBytes(res);
        } catch (PageException ee) {
            barr = engine.getCastUtil().toBinary(copyFrom);
        }
        img = Image.getInstance(PDFUtil.toImage(barr, 1), null, false);

    }

    // position
    float x = UNDEFINED, y = UNDEFINED;
    if (!Util.isEmpty(position)) {
        int index = position.indexOf(',');
        if (index == -1)
            throw engine.getExceptionUtil()
                    .createApplicationException("attribute [position] has an invalid value [" + position + "],"
                            + "value should follow one of the following pattern [40,50], [40,] or [,50]");
        String strX = position.substring(0, index).trim();
        String strY = position.substring(index + 1).trim();
        if (!Util.isEmpty(strX))
            x = engine.getCastUtil().toIntValue(strX);
        if (!Util.isEmpty(strY))
            y = engine.getCastUtil().toIntValue(strY);

    }

    PDFStruct doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();
    reader.consolidateNamedDestinations();
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null)
        master.addAll(bookmarks);

    // output
    boolean destIsSource = destination != null && doc.getResource() != null
            && destination.equals(doc.getResource());
    OutputStream os = null;
    if (!Util.isEmpty(name) || destIsSource) {
        os = new ByteArrayOutputStream();
    } else if (destination != null) {
        os = destination.getOutputStream();
    }

    try {

        int len = reader.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(reader, os);

        if (len > 0) {
            if (x == UNDEFINED || y == UNDEFINED) {
                PdfImportedPage first = stamp.getImportedPage(reader, 1);
                if (y == UNDEFINED)
                    y = (first.getHeight() - img.getHeight()) / 2;
                if (x == UNDEFINED)
                    x = (first.getWidth() - img.getWidth()) / 2;
            }
            img.setAbsolutePosition(x, y);
            // img.setAlignment(Image.ALIGN_JUSTIFIED); ration geht nicht anhand mitte

        }

        // rotation
        if (rotation != 0) {
            img.setRotationDegrees(rotation);
        }

        Set _pages = doc.getPages();
        for (int i = 1; i <= len; i++) {
            if (_pages != null && !_pages.contains(Integer.valueOf(i)))
                continue;
            PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
            PdfGState gs1 = new PdfGState();
            // print.out("op:"+opacity);
            gs1.setFillOpacity(opacity);
            // gs1.setStrokeOpacity(opacity);
            cb.setGState(gs1);
            cb.addImage(img);
        }
        if (bookmarks != null)
            stamp.setOutlines(master);
        stamp.close();
    } finally {
        Util.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
                        destination, true);// MUST overwrite
            if (!Util.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFStruct(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}

From source file:org.lucee.extension.pdf.tag.PDF.java

License:Open Source License

private void doActionRemoveWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "removeWatermark", "source", source);

    if (destination != null && destination.exists() && !overwrite)
        throw engine.getExceptionUtil()
                .createApplicationException("destination file [" + destination + "] already exists");

    BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bi.createGraphics();
    g.setBackground(Color.BLACK);
    g.clearRect(0, 0, 1, 1);//from w  w w.jav  a  2s. c  o m

    Image img = Image.getInstance(bi, null, false);
    img.setAbsolutePosition(1, 1);

    PDFStruct doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();

    boolean destIsSource = destination != null && doc.getResource() != null
            && destination.equals(doc.getResource());
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null)
        master.addAll(bookmarks);

    // output
    OutputStream os = null;
    if (!Util.isEmpty(name) || destIsSource) {
        os = new ByteArrayOutputStream();
    } else if (destination != null) {
        os = destination.getOutputStream();
    }

    try {
        int len = reader.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(reader, os);

        Set _pages = doc.getPages();
        for (int i = 1; i <= len; i++) {
            if (_pages != null && !_pages.contains(Integer.valueOf(i)))
                continue;
            PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
            PdfGState gs1 = new PdfGState();
            gs1.setFillOpacity(0);
            cb.setGState(gs1);
            cb.addImage(img);
        }
        if (bookmarks != null)
            stamp.setOutlines(master);
        stamp.close();
    } finally {
        Util.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
                        destination, true);// MUST overwrite
            if (!Util.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFStruct(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}

From source file:org.mapfish.print.map.renderers.BitmapMapRenderer.java

License:Open Source License

public void render(Transformer transformer, List<URI> uris, PdfContentByte dc, RenderingContext context,
        float opacity, int nbTilesHorizontal, float offsetX, float offsetY, long bitmapTileW, long bitmapTileH)
        throws IOException {
    dc.saveState();//from   w  ww.  j a  va  2  s.c om
    try {
        final AffineTransform bitmapTransformer = transformer.getBitmapTransform();
        dc.transform(bitmapTransformer);
        final double rotation = transformer.getRotation();

        for (int i = 0; i < uris.size(); i++) {
            URI uri = uris.get(i);
            if (uri == null) {
                continue;
            }

            final int line = i / nbTilesHorizontal;
            final int col = i % nbTilesHorizontal;
            final float posX = 0 - offsetX + col * bitmapTileW;
            final float posY = 0 - offsetY + line * bitmapTileH;

            if (rotation != 0.0
                    && !isTileVisible(posX, posY, bitmapTileW, bitmapTileH, bitmapTransformer, transformer)) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Not needed: " + uri);
                }
                continue;
            }

            LOGGER.debug(uri);
            final Image map = PDFUtils.getImage(context, uri, bitmapTileW, bitmapTileH);
            map.setAbsolutePosition(posX, posY);

            if (opacity < 1.0) {
                PdfGState gs = new PdfGState();
                gs.setFillOpacity(opacity);
                gs.setStrokeOpacity(opacity);
                dc.setGState(gs);
            }
            dc.addImage(map);
        }
    } catch (DocumentException e) {
        context.addError(e);
    } finally {
        dc.restoreState();
    }
}

From source file:org.mapfish.print.map.renderers.vector.PointRenderer.java

License:Open Source License

protected void renderImpl(RenderingContext context, PdfContentByte dc, PJsonObject style, Point geometry) {
    PdfGState state = new PdfGState();
    final Coordinate coordinate = geometry.getCoordinate();
    float pointRadius = style.optFloat("pointRadius", 4.0f);
    final float f = context.getStyleFactor();

    String graphicName = style.optString("graphicName");
    float width = style.optFloat("graphicWidth", pointRadius * 2.0f);
    float height = style.optFloat("graphicHeight", pointRadius * 2.0f);
    float offsetX = style.optFloat("graphicXOffset", -width / 2.0f);
    float offsetY = style.optFloat("graphicYOffset", -height / 2.0f);
    // See Feature/Vector.js for more information about labels
    String label = style.optString("label");
    String labelAlign = style.optString("labelAlign", "lb");
    /*/*w w w  . j  a  v a2 s .  co m*/
     * Valid values for horizontal alignment: "l"=left, "c"=center, "r"=right. 
     * Valid values for vertical alignment: "t"=top, "m"=middle, "b"=bottom.
     */
    float labelXOffset = style.optFloat("labelXOffset", (float) 0.0);
    float labelYOffset = style.optFloat("labelYOffset", (float) 0.0);
    String fontColor = style.optString("fontColor", "#000000");
    /* Supported itext fonts: COURIER, HELVETICA, TIMES_ROMAN */
    String fontFamily = style.optString("fontFamily", "HELVETICA");
    String fontSize = style.optString("fontSize", "12");
    String fontWeight = style.optString("fontWeight", "normal");

    if (style.optString("externalGraphic") != null) {
        float opacity = style.optFloat("graphicOpacity", style.optFloat("fillOpacity", 1.0f));
        state.setFillOpacity(opacity);
        state.setStrokeOpacity(opacity);
        dc.setGState(state);
        try {
            Image image = PDFUtils.createImage(context, width * f, height * f,
                    new URI(style.getString("externalGraphic")), 0.0f);
            image.setAbsolutePosition((float) coordinate.x + offsetX * f, (float) coordinate.y + offsetY * f);
            dc.addImage(image);
        } catch (BadElementException e) {
            context.addError(e);
        } catch (URISyntaxException e) {
            context.addError(e);
        } catch (DocumentException e) {
            context.addError(e);
        }

    } else if (graphicName != null && !graphicName.equalsIgnoreCase("circle")) {
        PolygonRenderer.applyStyle(context, dc, style, state);
        float[] symbol = SYMBOLS.get(graphicName);
        if (symbol == null) {
            throw new InvalidValueException("graphicName", graphicName);
        }
        dc.setGState(state);
        dc.moveTo((float) coordinate.x + symbol[0] * width * f + offsetX * f,
                (float) coordinate.y + symbol[1] * height * f + offsetY * f);
        for (int i = 2; i < symbol.length - 2; i += 2) {
            dc.lineTo((float) coordinate.x + symbol[i] * width * f + offsetX * f,
                    (float) coordinate.y + symbol[i + 1] * height * f + offsetY * f);

        }
        dc.closePath();
        dc.fillStroke();

    } else if (label != null && label.length() > 0) {
        BaseFont bf = PDFUtils.getBaseFont(fontFamily, fontSize, fontWeight);
        float fontHeight = (float) Double.parseDouble(fontSize.toLowerCase().replaceAll("px", "")) * f;
        dc.setFontAndSize(bf, fontHeight);
        dc.setColorFill(ColorWrapper.convertColor(fontColor));
        state.setFillOpacity((float) 1.0);
        dc.setGState(state);
        dc.beginText();
        dc.setTextMatrix((float) coordinate.x + labelXOffset * f, (float) coordinate.y + labelYOffset * f);
        dc.setGState(state);
        dc.showTextAligned(PDFUtils.getHorizontalAlignment(labelAlign), label,
                (float) coordinate.x + labelXOffset * f,
                (float) coordinate.y + labelYOffset * f - PDFUtils.getVerticalOffset(labelAlign, fontHeight),
                0);
        dc.endText();
    } else {
        PolygonRenderer.applyStyle(context, dc, style, state);
        dc.setGState(state);

        dc.circle((float) coordinate.x, (float) coordinate.y, pointRadius * f);
        dc.fillStroke();
    }
}

From source file:org.mapfish.print.PDFUtils.java

License:Open Source License

/**
 * Gets an iText image with a cache that uses PdfTemplates to re-use the same
 * bitmap content multiple times in order to reduce the file size.
 *///from w  w w .j ava 2 s  .  com
public static Image getImage(RenderingContext context, URI uri, float w, float h)
        throws IOException, DocumentException {
    //Check the image is not already used in the PDF file.
    //
    //This part is not protected against multi-threads... worst case, a single image can
    //be twice in the PDF, if used more than one time. But since only one !map
    //block is dealed with at a time, this should not happen
    Map<URI, PdfTemplate> cache = context.getTemplateCache();
    PdfTemplate template = cache.get(uri);
    if (template == null) {
        Image content = getImageDirect(context, uri);
        content.setAbsolutePosition(0, 0);
        final PdfContentByte dc = context.getDirectContent();
        synchronized (context.getPdfLock()) { //protect against parallel writing on the PDF file
            template = dc.createTemplate(content.getPlainWidth(), content.getPlainHeight());
            template.addImage(content);
        }
        cache.put(uri, template);
    }

    //fix the size/aspect ratio of the image in function of what is specified by the user
    if (w == 0.0f) {
        if (h == 0.0f) {
            w = template.getWidth();
            h = template.getHeight();
        } else {
            w = h / template.getHeight() * template.getWidth();
        }
    } else {
        if (h == 0.0f) {
            h = w / template.getWidth() * template.getHeight();
        }
    }

    final Image result = Image.getInstance(template);
    result.scaleToFit(w, h);
    return result;
}