Example usage for java.awt.image BufferedImage createGraphics

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

Introduction

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

Prototype

public Graphics2D createGraphics() 

Source Link

Document

Creates a Graphics2D , which can be used to draw into this BufferedImage .

Usage

From source file:com.aimluck.eip.fileupload.util.FileuploadUtils.java

/**
 * ?????????//from   w w  w  .ja va  2s.c  om
 * 
 * @param imgfile
 * @param dim
 * @return
 */
public static BufferedImage shrinkImage(BufferedImage imgfile, int width, int height) {

    int iwidth = imgfile.getWidth();
    int iheight = imgfile.getHeight();

    double ratio = Math.min((double) width / (double) iwidth, (double) height / (double) iheight);
    int shrinkedWidth = (int) (iwidth * ratio);
    int shrinkedHeight = (int) (iheight * ratio);

    // ??
    Image targetImage = imgfile.getScaledInstance(shrinkedWidth, shrinkedHeight, Image.SCALE_AREA_AVERAGING);
    BufferedImage tmpImage = new BufferedImage(targetImage.getWidth(null), targetImage.getHeight(null),
            BufferedImage.TYPE_3BYTE_BGR);
    Graphics2D g = tmpImage.createGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, shrinkedWidth, shrinkedHeight);
    g.drawImage(targetImage, 0, 0, null);

    return tmpImage;
}

From source file:fr.msch.wissl.server.Library.java

public static String resizeArtwork(String artPath) throws IOException {
    BufferedImage orig = ImageIO.read(new File(artPath));

    if (orig == null) {
        throw new IOException("Failed to open image");
    }//from   w w  w. j  av  a2  s .  c  o  m
    Image sc = orig.getScaledInstance(70, 70, Image.SCALE_SMOOTH);

    BufferedImage scaled = new BufferedImage(70, 70, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = scaled.createGraphics();
    g.drawImage(sc, 0, 0, 70, 70, null);
    g.dispose();

    File ret = new File(artPath + "_SCALED.jpg");
    ImageIO.write(scaled, "JPG", ret);

    return ret.getAbsolutePath();
}

From source file:com.t3.persistence.PersistenceUtil.java

public static void saveToken(Token token, File file, boolean doWait) throws IOException {
    // Thumbnail//from  w w w  . j av a 2  s  . co m
    BufferedImage image = null;
    if (doWait)
        image = ImageManager.getImageAndWait(token.getImageAssetId());
    else
        image = ImageManager.getImage(token.getImageAssetId());

    Dimension sz = new Dimension(image.getWidth(), image.getHeight());
    SwingUtil.constrainTo(sz, 50);
    BufferedImage thumb = new BufferedImage(sz.width, sz.height, BufferedImage.TRANSLUCENT);
    Graphics2D g = thumb.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.drawImage(image, 0, 0, sz.width, sz.height, null);
    g.dispose();

    PackedFile pakFile = null;
    try {
        pakFile = new PackedFile(file);
        saveAssets(token.getAllImageAssets(), pakFile);
        pakFile.putFile(Token.FILE_THUMBNAIL, ImageUtil.imageToBytes(thumb, "png"));
        pakFile.setContent(token);
        pakFile.save();
    } finally {
        if (pakFile != null)
            pakFile.close();
    }
}

From source file:com.t3.persistence.PersistenceUtil.java

static public void saveCampaignThumbnail(String fileName) {
    BufferedImage screen = TabletopTool.takeMapScreenShot(new PlayerView(TabletopTool.getPlayer().getRole()));
    if (screen == null)
        return;/* www . j ava 2 s . c o m*/

    Dimension imgSize = new Dimension(screen.getWidth(null), screen.getHeight(null));
    SwingUtil.constrainTo(imgSize, 200, 200);

    BufferedImage thumb = new BufferedImage(imgSize.width, imgSize.height, BufferedImage.TYPE_INT_BGR);
    Graphics2D g2d = thumb.createGraphics();
    g2d.drawImage(screen, 0, 0, imgSize.width, imgSize.height, null);
    g2d.dispose();

    File thumbFile = getCampaignThumbnailFile(fileName);

    try {
        ImageIO.write(thumb, "jpg", thumbFile);
    } catch (IOException ioe) {
        TabletopTool.showError("msg.error.failedSaveCampaignPreview", ioe);
    }
}

From source file:com.t3.image.ImageUtil.java

/**
 * Flip the image and return a new image
 * @param direction 0-nothing, 1-horizontal, 2-vertical, 3-both
 * @return/*from  w ww . ja  v a  2s.c o m*/
 */
public static BufferedImage flip(BufferedImage image, int direction) {
    BufferedImage workImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getTransparency());

    boolean flipHorizontal = (direction & 1) == 1;
    boolean flipVertical = (direction & 2) == 2;

    int workW = image.getWidth() * (flipHorizontal ? -1 : 1);
    int workH = image.getHeight() * (flipVertical ? -1 : 1);
    int workX = flipHorizontal ? image.getWidth() : 0;
    int workY = flipVertical ? image.getHeight() : 0;

    Graphics2D wig = workImage.createGraphics();
    wig.drawImage(image, workX, workY, workW, workH, null);
    wig.dispose();

    return workImage;
}

From source file:com.rapidminer.gui.new_plotter.engine.jfreechart.PlotInstanceLegendCreator.java

private static Paint createTransparentCheckeredPaint(Color color, int checkerSize) {
    int s = checkerSize;
    BufferedImage bufferedImage = new BufferedImage(2 * s, 2 * s, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2 = bufferedImage.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, // Anti-alias!
            RenderingHints.VALUE_ANTIALIAS_ON);

    Color c1 = DataStructureUtils.setColorAlpha(color, (int) (color.getAlpha() * .8));
    Color c2 = DataStructureUtils.setColorAlpha(color, (int) (color.getAlpha() * .2));
    g2.setStroke(new BasicStroke(0));
    g2.setPaint(c2);//from  www  .  j av  a  2 s.co m
    g2.setColor(c2);
    g2.fillRect(0, 0, s, s);
    g2.fillRect(s, s, s, s);
    g2.setPaint(c1);
    g2.setColor(c1);
    g2.fillRect(0, s, s, s);
    g2.fillRect(s, 0, s, s);

    // paint with the texturing brush
    Rectangle2D rect = new Rectangle2D.Double(0, 0, 2 * s, 2 * s);
    return new TexturePaint(bufferedImage, rect);
}

From source file:com.xauto.ux.Emf2.java

@SuppressWarnings("deprecation")
    public static void extractPicturesFromDoc(String docName) throws Exception {
        Document doc = new Document(docName + ".docx");
        Integer emfOrWmfIndex = 1;
        Integer pngOrJpegIndex = 100;
        Integer bmpOrPictIndex = 10000;
        Integer otherIndex = 1000;

        String outDir = "out" + File.separator + docName + File.separator;
        FileUtils.forceMkdir(new File(outDir));
        FileWriter html = new FileWriter(outDir + "out.html");
        html.write(//from  w w w  .  j a  v a 2s. c  om
                "<html>\n<head><meta http-equiv=\"x-ua-compatible\" content=\"IE=edge,chrome=1\"></head><body>\n");

        for (AsposeDrawingType type : AsposeDrawingType.values()) {
            Node[] drawArray = doc.getChildNodes(type.code(), true).toArray();
            int index = 0;
            logger.info("type={};count={}", type, drawArray.length);
            for (Node n : drawArray) {
                WordDrawing node = null;
                DrawingML dml = null;
                Shape s = null;
                if (n instanceof Shape) {
                    s = (Shape) n;
                    node = new WordDrawing(s);
                } else if (n instanceof DrawingML) {
                    dml = (DrawingML) n;
                    node = new WordDrawing(dml);
                }

                index++;
                IImageData img = node.getImageData();
                BufferedImage bi = img.toImage();
                AposeWordImageType asposeWordImageType = AposeWordImageType.fromCode(img.getImageType());
                String extn = null;
                String trimmedDrawingName = node.getName().replace(" ", "") + index;
                ImageSize is = img.getImageSize();
                long resolution = 600;
                int scale = 1000;
                Graphics2D gd = bi.createGraphics();
                gd.getClipBounds();
                int jpegQual = 70;
                boolean antiAlias = true;
                boolean highQualityRendering = true;
                try {
                    extn = FileFormatUtil.imageTypeToExtension(img.getImageType());
                } catch (IllegalArgumentException e) {
                    extn = "unknown";
                }

                String drawingName = node.getName();
                if (StringUtils.isBlank(drawingName)) {
                    if (node.getNode() instanceof Shape) {
                        Shape s = (Shape) node.getNode();
                        Node cell = null;
                        Node parent = s.getParentNode();
                        while (parent.getNodeType() != NodeType.ROW) {
                            if (parent.getNodeType() == NodeType.CELL) {
                                cell = parent;
                            }
                            parent = parent.getParentNode();
                        }
                        Row picturesRow = (Row) parent;
                        Row captionsRow = (Row) picturesRow.getPreviousSibling();
                        Node[] currentPicturesRowCells = picturesRow.getChildNodes(NodeType.CELL, true).toArray();
                        int foundIndex = 0;
                        for (Node n : currentPicturesRowCells) {
                            if (n == cell) {
                                break;
                            }
                            foundIndex++;
                        }
                        Cell captionCell = (Cell) captionsRow.getChild(NodeType.CELL, foundIndex, true);
                        StringBuilder sb = new StringBuilder();
                        Paragraph[] ps = captionCell.getParagraphs().toArray();
                        for (Paragraph p : ps) {
                            Run[] rs = p.getRuns().toArray();
                            for (Run r : rs) {
                                r.getDirectRunAttrsCount();
                                sb.append(r.getText());
                            }
                        }
                        drawingName = sb.toString().replace("SEQ Figure \\* ARABIC ", "");
                    }
                }

                logger.debug(
                        "imageType={};name={};hasImage()={};imageByteSize={};isLink={};imageSize.Width={};imageSize.Height={};"
                                + "imageSize.HorRes={};imageSize.VertRes={};imageSize.WPoints={};imageSize.HPoints={};"
                                + "bufferedImageType={}; biHeight={}; biWidth={}; trimmedDrawingName={}; extn={};"
                                + "" + "bufferedImageInfo={};drawInfo={}",
                        asposeWordImageType, drawingName, img.hasImage(),
                        img.getImageBytes() == null ? 0 : img.getImageBytes().length, img.isLink(),
                        is.getWidthPixels(), is.getHeightPixels(), is.getHorizontalResolution(),
                        is.getVerticalResolution(), is.getWidthPoints(), is.getHeightPoints(),
                        AwtImageType.fromCode(bi.getType()), bi.getHeight(), bi.getWidth(), trimmedDrawingName,
                        extn, bi.toString(), node.toString());
                if (StringUtils.isBlank(node.getName())) {
                    if (dml != null) {
                        dml.getParentNode();
                        logger.debug("getAncestor={}", dml.getAncestor(DocumentProperty.class));
                    } else if (s != null) {
                        s.getExpandedRunPr_IInline(54);

                        logger.debug(s.toTxt() + s.getText());
                        @SuppressWarnings("unchecked")
                        NodeCollection<Node> ns = s.getChildNodes();
                        while (ns.iterator().hasNext()) {
                            Node n1 = (Node) ns.iterator().next();
                            n1.getText();
                        }
                        logger.debug("shape={}", s.getAncestor(DocumentProperty.class));
                        s.getParentParagraph();
                    }
                }
                if (asposeWordImageType == AposeWordImageType.UNKNOWN) {
                    otherIndex++;
                    continue;
                }
                if (img == null || asposeWordImageType == AposeWordImageType.NO_IMAGE) {
                    continue;
                }
                if (asposeWordImageType == AposeWordImageType.EMF
                        || asposeWordImageType == AposeWordImageType.WMF) {

                    ShapeRenderer sr = node.getShapeRenderer();
                    img.save(outDir + trimmedDrawingName + extn);
                    PngOptions pngOptions = new PngOptions();
                    if (asposeWordImageType == AposeWordImageType.EMF) {
                        EmfMetafileImage emf = new EmfMetafileImage(outDir + trimmedDrawingName + extn);
                        emf.save(outDir + trimmedDrawingName + "_buffered_emf.png", pngOptions);
                    } else {
                        WmfMetafileImage wmf = new WmfMetafileImage(outDir + trimmedDrawingName + extn);
                        wmf.save(outDir + trimmedDrawingName + "_buffered_emf.png", pngOptions);
                    }

                    trimmedDrawingName += "_" + scale + "_" + resolution + "_" + jpegQual + "_" + antiAlias + "_"
                            + highQualityRendering;
                    ImageSaveOptions pngSave = new ImageSaveOptions(com.aspose.words.SaveFormat.PNG);
                    pngSave.setResolution(resolution);
                    pngSave.setUseHighQualityRendering(highQualityRendering);
                    pngSave.setDmlRenderingMode(DmlRenderingMode.DRAWING_ML);
                    pngSave.setDmlEffectsRenderingMode(DmlEffectsRenderingMode.FINE);
                    pngSave.setUseAntiAliasing(antiAlias);
                    pngSave.setScale((float) scale / 1000);

                    ImageSaveOptions jpgSave = new ImageSaveOptions(SaveFormat.JPEG);
                    jpgSave.setUseHighQualityRendering(true);
                    jpgSave.setResolution(resolution);
                    jpgSave.setJpegQuality(jpegQual);
                    jpgSave.setScale((float) scale / 1000);

                    sr.save(outDir + trimmedDrawingName + ".png", pngSave);
                    BufferedImage savedPNG = ImageIO.read(new File(outDir + trimmedDrawingName + ".png"));
                    BufferedImage resizedFromSaved = Scalr.resize(savedPNG, Method.ULTRA_QUALITY, Mode.FIT_TO_WIDTH,
                            435);
                    BufferedImage resizedFromBi = Scalr.resize(bi, Method.ULTRA_QUALITY, Mode.FIT_TO_WIDTH, 435);
                    ImageIO.write(bi, "png", new File(outDir + trimmedDrawingName + "_buffered.png"));
                    ImageIO.write(resizedFromSaved, "png",
                            new File(outDir + trimmedDrawingName + "_resized_from_saved_scalr_antialias_435.png"));
                    ImageIO.write(resizedFromBi, "png",
                            new File(outDir + trimmedDrawingName + "_resized_from_bi_scalr_antialias_435.png"));
                    //sr.save(outDir+trimmedDrawingName+".jpg", jpgSave);

                    html.write("\t<div>\n\t\t\n\t\t<br>\n\t\t<hr><p align=center>.SVG figure: " + trimmedDrawingName
                            + "</p>\n\t\t<hr>\n\t\t<br>\n\t\t<br>\n\t\t<img src=\"" + trimmedDrawingName
                            + ".svg\" width=\"100%\" />\n\t</div>\n");

                    //convertToSVG(outputDir + docId + "\\", trimmedDrawingName, extn);
                    emfOrWmfIndex++;
                } else if (asposeWordImageType == AposeWordImageType.PNG
                        || asposeWordImageType == AposeWordImageType.JPEG) {
                    ShapeRenderer sr = node.getShapeRenderer();
                    ImageSaveOptions pngSave = new ImageSaveOptions(com.aspose.words.SaveFormat.PNG);
                    pngSave.setResolution(resolution);
                    pngSave.setUseHighQualityRendering(highQualityRendering);
                    pngSave.setDmlRenderingMode(DmlRenderingMode.DRAWING_ML);
                    pngSave.setDmlEffectsRenderingMode(DmlEffectsRenderingMode.FINE);
                    pngSave.setUseAntiAliasing(antiAlias);
                    pngSave.setScale((float) scale / 1000);
                    img.save(outDir + trimmedDrawingName + extn);
                    sr.save(outDir + trimmedDrawingName + "_DIRECT" + extn, pngSave);
                    if (is.getHeightPoints() > 99) {
                        html.write("\t<div>\n\t\t\n\t\t<br>\n\t\t<hr><p align=center>" + extn.toUpperCase()
                                + " figure: " + trimmedDrawingName
                                + "</p>\n\t\t<hr>\n\t\t<br>\n\t\t<br>\n\t\t<img src=\"" + trimmedDrawingName + extn
                                + "\" width=\"100%\" />\n\t</div>\n");
                    }
                    pngOrJpegIndex++;
                } else if (asposeWordImageType == AposeWordImageType.BMP
                        || asposeWordImageType == AposeWordImageType.PICT) {
                    img.save(outDir + bmpOrPictIndex + extn);
                    bmpOrPictIndex++;
                } else {
                    logger.info(
                            "PICT type={}; isLink={}; isLinkOnly={}; imageSize={}; sourceFileName={}; hasImage={}",
                            asposeWordImageType, img.isLink(), img.isLinkOnly(),
                            img.getImageSize().getHorizontalResolution(), img.getSourceFullName(), img.hasImage());
                }
            }
        }
        html.write("</body>\n</html>");
        html.close();
    }

From source file:edu.ku.brc.specify.plugins.ipadexporter.InstitutionConfigDlg.java

public static BufferedImage toBufferedImage(final Image img) {
    if (img instanceof BufferedImage) {
        return (BufferedImage) img;
    }//www .j  a v  a  2 s. c  o  m

    // Create a buffered image with transparency
    BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null),
            BufferedImage.TYPE_INT_ARGB);
    // Draw the image on to the buffered image
    Graphics2D bGr = bimage.createGraphics();
    bGr.drawImage(img, 0, 0, null);
    bGr.dispose();

    // Return the buffered image
    return bimage;
}

From source file:main.java.whiteSocket.Bloop.java

public static BufferedImage createWhiteImage() {
    BufferedImage testOut = new BufferedImage(Bloop.blooprint.getWidth(), Bloop.blooprint.getHeight(),
            BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = testOut.createGraphics();
    graphics.setPaint(Color.white);
    graphics.fillRect(0, 0, testOut.getWidth(), testOut.getHeight());
    return testOut;
}

From source file:cognitivej.vision.overlay.builder.ImageOverlayBuilder.java

@NotNull
private static BufferedImage copy(@NotNull BufferedImage img, int imageType) {
    int width = img.getWidth();
    int height = img.getHeight();

    BufferedImage newImage = new BufferedImage(width, height, imageType);
    Graphics g = newImage.createGraphics();
    g.drawImage(img, 0, 0, null);/*from   ww w.  j  a  v a 2 s . c o  m*/
    g.dispose();

    return newImage;
}