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:TextQualityDemoVALUE_TEXT_ANTIALIAS_LCD_HBGR.java

public void paintComponent(Graphics g) {
    Dimension d = this.getSize();
    BufferedImage backBuffer = (BufferedImage) this.createImage(d.width, d.height);
    Graphics2D g2 = backBuffer.createGraphics();

    g2.setColor(Color.WHITE);/*from ww  w .  j a  v a  2  s.  c om*/
    g2.fillRect(0, 0, d.width, d.height);

    g2.setColor(Color.BLACK);
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, hintValue);

    g2.drawRect(0, 0, d.width - 1, d.height - 1);

    g2.drawString("abcdefghijklmnopqrstuvwxyz", 20, 40);
    g2.drawString("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 20, 60);
    g2.drawString("1234567890-=!@#$%^&*()_+,./<>?", 20, 80);

    g.drawImage(backBuffer, 0, 0, this);
}

From source file:ImageComposite.java

public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;

    BufferedImage buffImg = new BufferedImage(200, 100, BufferedImage.TYPE_INT_ARGB);
    Graphics2D gbi = buffImg.createGraphics();

    AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);

    gbi.drawImage(a, 40, 30, null);/* w w w .  j  av a 2  s  . c  om*/
    gbi.setComposite(ac);
    gbi.drawImage(b, 0, 0, null);

    g2d.drawImage(buffImg, 20, 20, null);
}

From source file:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java

/**
 * Rescales using plate intensities and converts to 8bit. Works for gray- and rgb color images.
 *
 * @param bi16/*  ww w  .  j a va 2  s . c om*/
 * @return
 */
public static BufferedImage convertTo8bit(int rdfId, BufferedImage bi16, PlateScalingMin plateScalingMin,
        PlateScalingMax plateScalingMax) throws Exception {
    RawDataFile rdf = DALConfig.getImageProvider().LoadRawDataFile(rdfId);
    /*
    if (plateScalingMin==defaultPlateScalingMin && plateScalingMax==defaultPlateScalingMax) {
        // /orbitvol1/2014-11/4309324.1002.jpg
        String url = RawUtils.STR_SERVER+"/rawFile?rawFile="+rdf.getDataPath()+"/"+rdfId+"."+RawUtils.LEVEL_8BITPREVIEW+".jpg";
        System.out.println("url: " + url);
        return ImageIO.read(new URL(url));
    }
    */

    RawData rd = DALConfig.getImageProvider().LoadRawData(rdf.getRawDataId());
    List<RawMeta> rmList = DALConfig.getImageProvider().LoadRawMetasByRawDataFile(rdfId);
    List<RawMeta> rmDataList = DALConfig.getImageProvider().LoadRawMetasByRawData(rd.getRawDataId());
    rmList.addAll(rmDataList);
    HashMap<String, RawMeta> rmHash = RawUtilsCommon.getHashFromMetaList(rmList);

    if (!rmHash.containsKey(RawUtilsCommon.STR_META_CHANNEL))
        throw new Exception("Error: Meta data 'Channel' not available for RawDataFile " + rdfId);
    //int channel = Integer.parseInt(rmHash.get(RawUtils.STR_META_CHANNEL).getValue()) - 1;
    int channel = Integer.parseInt(rmHash.get(RawUtilsCommon.STR_META_CHANNEL).getValue());
    String metaKey = "Percentiles_wvlength_" + channel + "_channel_0";
    if (!rmHash.containsKey(metaKey))
        throw new Exception("Error: Meta data '" + metaKey + "' not available for RawDataFile " + rdfId);
    String val = rmHash.get(metaKey).getValue();
    int[] minmax = parseMinMax(val, plateScalingMin, plateScalingMax);

    BufferedImage bi = null;
    if (bi16.getSampleModel().getNumBands() == 1) {
        bi16 = ImageUtils.scaleIntensities(bi16, new int[] { minmax[0] }, new int[] { minmax[1] });
        bi = new BufferedImage(bi16.getWidth(), bi16.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
    } else {
        throw new IllegalArgumentException("Only images with 1 band (gray-color) supported. This image has "
                + bi16.getSampleModel().getNumBands() + " bands.");
    }
    Graphics2D g2d = bi.createGraphics();
    g2d.drawImage(bi16, 0, 0, null);
    g2d.dispose();
    return bi;
}

From source file:ImageOpByRomain.java

/**
 * <p>/*from w  ww. ja  v  a 2 s  .  c  om*/
 * Returns a thumbnail of a source image. <code>newSize</code> defines the
 * length of the longest dimension of the thumbnail. The other dimension is
 * then computed according to the dimensions ratio of the original picture.
 * </p>
 * <p>
 * This method offers a good trade-off between speed and quality. The result
 * looks better than
 * {@link #createThumbnailFast(java.awt.image.BufferedImage, int)} when the
 * new size is less than half the longest dimension of the source image, yet
 * the rendering speed is almost similar.
 * </p>
 * 
 * @see #createThumbnailFast(java.awt.image.BufferedImage, int, int)
 * @see #createThumbnailFast(java.awt.image.BufferedImage, int)
 * @see #createThumbnail(java.awt.image.BufferedImage, int, int)
 * @param image
 *            the source image
 * @param newSize
 *            the length of the largest dimension of the thumbnail
 * @return a new compatible <code>BufferedImage</code> containing a
 *         thumbnail of <code>image</code>
 * @throws IllegalArgumentException
 *             if <code>newSize</code> is larger than the largest dimension
 *             of <code>image</code> or &lt;= 0
 */
public static BufferedImage createThumbnail(BufferedImage image, int newSize) {
    int width = image.getWidth();
    int height = image.getHeight();

    boolean isWidthGreater = width > height;

    if (isWidthGreater) {
        if (newSize >= width) {
            throw new IllegalArgumentException("newSize must be lower than" + " the image width");
        }
    } else if (newSize >= height) {
        throw new IllegalArgumentException("newSize must be lower than" + " the image height");
    }

    if (newSize <= 0) {
        throw new IllegalArgumentException("newSize must" + " be greater than 0");
    }

    float ratioWH = (float) width / (float) height;
    float ratioHW = (float) height / (float) width;

    BufferedImage thumb = image;

    do {
        if (isWidthGreater) {
            width /= 2;
            if (width < newSize) {
                width = newSize;
            }
            height = (int) (width / ratioWH);
        } else {
            height /= 2;
            if (height < newSize) {
                height = newSize;
            }
            width = (int) (height / ratioHW);
        }

        BufferedImage temp = createCompatibleImage(image, width, height);
        Graphics2D g2 = temp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(thumb, 0, 0, temp.getWidth(), temp.getHeight(), null);
        g2.dispose();

        thumb = temp;
    } while (newSize != (isWidthGreater ? width : height));

    return thumb;
}

From source file:com.occamlab.te.parsers.ImageParser.java

private static Node processFrame(ImageReader reader, int frame, NodeList nodes, PrintWriter logger)
        throws Exception {
    if (nodes.getLength() == 0) {
        return null;
    }/*from w w  w.j  a v a 2 s. c  o  m*/
    String formatName = reader.getFormatName().toLowerCase(); // 2011-09-08
                                                              // PwD
    BufferedImage image = reader.read(frame);

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // System.out.println(node.getLocalName());
            if (node.getLocalName().equals("type")) {
                node.setTextContent(formatName); // 2011-09-08 PwD was
                                                 // reader.getFormatName().toLowerCase()
            } else if (node.getLocalName().equals("height")) {
                node.setTextContent(Integer.toString(image.getHeight()));
            } else if (node.getLocalName().equals("width")) {
                node.setTextContent(Integer.toString(image.getWidth()));
            } else if (node.getLocalName().equals("metadata")) {
                try { // 2011--08-23 PwD
                    IIOMetadata metadata = reader.getImageMetadata(frame);
                    if (metadata != null) {
                        String format = ((Element) node).getAttribute("format");
                        if (format.length() == 0) {
                            format = metadata.getNativeMetadataFormatName();
                        }
                        Node tree = metadata.getAsTree(format);
                        TransformerFactory tf = TransformerFactory.newInstance();
                        Transformer t = tf.newTransformer();
                        t.transform(new DOMSource(tree), new DOMResult(node));
                    }
                } catch (javax.imageio.IIOException e) { // 2011--08-23 PwD
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    Document doc = db.newDocument();
                    String format = reader.getFormatName().toLowerCase();
                    String formatEltName = "javax_imageio_" + format + "_1.0";
                    Element formatElt = doc.createElement(formatEltName);
                    TransformerFactory tf = TransformerFactory.newInstance();
                    Transformer t = tf.newTransformer();
                    t.transform(new DOMSource(formatElt), new DOMResult(node));
                }
            } else if (node.getLocalName().equals("model")) {
                int imagetype = -1;
                String model = ((Element) node).getAttribute("value");
                if (model.equals("MONOCHROME")) {
                    imagetype = BufferedImage.TYPE_BYTE_BINARY;
                } else if (model.equals("GRAY")) {
                    imagetype = BufferedImage.TYPE_BYTE_GRAY;
                } else if (model.equals("RGB")) {
                    imagetype = BufferedImage.TYPE_3BYTE_BGR;
                } else if (model.equals("ARGB")) {
                    imagetype = BufferedImage.TYPE_4BYTE_ABGR;
                } else {
                    model = "CUSTOM";
                }
                ((Element) node).setAttribute("value", model);
                BufferedImage buffImage = image;
                if (image.getType() != imagetype && imagetype != -1) {
                    buffImage = new BufferedImage(image.getWidth(), image.getHeight(), imagetype);
                    Graphics2D g2 = buffImage.createGraphics();
                    ImageTracker tracker = new ImageTracker();
                    boolean done = g2.drawImage(image, 0, 0, tracker);
                    if (!done) {
                        while (!tracker.done) {
                            sleep(50);
                        }
                    }
                }
                processBufferedImage(buffImage, formatName, node.getChildNodes());
            } else if (node.getLocalName().equals("transparency")) { // 2011-08-24
                                                                     // PwD
                int transparency = image.getTransparency();
                String transparencyName = null;
                switch (transparency) {
                case Transparency.OPAQUE: {
                    transparencyName = "Opaque";
                    break;
                }
                case Transparency.BITMASK: {
                    transparencyName = "Bitmask";
                    break;
                }
                case Transparency.TRANSLUCENT: {
                    transparencyName = "Translucent";
                    break;
                }
                default: {
                    transparencyName = "Unknown";
                }
                }
                node.setTextContent(transparencyName);

            } else if (node.getLocalName().equals("base64Data")) { // 2011-09-08
                                                                   // PwD
                String base64Data = getBase64Data(image, formatName, node);
                node.setTextContent(base64Data);
            } else {
                logger.println("ImageParser Error: Invalid tag " + node.getNodeName());
            }
        }
    }
    return null;
}

From source file:AlphaCompositeSRCOUT.java

public void paint(Graphics g) {
    Graphics2D g2D = (Graphics2D) g;

    int w = getSize().width;
    int h = getSize().height;

    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D big = bi.createGraphics();

    ac = AlphaComposite.getInstance(compositeRule, alphaValue);

    big.setColor(Color.red);//from  w w  w.  j  a v  a2s .  com
    big.drawString("Destination", w / 4, h / 4);
    big.fill(new Ellipse2D.Double(0, h / 3, 2 * w / 3, h / 3));

    big.setColor(Color.blue);
    big.drawString("Source", 3 * w / 4, h / 4);

    big.setComposite(ac);
    big.fill(new Ellipse2D.Double(w / 3, h / 3, 2 * w / 3, h / 3));

    g2D.drawImage(bi, null, 0, 0);
}

From source file:TextureWithBufferedImage.java

public void paint(Graphics g) {
    Graphics2D g2D = (Graphics2D) g;
    Rectangle2D rec1, rec2, rec3, rec4, rec5;
    rec1 = new Rectangle2D.Float(25, 25, 75, 150);
    rec2 = new Rectangle2D.Float(125, 25, 10, 75);
    rec3 = new Rectangle2D.Float(75, 125, 125, 75);
    rec4 = new Rectangle2D.Float(25, 15, 12, 75);
    rec5 = new Rectangle2D.Float(15, 50, 15, 15);

    AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1);
    g2D.setComposite(ac);/*www  .  j a  v a2  s .  c om*/

    g2D.setStroke(new BasicStroke(5.0f));
    g2D.draw(rec1);
    GradientPaint gp = new GradientPaint(125f, 25f, Color.yellow, 225f, 100f, Color.blue);
    g2D.setPaint(gp);
    g2D.fill(rec2);
    BufferedImage bi = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB);
    Graphics2D big = bi.createGraphics();
    big.setColor(Color.magenta);
    big.fillRect(0, 0, 5, 5);
    big.setColor(Color.black);
    big.drawLine(0, 0, 5, 5);
    Rectangle r = new Rectangle(0, 0, 5, 5);
    TexturePaint tp = new TexturePaint(bi, r);

    g2D.setPaint(tp);
    g2D.fill(rec3);
    g2D.setColor(Color.green);
    g2D.fill(rec4);
    g2D.setColor(Color.red);
    g2D.fill(rec5);
}

From source file:net.rptools.maptool.util.PersistenceUtil.java

public static void saveToken(Token token, File file, boolean doWait) throws IOException {
    // Thumbnail/*from   w  w  w.  ja  v  a2  s . c o 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.setProperty(PROP_VERSION, MapTool.getVersion());
        pakFile.save();
    } finally {
        if (pakFile != null)
            pakFile.close();
    }
}

From source file:eu.novait.imageresizer.helpers.ImageConverter.java

public void process() throws IOException {
    BufferedImage inImage = ImageIO.read(this.file);
    double ratio = (double) inImage.getWidth() / (double) inImage.getHeight();
    int w = this.width;
    int h = this.height;
    if (inImage.getWidth() >= inImage.getHeight()) {
        w = this.width;
        h = (int) Math.round(w / ratio);
    } else {/* w ww.j av a2 s .c  o m*/
        h = this.height;
        w = (int) Math.round(ratio * h);
    }
    int type = inImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : inImage.getType();
    BufferedImage outImage = new BufferedImage(w, h, type);
    Graphics2D g = outImage.createGraphics();
    g.drawImage(inImage, 0, 0, w, h, null);
    g.dispose();
    String ext = FilenameUtils.getExtension(this.file.getAbsolutePath());
    String t = "jpg";
    switch (ext) {
    case "png":
        t = "png";
        break;
    }
    ImageIO.write(outImage, t, this.outputfile);
}

From source file:net.rptools.maptool.util.PersistenceUtil.java

static public void saveCampaignThumbnail(String fileName) {
    BufferedImage screen = MapTool.takeMapScreenShot(new PlayerView(MapTool.getPlayer().getRole()));
    if (screen == null)
        return;/*w ww.  ja  va  2  s  .  com*/

    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) {
        MapTool.showError("msg.error.failedSaveCampaignPreview", ioe);
    }
}