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:fr.ign.cogit.simplu3d.rjmcmc.generic.visitor.FilmVisitor.java

/**
 * Permet d'enregistrer une image  partir de l'cran Ne fonctionne qu'avec
 * l'IHM actuel (Offset ncessaire) Ne prends pas compte de l'existance d'un
 * fichier de mme nom/*from ww w.  j  av a 2 s  .  co  m*/
 * 
 * @param path
 *            le dossier dans lequel l'impr ecran sera supprime
 * @param fileName
 *            le nom du fichier
 * @return indique si la capture s'est effectue avec succs
 */
public boolean screenCapture(String path, String fileName, InterfaceMap3D iMap3D) {

    try {

        ChartPanel v = StatsVisitor.CHARTSINGLETON;

        int xSup = 0;
        int ySup = 0;

        boolean hasStats = (v != null);

        if (hasStats) {

            xSup = v.getSize().width;
            ySup = v.getSize().height;

        }

        int xSize = iMap3D.getSize().width + xSup;
        int ySize = Math.max(iMap3D.getSize().height, ySup);

        BufferedImage bufImage = new BufferedImage(xSize, ySize, BufferedImage.TYPE_INT_RGB);

        Graphics g = bufImage.createGraphics();

        g.setColor(Color.white);

        // g.drawRect(0, 0, xSize, ySize);

        g.fillRect(0, 0, xSize, ySize);

        iMap3D.getCanvas3D().paint(g);

        if (hasStats) {

            g.drawImage(v.getChart().createBufferedImage(xSup, ySup), iMap3D.getSize().width,
                    (ySize - ySup) / 2, null);

        }

        File fichier = new File(path, fileName);
        if (fichier.exists()) {
            System.out.println("Fail");
            return false;
        } else {
            ImageIO.write(bufImage, "jpg", fichier);
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:de.inren.service.picture.PictureModificationServiceImpl.java

private BufferedImage scaleImage(File orginal, final int max) throws IOException {
    // Load the image.
    BufferedImage originalImage = ImageIO.read(orginal);

    // Figure out the new dimensions.
    final int w = originalImage.getWidth();
    final int h = originalImage.getHeight();
    final double maxOriginal = Math.max(w, h);
    final double scaling = max / maxOriginal;

    final int newW = (int) Math.round(scaling * w);
    final int newH = (int) Math.round(scaling * h);

    // If we need to scale down by more than 2x, scale to double the
    // eventual size and then scale again. This provides much higher
    // quality results.
    if (scaling < 0.5f) {
        final BufferedImage newImg = new BufferedImage(newW * 2, newH * 2, BufferedImage.TYPE_INT_RGB);
        final Graphics2D gfx = newImg.createGraphics();
        gfx.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        gfx.drawImage(originalImage, 0, 0, newW * 2, newH * 2, null);
        gfx.dispose();//  w ww . j  a  v  a 2 s. co m
        newImg.flush();
        originalImage = newImg;
    }

    // Scale it.
    BufferedImage newImg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_RGB);
    final Graphics2D gfx = newImg.createGraphics();
    gfx.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    gfx.drawImage(originalImage, 0, 0, newW, newH, null);
    gfx.dispose();
    newImg.flush();
    originalImage.flush();

    return newImg;
}

From source file:com.mikenimer.familydam.services.photos.ThumbnailService.java

/**
 * Resizes an image using a Graphics2D object backed by a BufferedImage.
 * @param src - source image to scale//  w w w .  j a  va 2 s  .  c  om
 * @param w - desired width
 * @param h - desired height
 * @return - the new resized image
 */
private BufferedImage getScaledImage(BufferedImage src, int orientation, int w, int h) throws Exception {
    int finalW = w;
    int finalH = h;

    if (h == -1)
        finalH = w;
    if (w == -1)
        finalW = h;

    double factor = 1.0d;
    if (src.getWidth() > src.getHeight()) {
        factor = ((double) src.getHeight() / (double) src.getWidth());
        finalH = (int) (finalW * factor);
    } else {
        factor = ((double) src.getWidth() / (double) src.getHeight());
        finalW = (int) (finalH * factor);
    }

    BufferedImage scaledImage = new BufferedImage(finalW, finalH, src.getType());
    Graphics2D g = scaledImage.createGraphics();

    try {
        //AffineTransform at = AffineTransform.getScaleInstance((double) finalw / src.getWidth(), (double) finalh/ src.getHeight());
        AffineTransform at = getExifTransformation(orientation, (double) finalW, (double) finalH,
                (double) finalW / src.getWidth(), (double) finalH / src.getHeight());
        return transformImage(src, at);
        //g.drawRenderedImage(src, at);
        //return scaledImage;
    } finally {
        g.dispose();
    }

    /**
    BufferedImage resizedImg = new BufferedImage(finalw, finalh, src.getType());
    Graphics2D g2 = resizedImg.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(src, 0, 0, finalw, finalh, null);
    g2.dispose();
    return resizedImg;
    **/
}

From source file:eu.udig.style.advanced.utils.Utilities.java

/**
 * Creates an image from a set of {@link RuleWrapper}s.
 * /*from w  ww  . j a  v  a2 s .com*/
 * @param ruleWrapperList the list of rule wrappers.
 * @param width the image width.
 * @param height the image height.
 * @return the new created {@link BufferedImage}.
 */
public static BufferedImage pointRulesWrapperToImage(final List<RuleWrapper> ruleWrapperList, int width,
        int height) {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = image.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    for (RuleWrapper ruleWrapper : ruleWrapperList) {
        BufferedImage tmpImage = Utilities.pointRuleWrapperToImage(ruleWrapper, width, height);
        g2d.drawImage(tmpImage, 0, 0, null);
    }
    g2d.dispose();
    return image;
}

From source file:eu.udig.style.advanced.utils.Utilities.java

/**
 * Creates an image from a set of {@link RuleWrapper}s.
 * /*from   www . j ava  2s.c o m*/
 * @param rulesWrapperList the list of rules wrapper.
 * @param width the image width.
 * @param height the image height.
 * @return the new created {@link BufferedImage}.
 */
public static BufferedImage polygonRulesWrapperToImage(final List<RuleWrapper> rulesWrapperList, int width,
        int height) {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = image.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    for (RuleWrapper rule : rulesWrapperList) {
        BufferedImage tmpImage = Utilities.polygonRuleWrapperToImage(rule, width, height);
        g2d.drawImage(tmpImage, 0, 0, null);
    }
    g2d.dispose();
    return image;
}

From source file:eu.udig.style.advanced.utils.Utilities.java

/**
 * Creates an image from a set of {@link RuleWrapper}s.
 * /*  w  w  w  .  jav  a  2  s.c  o m*/
 * @param rulesWrapperList the list of rules wrapper.
 * @param width the image width.
 * @param height the image height.
 * @return the new created {@link BufferedImage}.
 */
public static BufferedImage lineRulesWrapperToImage(final List<RuleWrapper> rulesWrapperList, int width,
        int height) {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = image.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    for (RuleWrapper rule : rulesWrapperList) {
        BufferedImage tmpImage = Utilities.lineRuleWrapperToImage(rule, width, height);
        g2d.drawImage(tmpImage, 0, 0, null);
    }
    g2d.dispose();
    return image;
}

From source file:CompositeEffects.java

/** Draw the example */
public void paint(Graphics g1) {
    Graphics2D g = (Graphics2D) g1;

    // fill the background
    g.setPaint(new Color(175, 175, 175));
    g.fillRect(0, 0, getWidth(), getHeight());

    // Set text attributes
    g.setColor(Color.black);/* w  w  w.  j  a  v a2s .  co m*/
    g.setFont(new Font("SansSerif", Font.BOLD, 12));

    // Draw the unmodified image
    g.translate(10, 10);
    g.drawImage(cover, 0, 0, this);
    g.drawString("SRC_OVER", 0, COVERHEIGHT + 15);

    // Draw the cover again, using AlphaComposite to make the opaque
    // colors of the image 50% translucent
    g.translate(COVERWIDTH + 10, 0);
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
    g.drawImage(cover, 0, 0, this);

    // Restore the pre-defined default Composite for the screen, so
    // opaque colors stay opaque.
    g.setComposite(AlphaComposite.SrcOver);
    // Label the effect
    g.drawString("SRC_OVER, 50%", 0, COVERHEIGHT + 15);

    // Now get an offscreen image to work with. In order to achieve
    // certain compositing effects, the drawing surface must support
    // transparency. Onscreen drawing surfaces cannot, so we have to do the
    // compositing in an offscreen image that is specially created to have
    // an "alpha channel", then copy the final result to the screen.
    BufferedImage offscreen = new BufferedImage(COVERWIDTH, COVERHEIGHT, BufferedImage.TYPE_INT_ARGB);

    // First, fill the image with a color gradient background that varies
    // left-to-right from opaque to transparent yellow
    Graphics2D osg = offscreen.createGraphics();
    osg.setPaint(new GradientPaint(0, 0, Color.yellow, COVERWIDTH, 0, new Color(255, 255, 0, 0)));
    osg.fillRect(0, 0, COVERWIDTH, COVERHEIGHT);

    // Now copy the cover image on top of this, but use the DstOver rule
    // which draws it "underneath" the existing pixels, and allows the
    // image to show depending on the transparency of those pixels.
    osg.setComposite(AlphaComposite.DstOver);
    osg.drawImage(cover, 0, 0, this);

    // And display this composited image on the screen. Note that the
    // image is opaque and that none of the screen background shows through
    g.translate(COVERWIDTH + 10, 0);
    g.drawImage(offscreen, 0, 0, this);
    g.drawString("DST_OVER", 0, COVERHEIGHT + 15);

    // Now start over and do a new effect with the off-screen image.
    // First, fill the offscreen image with a new color gradient. We
    // don't care about the colors themselves; we just want the
    // translucency of the background to vary. We use opaque black to
    // transparent black. Note that since we've already used this offscreen
    // image, we set the composite to Src, we can fill the image and
    // ignore anything that is already there.
    osg.setComposite(AlphaComposite.Src);
    osg.setPaint(new GradientPaint(0, 0, Color.black, COVERWIDTH, COVERHEIGHT, new Color(0, 0, 0, 0)));
    osg.fillRect(0, 0, COVERWIDTH, COVERHEIGHT);

    // Now set the compositing type to SrcIn, so colors come from the
    // source, but translucency comes from the destination
    osg.setComposite(AlphaComposite.SrcIn);

    // Draw our loaded image into the off-screen image, compositing it.
    osg.drawImage(cover, 0, 0, this);

    // And then copy our off-screen image to the screen. Note that the
    // image is translucent and some of the image shows through.
    g.translate(COVERWIDTH + 10, 0);
    g.drawImage(offscreen, 0, 0, this);
    g.drawString("SRC_IN", 0, COVERHEIGHT + 15);

    // If we do the same thing but use SrcOut, then the resulting image
    // will have the inverted translucency values of the destination
    osg.setComposite(AlphaComposite.Src);
    osg.setPaint(new GradientPaint(0, 0, Color.black, COVERWIDTH, COVERHEIGHT, new Color(0, 0, 0, 0)));
    osg.fillRect(0, 0, COVERWIDTH, COVERHEIGHT);
    osg.setComposite(AlphaComposite.SrcOut);
    osg.drawImage(cover, 0, 0, this);
    g.translate(COVERWIDTH + 10, 0);
    g.drawImage(offscreen, 0, 0, this);
    g.drawString("SRC_OUT", 0, COVERHEIGHT + 15);

    // Here's a cool effect; it has nothing to do with compositing, but
    // uses an arbitrary shape to clip the image. It uses Area to combine
    // shapes into more complicated ones.
    g.translate(COVERWIDTH + 10, 0);
    Shape savedClip = g.getClip(); // Save current clipping region
    // Create a shape to use as the new clipping region.
    // Begin with an ellipse
    Area clip = new Area(new Ellipse2D.Float(0, 0, COVERWIDTH, COVERHEIGHT));
    // Intersect with a rectangle, truncating the ellipse.
    clip.intersect(new Area(new Rectangle(5, 5, COVERWIDTH - 10, COVERHEIGHT - 10)));
    // Then subtract an ellipse from the bottom of the truncated ellipse.
    clip.subtract(new Area(new Ellipse2D.Float(COVERWIDTH / 2 - 40, COVERHEIGHT - 20, 80, 40)));
    // Use the resulting shape as the new clipping region
    g.clip(clip);
    // Then draw the image through this clipping region
    g.drawImage(cover, 0, 0, this);
    // Restore the old clipping region so we can label the effect
    g.setClip(savedClip);
    g.drawString("Clipping", 0, COVERHEIGHT + 15);
}

From source file:com.chiorichan.factory.event.PostImageProcessor.java

@EventHandler()
public void onEvent(PostEvalEvent event) {
    try {//from ww w. jav  a 2 s .c om
        if (event.context().contentType() == null
                || !event.context().contentType().toLowerCase().startsWith("image"))
            return;

        float x = -1;
        float y = -1;

        boolean cacheEnabled = AppConfig.get().getBoolean("advanced.processors.imageProcessorCache", true);
        boolean grayscale = false;

        ScriptingContext context = event.context();
        HttpRequestWrapper request = context.request();
        Map<String, String> rewrite = request.getRewriteMap();

        if (rewrite != null) {
            if (rewrite.get("serverSideOptions") != null) {
                String[] params = rewrite.get("serverSideOptions").trim().split("_");

                for (String p : params)
                    if (p.toLowerCase().startsWith("width") && x < 0)
                        x = Integer.parseInt(p.substring(5));
                    else if ((p.toLowerCase().startsWith("x") || p.toLowerCase().startsWith("w"))
                            && p.length() > 1 && x < 0)
                        x = Integer.parseInt(p.substring(1));
                    else if (p.toLowerCase().startsWith("height") && y < 0)
                        y = Integer.parseInt(p.substring(6));
                    else if ((p.toLowerCase().startsWith("y") || p.toLowerCase().startsWith("h"))
                            && p.length() > 1 && y < 0)
                        y = Integer.parseInt(p.substring(1));
                    else if (p.toLowerCase().equals("thumb")) {
                        x = 150;
                        y = 0;
                        break;
                    } else if (p.toLowerCase().equals("bw") || p.toLowerCase().equals("grayscale"))
                        grayscale = true;
            }

            if (request.getArgument("width") != null && request.getArgument("width").length() > 0)
                x = request.getArgumentInt("width");

            if (request.getArgument("height") != null && request.getArgument("height").length() > 0)
                y = request.getArgumentInt("height");

            if (request.getArgument("w") != null && request.getArgument("w").length() > 0)
                x = request.getArgumentInt("w");

            if (request.getArgument("h") != null && request.getArgument("h").length() > 0)
                y = request.getArgumentInt("h");

            if (request.getArgument("thumb") != null) {
                x = 150;
                y = 0;
            }

            if (request.hasArgument("bw") || request.hasArgument("grayscale"))
                grayscale = true;
        }

        // Tests if our Post Processor can process the current image.
        List<String> readerFormats = Arrays.asList(ImageIO.getReaderFormatNames());
        List<String> writerFormats = Arrays.asList(ImageIO.getWriterFormatNames());
        if (context.contentType() != null
                && !readerFormats.contains(context.contentType().split("/")[1].toLowerCase()))
            return;

        int inx = event.context().buffer().readerIndex();
        BufferedImage img = ImageIO.read(new ByteBufInputStream(event.context().buffer()));
        event.context().buffer().readerIndex(inx);

        if (img == null)
            return;

        float w = img.getWidth();
        float h = img.getHeight();
        float w1 = w;
        float h1 = h;

        if (x < 1 && y < 1) {
            x = w;
            y = h;
        } else if (x > 0 && y < 1) {
            w1 = x;
            h1 = x * (h / w);
        } else if (y > 0 && x < 1) {
            w1 = y * (w / h);
            h1 = y;
        } else if (x > 0 && y > 0) {
            w1 = x;
            h1 = y;
        }

        boolean resize = w1 > 0 && h1 > 0 && w1 != w && h1 != h;
        boolean argb = request.hasArgument("argb") && request.getArgument("argb").length() == 8;

        if (!resize && !argb && !grayscale)
            return;

        // Produce a unique encapsulated id based on this image processing request
        String encapId = SecureFunc.md5(context.filename() + w1 + h1 + request.getArgument("argb") + grayscale);
        File tmp = context.site() == null ? AppConfig.get().getDirectoryCache()
                : context.site().directoryTemp();
        File file = new File(tmp, encapId + "_" + new File(context.filename()).getName());

        if (cacheEnabled && file.exists()) {
            event.context().resetAndWrite(FileUtils.readFileToByteArray(file));
            return;
        }

        Image image = resize ? img.getScaledInstance(Math.round(w1), Math.round(h1),
                AppConfig.get().getBoolean("advanced.processors.useFastGraphics", true) ? Image.SCALE_FAST
                        : Image.SCALE_SMOOTH)
                : img;

        // TODO Report malformed parameters to user

        if (argb) {
            FilteredImageSource filteredSrc = new FilteredImageSource(image.getSource(),
                    new RGBColorFilter((int) Long.parseLong(request.getArgument("argb"), 16)));
            image = Toolkit.getDefaultToolkit().createImage(filteredSrc);
        }

        BufferedImage rtn = new BufferedImage(Math.round(w1), Math.round(h1), img.getType());
        Graphics2D graphics = rtn.createGraphics();
        graphics.drawImage(image, 0, 0, null);
        graphics.dispose();

        if (grayscale) {
            ColorConvertOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
            op.filter(rtn, rtn);
        }

        if (resize)
            Log.get().info(EnumColor.GRAY + "Resized image from " + Math.round(w) + "px by " + Math.round(h)
                    + "px to " + Math.round(w1) + "px by " + Math.round(h1) + "px");

        if (rtn != null) {
            ByteArrayOutputStream bs = new ByteArrayOutputStream();

            if (context.contentType() != null
                    && writerFormats.contains(context.contentType().split("/")[1].toLowerCase()))
                ImageIO.write(rtn, context.contentType().split("/")[1].toLowerCase(), bs);
            else
                ImageIO.write(rtn, "png", bs);

            if (cacheEnabled && !file.exists())
                FileUtils.writeByteArrayToFile(file, bs.toByteArray());

            event.context().resetAndWrite(bs.toByteArray());
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }

    return;
}

From source file:com.devbury.mkremote.server.QuickLaunchServiceImpl.java

public ArrayList<LaunchItem> list(String dir) {
    Base64 base64 = new Base64();
    JFileChooser chooser = new JFileChooser();
    File new_dir = newFileDir(dir);
    logger.debug("Looking for files in {}", new_dir.getAbsolutePath());
    ArrayList<LaunchItem> items = new ArrayList<LaunchItem>();
    if (isSupported()) {
        if (new_dir.isDirectory()) {
            FilenameFilter filter = new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return !name.startsWith(".");
                }/*from w w  w.  ja  v a2  s . c o m*/
            };
            for (File f : new_dir.listFiles(filter)) {
                if (!f.isHidden()) {
                    LaunchItem item = new LaunchItem();
                    item.setName(f.getName());
                    item.setPath(dir);
                    if (f.isDirectory()) {
                        if (isMac() && f.getName().endsWith(".app")) {
                            item.setType(LaunchItem.FILE_TYPE);
                            item.setName(f.getName().substring(0, f.getName().length() - 4));
                        } else {
                            item.setType(LaunchItem.DIR_TYPE);
                        }
                    } else {
                        item.setType(LaunchItem.FILE_TYPE);
                    }
                    Icon icon = chooser.getIcon(f);
                    BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(),
                            BufferedImage.TYPE_INT_RGB);
                    icon.paintIcon(null, bi.createGraphics(), 0, 0);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    try {
                        ImageIO.write(bi, "png", os);
                        item.setIcon(base64.encodeToString(os.toByteArray()));
                    } catch (IOException e) {
                        logger.debug("could not write image {}", e);
                        item.setIcon(null);
                    }
                    logger.debug("Adding LaunchItem : {}", item);
                    items.add(item);
                } else {
                    logger.debug("Skipping hidden file {}", f.getName());
                }
            }
        }
    } else {
        new Thread() {
            @Override
            public void run() {
                JOptionPane.showMessageDialog(null,
                        "We are sorry but quick launch is not supported on your platform",
                        "Quick Launch Not Supported", JOptionPane.ERROR_MESSAGE);
            }
        }.start();
    }
    return items;
}

From source file:fungus.JungVisualizer.java

public void saveAsPNG() {

    String filePath = String.format("%s/%s-%03d.png", imageDir, nameFragment, CDState.getCycle());

    File dir = new File(imageDir);
    dir.mkdir();/*from  w ww.ja v  a2 s  .c  o m*/

    Dimension size = visualizer.getSize();
    BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    visualizer.paint(g2);

    try {
        File file = new File(filePath);
        ImageIO.write(image, "png", file);
    } catch (Exception e) {
        System.out.println(e);
    }
}