Example usage for java.awt.image BufferedImage getGraphics

List of usage examples for java.awt.image BufferedImage getGraphics

Introduction

In this page you can find the example usage for java.awt.image BufferedImage getGraphics.

Prototype

public java.awt.Graphics getGraphics() 

Source Link

Document

This method returns a Graphics2D , but is here for backwards compatibility.

Usage

From source file:ca.sqlpower.wabit.report.ResultSetRendererTest.java

public void testRenderOlapQueryInRsRenderer() throws Exception {

    PlDotIni plIni = new PlDotIni();
    plIni.read(new File("src/test/resources/pl.regression.ini"));
    final Olap4jDataSource ds = plIni.getDataSource("World Facts OLAP Connection", Olap4jDataSource.class);

    final SQLDatabase db = new SQLDatabase(ds.getDataSource());

    final SQLDatabaseMapping dbMapping = new SQLDatabaseMapping() {

        public SQLDatabase getDatabase(JDBCDataSource ds) {
            return db;
        }/*from  w  w  w.  j a  v a2s . co  m*/
    };

    OlapConnectionProvider connectionMapping = new OlapConnectionProvider() {

        public OlapConnection createConnection(Olap4jDataSource dataSource)
                throws SQLException, ClassNotFoundException, NamingException {
            OlapConnectionPool pool = new OlapConnectionPool(ds, dbMapping);
            return pool.getConnection();
        }

        public PreparedOlapStatement createPreparedStatement(Olap4jDataSource dataSource, String mdx,
                SPVariableHelper helper) {
            try {
                OlapConnection conn = createConnection(dataSource);
                return helper.substituteForDb(conn, mdx);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            } catch (NamingException e) {
                throw new RuntimeException(e);
            }
        }

    };

    OlapQuery query = new OlapQuery(null, connectionMapping, "Life Expectancy And GNP Correlation", "GUI Query",
            "LOCALDB", "World", "World Countries", null);

    query.setOlapDataSource(ds);

    String catalogName = query.getCatalogName();
    String schemaName = query.getSchemaName();
    String cubeName = query.getCubeName();

    Catalog catalog;
    try {
        catalog = connectionMapping.createConnection(ds).getCatalogs().get(catalogName);
    } catch (Exception ex) {
        throw new ConversionException("Error connecting to data source " + catalogName + " to get cube", ex);
    }
    Schema schema;
    try {
        schema = catalog.getSchemas().get(schemaName);
        Cube cube = schema.getCubes().get(cubeName);
        query.setCurrentCube(cube, false);

    } catch (OlapException e) {
        throw new ConversionException("The cube could not be retrieved.", e);
    }

    getWorkspace().addOlapQuery(query);
    getWorkspace().addDataSource(query.getOlapDataSource());
    ResultSetRenderer renderer = new ResultSetRenderer(query);
    ContentBox parentCB = new ContentBox();
    parentCB.setContentRenderer(renderer);

    Report report = new Report("report");
    report.getPage().addContentBox(parentCB);
    getWorkspace().addReport(report);

    BufferedImage image = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = (Graphics2D) image.getGraphics();
    renderer.renderReportContent(g, (int) parentCB.getWidth(), (int) parentCB.getHeight(), 1, 1, false,
            new SPVariableHelper(parentCB));
}

From source file:algorithm.QRCodeWatermarking.java

/**
 * Creates a PNG image that contains the QR-code with the information from
 * the payload file. The image has the same name as the payload file.
 * /* ww  w .j a  v a  2  s  .  c  o  m*/
 * @param payload
 * @return qr code as png image file
 * @throws IOException
 */
private File createBarcodeFile(File payload, String imageFormat, String usedMethod) throws IOException {
    // Create restoration metadata only for the payload file to spare space.
    PayloadSegment metadata = new PayloadSegment(payload);
    metadata.addOptionalProperty("usedMethod", usedMethod);
    byte[] payloadSegment = metadata.getPayloadSegmentBytes();
    String barcodeInformation = new String(payloadSegment);
    int size = getQRCodeSize();
    String outputFileName = FilenameUtils.removeExtension(getOutputFileName(payload)) + "." + imageFormat;
    File outputFile = new File(outputFileName);
    Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
    hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
    BitMatrix byteMatrix = encodeWithQRCode(barcodeInformation, hintMap, size);
    if (byteMatrix == null) {
        return null;
    }
    BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
    image.createGraphics();
    Graphics2D graphics = (Graphics2D) image.getGraphics();
    graphics.setColor(Color.WHITE);
    graphics.fillRect(0, 0, size, size);
    graphics.setColor(Color.BLACK);
    for (int x = 0; x < size; x++) {
        for (int y = 0; y < size; y++) {
            if (byteMatrix.get(x, y)) {
                graphics.fillRect(x, y, 1, 1);
            }
        }
    }
    ImageIO.write(image, imageFormat, outputFile);
    return outputFile;
}

From source file:org.openmicroscopy.shoola.agents.imviewer.util.saver.ImgSaver.java

/**
 * Creates a single image./*from w ww  .j  a  v  a 2 s  . c  o  m*/
 * 
 * @param image      The image to create.
 * @param constrain   The constrain indicating to add the scale bar.
 * @param name      The name of the image.
 */
private void writeSingleImage(BufferedImage image, boolean constrain, String name) {
    int width = image.getWidth();
    int h = image.getHeight();
    String v = getUnitBarValue();
    int s = (int) model.getUnitBarSize();

    BufferedImage newImage = new BufferedImage(width, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = (Graphics2D) newImage.getGraphics();
    ImagePaintingFactory.setGraphicRenderingSettings(g2);
    //Paint the original image.
    g2.drawImage(image, null, 0, 0);

    if (constrain)
        ImagePaintingFactory.paintScaleBar(g2, width - s - 10, h - 10, s, v);
    writeImage(newImage, name);
}

From source file:PlatformTest.java

private Shape3D createLabel(String szText, float x, float y, float z) {
    BufferedImage bufferedImage = new BufferedImage(25, 14, BufferedImage.TYPE_INT_RGB);
    Graphics g = bufferedImage.getGraphics();
    g.setColor(Color.white);//from w w w . j a  v a  2s.com
    g.drawString(szText, 2, 12);

    ImageComponent2D imageComponent2D = new ImageComponent2D(ImageComponent2D.FORMAT_RGB, bufferedImage);

    // create the Raster for the image
    javax.media.j3d.Raster renderRaster = new javax.media.j3d.Raster(new Point3f(x, y, z),
            javax.media.j3d.Raster.RASTER_COLOR, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(),
            imageComponent2D, null);

    return new Shape3D(renderRaster);
}

From source file:org.apache.cocoon.reading.RepoImageReader.java

/**
 * @return the time the read source was last modified or 0 if it is not
 *         possible to detect//ww  w.  j  a  va 2 s  .c o m
 */
/*
public long getLastModified() {
if (hasRanges()) {
    // This is a byte range request so we can't use the cache, return null.
    return 0;
}
        
if (quickTest) {
    return inputSource.getLastModified();
}
        
final String systemId = (String) documents.get(request.getRequestURI());
// Note: getURI() might be null in some incomplete implementations
final String sourceURI = inputSource.getURI();
if (systemId == null || (sourceURI != null && sourceURI.equals(systemId))) {
    return inputSource.getLastModified();
}
        
documents.remove(request.getRequestURI());
return 0;
}*/

protected void processStream(InputStream inputStream) throws IOException, ProcessingException {

    if (inputStream != null) {
        if (hasTransform()) {
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("image " + ((width == 0) ? "?" : Integer.toString(width)) + "x"
                        + ((height == 0) ? "?" : Integer.toString(height)) + " expires: " + expires);
            }

            try {
                byte content[] = readFully(inputStream);
                ImageIcon icon = new ImageIcon(content);
                BufferedImage original = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(),
                        BufferedImage.TYPE_INT_RGB);
                BufferedImage currentImage = original;
                currentImage.getGraphics().drawImage(icon.getImage(), 0, 0, null);

                if (width > 0 || height > 0) {
                    double ow = icon.getImage().getWidth(null);
                    double oh = icon.getImage().getHeight(null);

                    if (usePercent) {
                        if (width > 0) {
                            width = Math.round((int) (ow * width) / 100);
                        }
                        if (height > 0) {
                            height = Math.round((int) (oh * height) / 100);
                        }
                    }

                    AffineTransformOp filter = new AffineTransformOp(getTransform(ow, oh, width, height),
                            AffineTransformOp.TYPE_BILINEAR);
                    WritableRaster scaledRaster = filter.createCompatibleDestRaster(currentImage.getRaster());

                    filter.filter(currentImage.getRaster(), scaledRaster);

                    currentImage = new BufferedImage(original.getColorModel(), scaledRaster, true, null);
                }

                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                JPEGEncodeParam p = encoder.getDefaultJPEGEncodeParam(currentImage);
                p.setQuality(this.quality[0], true);
                encoder.setJPEGEncodeParam(p);
                encoder.encode(currentImage);

                out.flush();
            } catch (ImageFormatException e) {
                throw new ProcessingException(
                        "Error reading the image. " + "Note that only JPEG images are currently supported.");
            } finally {
                // Bugzilla Bug 25069, close inputStream in finally block
                // this will close inputStream even if processStream throws
                // an exception
                inputStream.close();
            }
        } else {
            try {
                InputStream is = inputStream;

                long expires = parameters.getParameterAsInteger("expires", -1);
                if (expires > 0) {
                    response.setDateHeader("Expires", System.currentTimeMillis() + expires);
                }
                response.setHeader("Accept-Ranges", "bytes");

                byte[] buffer = new byte[8192];
                int length;
                while ((length = is.read(buffer)) > -1) {
                    out.write(buffer, 0, length);
                }
                is.close();
                out.flush();
            } catch (RuntimeException e) {
                throw e;
            } finally {
                // Bugzilla Bug 25069, close inputStream in finally block
                // this will close inputStream even if processStream throws
                // an exception
                inputStream.close();
            }

        }
    } else {
        throw new IOException("Deals: Problem, resource not found or Repository not working correctly");
    }

}

From source file:com.pronoiahealth.olhie.server.services.BookCoverImageService.java

/**
 * Create a back cover//from  w  w w.j a  va 2  s .  c  om
 * 
 * @param coverId
 * @param titleStr
 * @param textColor
 * @param width
 * @param height
 * @param type
 * @param imgFormat
 * @param macColors
 *            - for PNG images reduce the color palette (must be greater
 *            than 2)
 * @return
 * @throws Exception
 */
public byte[] createBackCover(String coverId, String titleStr, String spineColor, String textColor, int width,
        int height, int type, ImageFormat imgFormat, int maxColors) throws Exception {

    Graphics2D g2D = null;

    try {
        // Front cover first
        // Read in base cover image
        BufferedImage coverImg = Imaging.getBufferedImage(coverMap.get(coverId));

        // Resize cover image to the basic 300 X 400 for front cover
        BufferedImage backCoverImg = resize(coverImg, 300, 400, type);
        g2D = (Graphics2D) backCoverImg.getGraphics();

        // Add title if present
        if (titleStr != null && titleStr.length() > 0) {
            BufferedImage titleTextImg = createText(82, 220, titleStr, textColor, true, backTitleFontMap, type);
            g2D.drawImage(titleTextImg, 40, 35, null);
        }

        // Add spine if present
        if (spineColor != null && spineColor.length() > 0) {
            g2D.setColor(Color.decode(spineColor));
            g2D.fillRect(backCoverImg.getWidth() - 2, 0, 2, backCoverImg.getHeight());
        }

        // If the requested size is not 300X400 convert the image
        BufferedImage outImg = null;
        if (width != 300 || height != 400) {
            outImg = resize(backCoverImg, width, height, type);
        } else {
            outImg = backCoverImg;
        }

        // Do we want a PNG with a fixed number of colors
        if (maxColors >= 2 && imgFormat == ImageFormat.IMAGE_FORMAT_PNG) {
            outImg = ImageUtils.reduce32(outImg, maxColors);
        }

        // Return bytes
        Map<String, Object> params = new HashMap<String, Object>();
        byte[] outBytes = Imaging.writeImageToBytes(outImg, imgFormat, params);
        return outBytes;
    } finally {
        if (g2D != null) {
            g2D.dispose();
        }
    }
}

From source file:ro.finsiel.eunis.admin.EUNISUploadServlet.java

/**
 * This method is used to upload pictures for species/sites within database.
 *
 * @param fileItems/*from   w w  w. j ava2  s .  c o  m*/
 *            FileItems which came form request parsed by the upload method (DiskFileUpload).<br />
 *            Contains information about upload (HTTP FORM headers, parsed as elements).
 * @throws Exception
 *             Is throwed for various reasons: IOException, database down etc.
 */
private void uploadPicture(List fileItems) throws Exception {
    natureObjectInfo = new NatureObjectInfo();
    String filename = "";
    String idObject = "";
    String description = "";
    String natureObjectType = "";
    String source = "";
    String sourceUrl = "";
    String license = "";
    boolean mainPicture = false;
    FileItem uploadedFileItem = null;

    for (int i = 0; i < fileItems.size(); i++) {
        FileItem item = (FileItem) fileItems.get(i);

        if (item.isFormField()) {
            // FORM FIELD
            String fieldName = item.getFieldName();
            String fieldValue = item.getString();

            // Filename
            if (null != fieldName && fieldName.equalsIgnoreCase("filename")) {
                filename = fieldValue;
            }
            // Id object
            if (null != fieldName && fieldName.equalsIgnoreCase("idobject")) {
                idObject = fieldValue;
            }
            // Description
            if (null != fieldName && fieldName.equalsIgnoreCase("description")) {
                description = new String(fieldValue.getBytes("iso-8859-1"), "UTF-8");
            }
            // Nature object type
            if (null != fieldName && fieldName.equalsIgnoreCase("natureobjecttype")) {
                natureObjectType = fieldValue;
            }

            // Main picture
            if (null != fieldName && fieldName.equalsIgnoreCase("main_picture")) {
                mainPicture = true;
            }

            // Source
            if (null != fieldName && fieldName.equalsIgnoreCase("source")) {
                source = new String(fieldValue.getBytes("iso-8859-1"), "UTF-8");
            }

            // Source URL
            if (null != fieldName && fieldName.equalsIgnoreCase("sourceUrl")) {
                sourceUrl = new String(fieldValue.getBytes("iso-8859-1"), "UTF-8");
            }

            // License
            if (null != fieldName && fieldName.equalsIgnoreCase("license")) {
                license = new String(fieldValue.getBytes("iso-8859-1"), "UTF-8");
            }

        } else {
            // / UPLOAD FIELD
            filename = item.getName();
            uploadedFileItem = item;
        }
    }
    String uploadDir = "";

    if (natureObjectType.equalsIgnoreCase("Species")) {
        uploadDir = getServletConfig().getServletContext().getInitParameter("UPLOAD_DIR_PICTURES_SPECIES");
    } else if (natureObjectType.equalsIgnoreCase("Sites")) {
        uploadDir = getServletConfig().getServletContext().getInitParameter("UPLOAD_DIR_PICTURES_SITES");
    } else if (natureObjectType.equalsIgnoreCase("Habitats")) {
        uploadDir = getServletConfig().getServletContext().getInitParameter("UPLOAD_DIR_PICTURES_HABITATS");
    }
    // Save the file in the right dir...
    filename = FileUtils.getRealName(filename);
    String imgName = filename;

    String suffix = imgName.substring(imgName.lastIndexOf("."));

    if (suffix == null || suffix.equals("")
            || (!suffix.equalsIgnoreCase(".jpg") && !suffix.equalsIgnoreCase(".jpeg")
                    && !suffix.equalsIgnoreCase(".gif") && !suffix.equalsIgnoreCase(".png")
                    && !suffix.equalsIgnoreCase(".tif") && !suffix.equalsIgnoreCase(".tiff"))) {
        throw new Exception(
                "File has to be in one of the following formats: jpg, jpeg, gif, png, tif, tiff (case-insensitive)");
    }

    String fname = UniqueID.getUniqueID() + suffix.toLowerCase();

    filename = BASE_DIR + uploadDir + fname;
    // System.out.println("filename = " + filename);
    File file = new File(filename);

    // System.out.println("file = " + file);
    uploadedFileItem.write(file);
    natureObjectInfo.filename = fname;
    natureObjectInfo.description = description;
    natureObjectInfo.idObject = idObject;
    natureObjectInfo.natureObjectType = natureObjectType;
    // Sync the database with the pictures
    String scientificName = null;

    if (natureObjectType.equalsIgnoreCase("Species")) {
        scientificName = PicturesHelper.findSpeciesByIDObject(idObject);
    } else if (natureObjectType.equalsIgnoreCase("Sites")) {
        scientificName = PicturesHelper.findSitesByIDObject(idObject);
    } else if (natureObjectType.equalsIgnoreCase("Habitats")) {
        scientificName = PicturesHelper.findHabitatsByIDObject(idObject);
    }

    Chm62edtNatureObjectPicturePersist pictureObject = new Chm62edtNatureObjectPicturePersist();

    pictureObject.setDescription(description);
    pictureObject.setMainPicture(false);
    pictureObject.setFileName(fname);
    pictureObject.setIdObject(idObject);
    pictureObject.setName(scientificName);
    pictureObject.setNatureObjectType(natureObjectType);
    pictureObject.setSource(source);
    pictureObject.setSourceUrl(sourceUrl);
    pictureObject.setLicense(license);
    new Chm62edtNatureObjectPictureDomain().save(pictureObject);

    String mainPictureFilename = idObject + "_main_picture" + suffix;
    Chm62edtNatureObjectPictureDomain domain = new Chm62edtNatureObjectPictureDomain();
    List<Chm62edtNatureObjectPicturePersist> mainPictures = domain.findWhere(
            " FILE_NAME = '" + mainPictureFilename + "' and MAIN_PIC = 1 and NAME = '" + scientificName + "'");

    if (mainPictures == null || mainPictures.size() == 0) {
        mainPicture = true;
    }

    // processing main picture
    if (mainPicture) {
        BufferedImage image = ImageIO.read(file);
        double ratio = (double) image.getWidth() / (double) image.getHeight();
        double idealRatio = (double) MAX_WIDTH / (double) MAX_HEIGHT;
        int newHeight = 0, newWidth = 0;

        if (ratio > idealRatio) {
            newWidth = Math.min(image.getWidth(), MAX_WIDTH);
            newHeight = (int) (newWidth / ratio);
        } else {
            newHeight = Math.min(image.getHeight(), MAX_HEIGHT);
            newWidth = (int) (newHeight * ratio);
        }

        AffineTransform at = AffineTransform.getScaleInstance((double) newWidth / (double) image.getWidth(),
                (double) newHeight / (double) image.getHeight());
        BufferedImage output = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);

        ((Graphics2D) output.getGraphics()).drawRenderedImage(image, at);

        File outputFile = new File(BASE_DIR + uploadDir + mainPictureFilename);

        ImageIO.write(output, "JPG", outputFile);

        Chm62edtNatureObjectPicturePersist mainPicturePersist = new Chm62edtNatureObjectPicturePersist();

        // delete old mainPictures
        for (Chm62edtNatureObjectPicturePersist mainPic : mainPictures) {
            domain.save(mainPic);
            domain.delete(mainPic);
        }
        // create new one
        mainPicturePersist.setDescription(description);
        mainPicturePersist.setMainPicture(true);
        mainPicturePersist.setFileName(mainPictureFilename);
        mainPicturePersist.setIdObject(idObject);
        mainPicturePersist.setName(scientificName);
        mainPicturePersist.setNatureObjectType(natureObjectType);
        mainPicturePersist.setMaxWidth(new Integer(newWidth));
        mainPicturePersist.setMaxHeight(new Integer(newHeight));
        mainPicturePersist.setSource(source);
        mainPicturePersist.setSourceUrl(sourceUrl);
        mainPicturePersist.setLicense(license);
        domain.save(mainPicturePersist);

    }

}

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. j  a v  a  2 s .c o  m

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

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

From source file:tilt.image.Picture.java

/**
 * Convert from the original png file to greyscale png. Save original.
 * @throws ImageException /*from   ww  w  .  j a v a2s. c om*/
 */
void convertToGreyscale() throws ImageException {
    try {
        BufferedImage png = ImageIO.read(orig);
        BufferedImage grey = new BufferedImage(png.getWidth(), png.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
        Graphics g = grey.getGraphics();
        g.drawImage(png, 0, 0, null);
        g.dispose();
        if (!isWholePicture()) {
            // clear excluded regions
            Graphics2D g2d = grey.createGraphics();
            g2d.setColor(Color.white);
            if (coords[0][0].doubleValue() > 0.0) {
                int w = grey.getWidth();
                int h = grey.getHeight();
                g2d.fillRect(0, 0, getPropVal(coords[0][0], w), h);
            }
            if (coords[1][0].doubleValue() < 100.0) {
                int x = getPropVal(coords[1][0], grey.getWidth());
                g2d.fillRect(x, 0, grey.getWidth() - x, grey.getHeight());
            }
            if (coords[2][1].doubleValue() < 100.0) {
                int y = getPropVal(coords[2][1], grey.getHeight());
                g2d.fillRect(0, y, grey.getWidth(), grey.getHeight() - y);
            }
            if (coords[0][1].doubleValue() > 0.0) {
                int y = getPropVal(coords[0][1], grey.getHeight());
                g2d.fillRect(0, 0, grey.getWidth(), y);
            }
            g2d.dispose();
        }
        greyscale = File.createTempFile(PictureRegistry.PREFIX, PictureRegistry.SUFFIX);
        ImageIO.write(grey, "png", greyscale);
    } catch (Exception e) {
        throw new ImageException(e);
    }
}

From source file:fr.avianey.androidsvgdrawable.SvgDrawablePlugin.java

/**
 * Draw the stretch and content area defined by the {@link NinePatch} around the given image
 * @param is/*  www . j  av a2s.  c  o m*/
 * @param finalName
 * @param ninePatch
 * @param ratio
 * @throws IOException
 */
private void toNinePatch(final InputStream is, final String finalName, final NinePatch ninePatch,
        final double ratio) throws IOException {
    BufferedImage image = ImageIO.read(is);
    final int w = image.getWidth();
    final int h = image.getHeight();
    BufferedImage ninePatchImage = new BufferedImage(w + 2, h + 2, BufferedImage.TYPE_INT_ARGB);
    Graphics g = ninePatchImage.getGraphics();
    g.drawImage(image, 1, 1, null);

    // draw patch
    g.setColor(Color.BLACK);

    Zone stretch = ninePatch.getStretch();
    Zone content = ninePatch.getContent();

    if (stretch.getX() == null) {
        if (getLog().isDebugEnabled()) {
            getLog().debug("+ ninepatch stretch(x) [start=0 - size=" + w + "]");
        }
        g.fillRect(1, 0, w, 1);
    } else {
        for (int[] seg : stretch.getX()) {
            final int start = NinePatch.start(seg[0], seg[1], w, ratio);
            final int size = NinePatch.size(seg[0], seg[1], w, ratio);
            if (getLog().isDebugEnabled()) {
                getLog().debug("+ ninepatch stretch(x) [start=" + start + " - size=" + size + "]");
            }
            g.fillRect(start + 1, 0, size, 1);
        }
    }

    if (stretch.getY() == null) {
        if (getLog().isDebugEnabled()) {
            getLog().debug("+ ninepatch stretch(y) [start=0 - size=" + h + "]");
        }
        g.fillRect(0, 1, 1, h);
    } else {
        for (int[] seg : stretch.getY()) {
            final int start = NinePatch.start(seg[0], seg[1], h, ratio);
            final int size = NinePatch.size(seg[0], seg[1], h, ratio);
            if (getLog().isDebugEnabled()) {
                getLog().debug("+ ninepatch stretch(y) [start=" + start + " - size=" + size + "]");
            }
            g.fillRect(0, start + 1, 1, size);
        }
    }

    if (content.getX() == null) {
        if (getLog().isDebugEnabled()) {
            getLog().debug("+ ninepatch content(x) [start=0 - size=" + w + "]");
        }
        g.fillRect(1, h + 1, w, 1);
    } else {
        for (int[] seg : content.getX()) {
            final int start = NinePatch.start(seg[0], seg[1], w, ratio);
            final int size = NinePatch.size(seg[0], seg[1], w, ratio);
            if (getLog().isDebugEnabled()) {
                getLog().debug("+ ninepatch content(x) [start=" + start + " - size=" + size + "]");
            }
            g.fillRect(start + 1, h + 1, size, 1);
        }
    }

    if (content.getY() == null) {
        if (getLog().isDebugEnabled()) {
            getLog().debug("+ ninepatch content(y) [start=0 - size=" + h + "]");
        }
        g.fillRect(w + 1, 1, 1, h);
    } else {
        for (int[] seg : content.getY()) {
            final int start = NinePatch.start(seg[0], seg[1], h, ratio);
            final int size = NinePatch.size(seg[0], seg[1], h, ratio);
            if (getLog().isDebugEnabled()) {
                getLog().debug("+ ninepatch content(y) [start=" + start + " - size=" + size + "]");
            }
            g.fillRect(w + 1, start + 1, 1, size);
        }
    }

    ImageIO.write(ninePatchImage, "png", new File(finalName));
}