Drawing BufferedImage vs. Graphics2D

Hello everyone,
I've got an app that does the following:
- Reads image data from an input file (24 bit integers)
- Stores the data in a buffered image (literally calls setRGB(...) for each pixel)
- Displays the buffered image on a canvas (JPanel):
getGraphics().drawImage(image, 0, 0, WIDTH, HEIGHT, Color.WHITE, this);
fyi, here is my paintComponent() method:
    public void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D)g;
        g2d.drawImage(image, 0, 0, this);
    }Now that the image is displayed, I want to allow the user to draw (edit) the image and then save the changes to an output file. The drawing occurs in my canvas draw() method. I have a MouseListener and MouseMotionListener that detect mouse events on the canvas. The brushSize and currentColor are already set before draw(...) is called. Here is my draw method:
    protected void draw(Point start) {
        Graphics2D g2d = (Graphics2D)getGraphics();
        g2d.setColor(currentColor);
        int x = start.x - (brushSize/2) + 1;
        int y = start.y - (brushSize/2) + 1;
        g2d.fillOval(x, y, brushSize, brushSize);//maybe I should directly edit my image and call repaint() instead of doing this?
     }Visually, this seems to work. Drawing is displayed on the canvas as expected when the user drags the mouse around. But when I attempt to save the image to a file, I can see that the image is unchanged. Looking at the code, I think that what I need to do is change my draw method so that I actually edit the image (i.e. make changes to my image and then call repaint(), instead of using g2d.fillOval(...)). But I have no idea how to do this!
I want to try:
image.setRGB(startx, starty, width, height, rgbArray, offset, scansize);
but I have no idea what these values should be: rgbArray, offset, scansize
PLEASE advise.....

Hi Markt,
thank you, that helped.
The first line (using the graphics of the image) did allow me to draw to the image which is what I needed.
But when I called the second line:
repaint(0,0,image.getWidth(null),image.getHeight(null));
my whole canvas just went white.
I tried this instead:
getGraphics().drawImage(currentImage, 0, 0, (int)width, (int)height, this);
and it seems to work. So now my drawing problem (as far as drawing to the image) is solved. This has uncovered a new problem...hopefully someone here can help me with this one too.
My app also allows the user to zoom in and zoom out on the image. The zooming functionality (visually) is working. You can zoom in or zoom out as many times as you want - and the image displays properly (and is scrollable). BUT, when zoomed in, the moment you start to draw on the canvas with the mouse, the image reverts back to it's original size (scale of 1). I am pretty sure that this scaling is happening before my draw (the draw does not end up being in the same place as the mouse click).
I put a breakpoint inside my paintComponent(g) method - this method is not being called when the user draws (i.e. clicks the mouse inside the canvas)
I'm posting my code here. I guess I'm either doing something wrong - or forgetting to do something that I SHOULD do. If someone can tell me why my image jumps back to a scale of 1 when the mouse is clicked, I'd really appreciate it!
CanvasDrawingListener.java (implements MouseListener, MouseMotionListener)
        public void mousePressed(MouseEvent e)
            lastPoint = e.getPoint();
            canvas.draw(lastPoint);
* Represents a canvas that displays the image contained in a buffer of 24-bit
* RGB values.  The canvas is initially displayed on a scale of 1.  The scale
* is increased by a factor of zoomFactor each time the image is zoomed in.
* Likewise, the scale is decreased by a factor of zoomFactor each time the image
* is zoomed out.
* Each time the image is zoomed in, the new scale value is placed inside scaleValuesVec.
* This allows the application to keep track of previous scale values so that
* the user can "back out" of the zoomed image.  In other words, if the user
* clicks "zoom in" five times, scaleValuesVec will contain values: 2,3,4,5,6.
* If the user then clicks "zoom out", the n-2 value (in this example, 5)
* is retrieved from the scaleValuesVec and used to scale the image.
public class Canvas extends JPanel{
    //initialize x to -1 so first increment sets it to 0 - drawing starts at x==0
    //y does not get incremented the first time
    BufferedImage origImage = null, currentImage = null;
    private int x = -1, y = 0;
    private boolean imageDisplayed = false;//this flag lets us know when to enable zoom buttons
    private Vector<Double> scaleValuesVec = new Vector<Double>();
    private final double zoomFactor = 1.0; //how much to increase or decrease the scale each time zoom button clicked
    private double scale; //the current scale of the bufferedImage
    private double WIDTH, HEIGHT;
    private int brushSize;
    private Color currentColor = Color.WHITE; //TODO set this same as initial button color
    /** Creates a new instance of Canvas */
    public Canvas() {
        scaleValuesVec.addElement(Double.valueOf(1.0)); //initial zoomFactor
        this.setPreferredSize(new Dimension(298, 310));
        this.setVisible(true);
    public void addListeners(){
        CanvasPropertyChangeListener cpcListener = new CanvasPropertyChangeListener();
        CanvasDrawingListener cdListener = new CanvasDrawingListener();
     * Sets the original size of the image.
    public void setInitialSize(Dimension d){
        WIDTH = d.getWidth();
        HEIGHT = d.getHeight();
        this.setPreferredSize(d);
    public BufferedImage getBufferImage(){
        return currentImage;
     * Reads a 24bit RGB value from buffer24 and registers a pixel of that
     * color to the buffered image that is displayed on the canvas.
     * This is the initial display of the image - only called once, when the
     * input file is opened.
    public void displayBufferedImage(int[] buffer24){
        origImage = new BufferedImage((int)WIDTH, (int)HEIGHT, BufferedImage.TYPE_INT_RGB);
        currentImage = new BufferedImage((int)WIDTH, (int)HEIGHT, BufferedImage.TYPE_INT_RGB);
        //read RGB data into origImage
        for(int i = 0; i < buffer24.length; i++){
            increment();
            origImage.setRGB(x, y, buffer24);
//copy origImage to currentImage (currentImage is the working image)
currentImage.setData(origImage.getData());
this.getGraphics().drawImage(currentImage, 0, 0, (int)WIDTH, (int)HEIGHT, Color.RED, this);
this.setImageDisplayed(true);
* Increments the x and y coordinate so that the next drawn pixel
* will be drawn at the next coordinate. For example, assume the dimension
* of this canvas is 298x310. Pixels will begin drawing in the upper
* left coordinate (0,0), left to right, and increment until the last pixel
* is drawn at (297,309). If the last coordinate drawn was 150,150;
* then this method will increment the coordinate to be 151,150
public void increment(){
if(x == getWidth() && y == getHeight()){
Session.getInstance().getErrorHandler().displayError(ErrorMessage.DRAW_OPERATION_ERROR);
if(x == getWidth() -1){ //reset when x == 255
x = 0;
y++;
}else if(x < getWidth() - 1){
x++; //first increment of x will set x == 0
* Adjusts canvas size to encompass entire scaled image.
public void adjustCanvasSize(double scale){
double newWidth = scale * WIDTH;
double newHeight = scale * HEIGHT;
this.setSize((int)newWidth, (int)newHeight);
this.setPreferredSize(new Dimension((int)newWidth, (int)newHeight));
//repaint();
public void zoomIn(){
scale = ((Double)scaleValuesVec.get(scaleValuesVec.size()-1)) + zoomFactor;
scaleValuesVec.addElement(scale);
adjustCanvasSize(scale);
public void zoomOut(){
if(scaleValuesVec.size() > 1){
scale = getLastScaleValue() - 1;
}else{
System.out.println("Already zoomed out to max!");
adjustCanvasSize(scale);
* Called when frame comes up, anytime repaint() called
* Called when zooming in
* Note: this method is NOT called from draw(Point p)
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.scale(scale, scale);
g2d.drawImage(currentImage, 0, 0, this);
protected void draw(Point start) {
Graphics2D g2d = (Graphics2D)currentImage.createGraphics();
g2d.setColor(currentColor);
int x = start.x - (brushSize/2) + 1;
int y = start.y - (brushSize/2) + 1;
g2d.fillOval(x, y, brushSize, brushSize);
double width = currentImage.getWidth();
double height = currentImage.getHeight();
getGraphics().drawImage(currentImage, 0, 0, (int)width, (int)height, this);
* Removes most recent scale value from the vec and returns it.
public double getLastScaleValue(){
double scale = (Double)scaleValuesVec.elementAt(scaleValuesVec.size()-1);
scaleValuesVec.removeElementAt(scaleValuesVec.size()-1);
return scale;
public boolean isImageDisplayed() {
return imageDisplayed;
* fires a change event so the zoom buttons become enabled
public void setImageDisplayed(boolean imageDisplayed) {
if(imageDisplayed != this.imageDisplayed){
this.imageDisplayed = imageDisplayed;
firePropertyChange("imageDisplayed", !imageDisplayed, imageDisplayed);
public void setBrushSize(int size){
System.out.println("CANVAS BRUSH SIZE IS " + size);
this.brushSize = size;
public void setCurrentColor(Color color){
currentColor = color;
* Compare each pixel in the origImage to the currentImage.
* If pixels have same RGB, write a 0 to outputBuff.
* If they are different, write a 1 to outputBuff.
public byte[] getData(){
//first, scale the currentImage back to 1
adjustCanvasSize(1);
//make sure currentImage is same size as origImage
if(origImage.getWidth()==currentImage.getWidth() && origImage.getHeight() == currentImage.getHeight()){
int width = currentImage.getWidth();
int height = currentImage.getHeight();
byte[] outputBuff = new byte[width*height];
x = -1; y = 0; //reset x and y to beginning of image
for(int i = 0; i < outputBuff.length; i++){
increment();
if(currentImage.getRGB(x,y) == origImage.getRGB(x,y)){
outputBuff[i] = 48; //'0'
}else {
outputBuff[i] = 49;//'1'
return outputBuff;
}else {
return null;
//iterate thru both images and see if all RGB values are the same
public boolean imagesEqual(BufferedImage image1, BufferedImage image2){
if(image1.getWidth()==image2.getWidth() && image1.getHeight() == image2.getHeight()){
int width = image1.getWidth();
int height = image1.getHeight();
int numBytes = width * height;
x = -1; y = 0; //reset x and y to beginning of image
for(int i = 0; i < numBytes; i++){
increment();
if(image1.getRGB(x,y) != image2.getRGB(x,y)){
return false;
}else{
return false;
return true;

Similar Messages

  • Unexpected clipping using draw transform in Graphics2D

    My current project needs to be able to take arbitrary sized images and size them to a fixed size on the screen. It also has to rotate them through 90 degrees.
    I have code to do this which (omitting a few details) looks like this.:
    int dynamicImageWidth = // the actual display width we are after
    int dynamicImageHeight = // the actual display height we are after
    Image img = // .. some source Image outside our control
    Graphics2D g = // .. some Graphics we are drawing to.
    if ( img.getHeight() != dynamicImageHeight || img.getWidth() != dynamicImageWidth ) {
    double sx = (double) dynamicImageWidth / img.getWidth();
    double sy = (double) dynamicImageHeight / img.getHeight();
    g.scale( sx, sy );
    g.rotate( Math.PI * 90.0 / 180.0 );
    g.drawImage( img, 0, -img.getHeight(), null );
    This works just fine when the image is the same size or larger than the display rectangle but when it is smaller I get the right scaling but the output image is is clipped to the source image's size.
    What is actually happening?

    This is much easier if you separate the scaling and rotation operations.
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.imageio.ImageIO;
    import java.io.IOException;
    import javax.swing.*;
    public class ScaleAndRotate extends JPanel
        BufferedImage image;
        final int
            WIDTH  = 120,
            HEIGHT = 160;
        public ScaleAndRotate(BufferedImage image)
            this.image = getScaledImage(image);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            Rectangle2D clip = new Rectangle2D.Double(0, 0, WIDTH, HEIGHT);
            AffineTransform at = AffineTransform.getRotateInstance(Math.PI / 2);
            at.translate(0, - image.getHeight());
            //at.setToIdentity();
            g2.drawRenderedImage( image, at );
            g2.setPaint(Color.red);
            g2.draw(at.createTransformedShape(clip));
            at.setToTranslation(150,150);
            g2.drawRenderedImage( image, at );
            g2.setPaint(Color.blue);
            g2.draw(at.createTransformedShape(clip));
        private BufferedImage getScaledImage(BufferedImage in)
            int w = in.getWidth();
            int h = in.getHeight();
            double scale = getScale(w, h);
            int width  = (int)(scale * w);
            int height = (int)(scale * h);
            int dx = width  > WIDTH  ? width  - WIDTH  : 0;
            int dy = height > HEIGHT ? height - HEIGHT : 0;
            width -= dx;
            height -= dy;
            BufferedImage out = new BufferedImage(width, height, in.getType());
            Graphics2D g2 = out.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            AffineTransform at = AffineTransform.getTranslateInstance(-dx/2, -dy/2);
            at.scale(scale, scale);
            g2.drawImage(in, at, this);
            g2.dispose();
            return out;
        private double getScale(int imageWidth, int imageHeight)
            double sx = (double) WIDTH  / imageWidth;
            double sy = (double) HEIGHT / imageHeight;
            double scale = //Math.max(sx, sy);  // scale to fill
                           Math.min(sx, sy);    // scale to fit
            return scale;
        public static void main(String[] args) throws IOException
            String path = "images/cougar.jpg";       // 195, 296
                          //"images/geek-----.gif";  // 83, 67
            BufferedImage image = ImageIO.read(ScaleAndRotate.class.getResource(path));
            ScaleAndRotate sar = new ScaleAndRotate(image);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(sar);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • BufferedImage doesn't draw every gif

    hi all,
    I create a buffered Image which should show 2 different gifs (not animated). my problem is that it draws only one of them. I don't think that it has to do with the gif itself because I tried the same drawing without buffering and everything could be seen.
    private BufferedImage bufferedBG;
    setBG();
    private void setBG() { 
    Image linieH = getToolkit().getImage(getClass().getResource("img/bg_linieH.gif"));
    Image linieV = getToolkit().getImage(getClass().getResource("img/bg_linieV.gif"));
    setBackground( Color.WHITE );
    bufferedBG = new BufferedImage( 676 + OFFSET_X, 578, BufferedImage.TYPE_INT_ARGB );
    Graphics2D g = bufferedBG.createGraphics();
    g.drawImage(linieH, 100,200, this);
    g.drawImage(linieV, 150,300, this);
    public void paint( Graphics g ) {
    Graphics2D g2 = (Graphics2D) g;
    g2.drawImage( bufferedBG, null, 0, 0 );
    any ideas?
    thanks
    gammloop

    I strongly suspect that what we have here may be confusion about user space and device space..
    The Graphics2D instance in your image class DOES NOT share coords with your paint(Graphics g)
    instance! Its x, y start is 0, 0 and bears no relation to the position on-screen of the component you are
    trying to paint...

  • Draw image in a indexed bufferedimage

    When i draw a image in a indexed bufferedimage the destination image is distorted. As source image i use a 256 color gif image. But when i use a TYPE_INT_RGB bufferedimage it's all good. I don't get it. Here's a is the simple code i'm using.
    Image image = new ImageIcon("E:/Java/MapEdJava/MapEditor/pics/"+ImageName).getImage());
    BufferedImage bi = new BufferedImage(image.getWidth(this),image.getHeight(this) , BufferedImage.TYPE_BYTE_INDEXED);
    Graphics2D g2d = bi.createGraphics();
    g2d.drawImage(image, 0, 0, this);

    First, a plea to all posters: if you write "why does my code do this..." either include a brief program that recreates the problem, or give the url to such code. On one hand, posting a long listing doesn't encourage assistence from the forum -- you should be motivated enough to recreate your problem "in the small". On the other hand, not posting enough information doesn't help either: for example, if a particular image is giving you grief, include its url, or find an image with a publicly-reachable url. [Getting off soapbox :-]
    Here's some quick&dirty code that, perhaps, demonstrates the poster's problem. It features a certain bald, chunky guy (no, not me!)
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class ImageTest extends JComponent {
         public static void main(String[] args) throws java.io.IOException {
              java.net.URL url = new java.net.URL(
    "http://java.sun.com/people/jag/JagWithDukeSmall.gif");
              JFrame frame = new JFrame(url.toString());
              Image image1 = new ImageIcon(url).getImage();
              BufferedImage image2 = javax.imageio.ImageIO.read(url);
              BufferedImage image3 = new BufferedImage(image2.getWidth(),image2.getHeight() ,
                   BufferedImage.TYPE_BYTE_INDEXED);
              System.out.println("image2 colormodel="+image2.getColorModel().getClass().getName());
              System.out.println("image3 colormodel="+image3.getColorModel().getClass().getName());
              Graphics2D g2 = image3.createGraphics();
              g2.drawImage(image1, 0, 0, null);
              frame.getContentPane().add(new ImageTest(image1, image2, image3));
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.show();
         Image im1, im2, im3;
         ImageTest(Image im1, Image im2, Image im3) { //assume loaded into memory
              this.im1 = im1; this.im2 = im2; this.im3 = im3;
         public Dimension getPreferredSize() {
              return new Dimension(3*im1.getWidth(null), im1.getHeight(null));
         protected void paintComponent(Graphics g) {
              g.drawImage(im1, 0, 0, null);
              g.drawImage(im2, im1.getWidth(null), 0, null);
              g.drawImage(im3, 2*im1.getWidth(null), 0, null);
    }Why is the third image grainy? I tried adjusting g2's rendering hints, specifically KEY_COLOR_RENDERING and KEY_DITHERING, but I couldn't see any difference. Perhaps the graininess is because image3 is constructed with (I assume) a generic half-tone(?) IndexColorModel. If you know your image has lots of blues, you could construct an ICM with more blue-tones and pass it to constructor:
    BufferedImage(int width, int height, int imageType, IndexColorModel cm)On the other hand, image2 has an ICM and it looks OK -- why not load images using java.imageio.ImageIO.read()?
    --Paul                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to turn a graphics2D object into a BufferedImage

    Is there a simple way to take a Graphics 2D I have
    drawn and turn it into a BufferedImage?
    MArk

    OK, I understand now. First of all, a subimage has to be rectangular. You can't get a subimage that's an irregular shape. If you want a transparent background, we'll approach that later. First:
    // Create a BufferedImage for your original image.
    BufferedImage wholeImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = offScreen.createGraphics();
    // Set the clip region to draw in.
    g2.setClip(...);
    // Draw your entire picture to the offscreen image.
    g2.draw(...);
    // Now we want a bounding box for your clipped region.
    Rectangle clipRect = g2.getClipBounds();
    // Get a subimage from your original image that contains the clipped region.
    BufferedImage clippedImage = wholeImage.getSubimage(clipRect.getX(), clipRect.getY(), clipRect.getWidth(), clipRect.getHeight());Now you have a subimage that has the proper bounds to contain your clipped image in the smallest rectangle possible. The second image can be written to disk. The TYPE_INT_ARGB implies an alpha channel that gives you a transparent background so there's no bounding "square" wherever you decide to draw your subimage. Does this help?
    Michael Bishop

  • Changing a Graphics2D object into a BufferedImage

    Well subject says it all really. At some point in my code I extract a Graphics2D object from another object, and I'd like to store it as a BufferedImage. The code below does almost what i want, but not quite.
    BufferedImage img;
    GraphicsConfiguration gc = this.getGraphicsConfiguration();
    this.img = gc.createCompatibleImage(getWidth(), getHeight(), BufferedImage.OPAQUE);
    Graphics2D g2d = img.createGraphics();
    This is the only hint I've been finding around the forums, and it works well if you just want to draw new drawings on a BufferedImage. However, I have a Graphics2D object that already contains alot of graphics, and I want to copy this into a BufferedImage. I can't seem to find a way to do this no matter where i look.
    Any help would be appreciated.

    reading through alot of code will be alot more work than a simple explanation of the problemA good SSCCE is many times easier to understand than a description.
    That said, if I understand what you are trying, I assume you have a paintComponent override in nr1 that has a drawImage statement, and you want to obtain a part of that image in nr2 which is in a different class, to a BufferedImage in the same class as nr2.
    If that's it, you can construct a BufferedImage of appropriate size and call the paintComponent method of nr1 with the Graphics reference of the BufferedImage, translated or otherwise transformed if necessary, to paint the panel's painting on the BufferedImage. Something like (in the class containing nr2)
    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bi.createGraphics());
    g.translate(x, y); // optional
    g.setClip(x1, y1, w1, h1); // optional
    nr1.paintComponent(g);Note that you need a reference to panel nr1 in the class containing nr2.
    Now (even if this is not what you needed) which was easier to understand -- the description above or the code? So if that's not it, don't expect anything more without a SSCCE which only demonstrates the problem faced -- not 500 lines of code that have nothing to do with the problem.
    luck, db

  • Drawing transparent pixels into BufferedImage?

    Hi,
    I'm trying to do this:
    1) Create a BufferedImage
    2) Paint its background to black
    3) Paint a rectangle using a fully-transparent color
    4) Output this BufferedImage in the form of a PNG file using ImageIO
    My expectation is for step 3 to paint in "transparent" but what seems to be happening is that Graphics interprets my paint command as "draw nothing, it won't change the image anyway". Or maybe the PNG writer in JDK 1.5 does not actually output transparent pixels? Either way, I'm not getting the results I want. Any ideas?
    Thanks,
    Gili

    one should use Graphics.clearRect() for clearing a regionI'm not so sure about that. The API for clearRect states:
    ...the background color of offscreen images may be system dependent. Applications should use setColor
    followed by fillRect to ensure that an offscreen image is cleared to a specific color.
    So I tried to do as this suggests:
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    public class Test0 {
        public static void main(String[] args) throws IOException {
            int W = 100, H = 100;
            BufferedImage bi = new BufferedImage(W, H, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g = bi.createGraphics();
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, W, H);
            g.setColor(new Color(0,0,0,0));
            g.fillRect(W/4, H/4, W/2, H/2);
            g.dispose();
            ImageIO.write(bi, "png", new File("temp.png"));
    }...and it doesn't work?! I'm thinking this is a bug. What to do? Can't get enough of that Porter-Duff:
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class Test {
        public static void main(String[] args) throws IOException {
            int W = 100, H = 100;
            BufferedImage bi = new BufferedImage(W, H, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g = bi.createGraphics();
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, W, H);
            g.setComposite(AlphaComposite.Clear); //<<---- magic pixie dust
            g.fillRect(W/4, H/4, W/2, H/2);
            g.dispose();
            ImageIO.write(bi, "png", new File("temp.png"));
            JLabel lbl = new JLabel(new ImageIcon(bi));
            lbl.setOpaque(true);
            lbl.setBackground(Color.GREEN);
            JFrame f = new JFrame("Test");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(lbl);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }

  • Drawing colored bufferedImages on greyscale BufferedImages

    I create a BufferedImage from a base black and white image like this:
    image = new ImageIcon(image).getImage();
    BufferedImage bimage =  new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics g = bimage.createGraphics();
    g.drawImage(image, 0, 0, null);Image renders just fine in a JFrame
    I then take a color image (a .png icon file) and run it through the same process (it retains its color when test drawn on a JFrame) and then draw the resulting BufferedImage from the icon file on the original image using the g.draw(BufferedImage) method. This resulting image has the icon on it, but the icon, which was originally in color, is now in greyscale. How do I draw color images on top of black and white images and retain the color in the overlay? I have tried using the ConvertColorOp on the overlay inside the draw call and that does not do anything. Any help is greatly appreciated

    I then take a color image (a .png icon file) and run it through the same process (it retains its color when test drawn on a JFrame) and then draw the resulting BufferedImage from the icon file on the original image using the g.draw(BufferedImage) method. This resulting image has the icon on it, but the icon, which was originally in color, is now in greyscale.This requires an SSCCE. I don't really understand it: you draw colored image #1 onto #2. Then you draw #2 back onto #1, and #1 is now gray? Under normal circumstances this is impossible. But I'm probably just misunderstanding you. Hence the need for an SSCCE.
    How do I draw color images on top of black and white images and retain the color in the overlay?This I can answer: you can't. A black and white image can only contain the colors black and white. You would need to create a new image and draw the black and white one and the colored one onto the new image.

  • How can I make ANY vector  graphics with graphics2D and save on clipboard?

    I am at my wits end here, and need some help. Simply put, I have a program that creates a basic x-y graph, drawn in a jpanel. I want to create the graph as a vector (emf, eps, svg, I don't care anymore, any of them would be good). But, all I get is a jpg or bitmap.
    I tried using the infamous FreeHEP programs, but it won't recognize the output as anything but "image" which means bitmap/jpg.
         The user enters x/y data, clicks a button, which crreates a jpanel thusly:
    public class GraphMaker extends JPanel {
    static BufferedImage image = new BufferedImage(600, 500, BufferedImage.TYPE_INT_ARGB);
    GraphMaker(double[] xVals, double[] yVals, double[] sems){
    setPreferredSize(new Dimension (600,500));     
    symSize = 10;
    XminV = 0;
    XmaxV = 0;
    // code here just converts input x and y's to pixel coordinates, spacing of ticks, etc...
    for (int i =0;i < ArLn; i++){
    gX[i] = xO + (gX[i] * xRat);
    gX[i] -= xStart;
    gY[i] = gY[i] * yRat;
    gY[i] = yEnd - gY;
    semVal[i] = semVal[i]*yRat;
         Ymin = yEnd - (Ymin*yRat);
         Ymax = yEnd - (Ymax*yRat);
    BufferedImage anImage = new BufferedImage(600, 500, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = anImage.createGraphics();
    g2.setBackground(white);
    g2.setColor( Color.WHITE );
    g2.fillRect(0,0,600,500);
    g2.setStroke(stroke);
    // here I use the values to draw lines and circles - nothing spectacular:
              g2.setPaint(Color.blue);
              int ii = 0;
              for ( int j = 0; j < ArLn[ii]; j++ ) {
    g2.fill(new Ellipse2D.Float(LgX[ii][j] - symOffst, gY[ii][j]-symOffst, symSize,symSize));
    g2.draw(new Line2D.Float(LgX[ii][j],(gY[ii][j]-semVal[ii][j]),LgX[ii][j],(gY[ii][j]+semVal[ii][j])));
    g2.draw(new Line2D.Float(LgX[ii][j]-2.0f,(gY[ii][j]-semVal[ii][j]),LgX[ii][j]+2.0f,(gY[ii][j]-semVal[ii][j])));
    g2.draw(new Line2D.Float(LgX[ii][j]-2.0f,(gY[ii][j]+semVal[ii][j]),LgX[ii][j]+2.0f,(gY[ii][j]+semVal[ii][j])));
                        g2.draw(new Line2D.Float(xLoVal[ii],yLoVal[ii],xHiVal[ii],yHiVal[ii]));
    image = anImage;
    And, when the user clicks on the "copy" button, invokes this:
    public class Freep implements Transferable, ClipboardOwner {
         public static final DataFlavor POSTSCRIPT_FLAVOR = new DataFlavor("application/postscript", "Postscript");
         private static DataFlavor[] supportedFlavors = {
              DataFlavor.imageFlavor,
              POSTSCRIPT_FLAVOR,
              DataFlavor.stringFlavor
         private static JPanel chart;
         private int width;
         private int height;
         public Freep(JPanel theGraph, int width, int height) {
              this.theGraph = Graphs;
              this.width = width;
              this.height = height;
    //******This is the key method right here: It is ALWAYS imageFlavor, never anything else. How do I make this an EPS flavor?
         public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
    if (flavor.equals(DataFlavor.imageFlavor)) {
    return GraphMaker.image;
    else if (flavor.equals(POSTSCRIPT_FLAVOR)) {
                   return new ByteArrayInputStream(epsOutputStream().toByteArray());
    else if (flavor.equals(DataFlavor.stringFlavor)) {
                   return epsOutputStream().toString();
              } else{
                   throw new UnsupportedFlavorException(flavor);
         private ByteArrayOutputStream epsOutputStream() throws IOException {
    EPSDocumentGraphics2D g2d = new EPSDocumentGraphics2D(false);
    g2d.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());
    ByteArrayOutputStream out = new ByteArrayOutputStream();
         public DataFlavor[] getTransferDataFlavors() {
              return supportedFlavors;
         public boolean isDataFlavorSupported(DataFlavor flavor) {
              for(DataFlavor f : supportedFlavors) {
                   if (f.equals(flavor))
                        return true;
              return false;
         public void lostOwnership(Clipboard arg, Transferable arg1) {
    The same happens with FreeHEP - I want the flavor to be EMF, but the program sees an image so it is always imageFlavor. I know I am missing something, but what, I don't know.
    thanks for your help.

    I don't think there's a built-in solution. One workaround I've seen is to create a dummy graphics class that overrides the desired drawing functions. Instead of actually drawing pixels, the object writes postscript commands to a buffer. There also seems to be commercial code that does exactly this.

  • JAVA Drawing Graphics Save as JPEG?

    My problem is this, I am trying to save my g2 graphic image to a jpg. This is how I have things setup, I will show code and my thoughts. What I need is help to figure out how I could save seperate .java files graphics g to the jpg format from a JFileChooser in a different .java file.
    HERE IS THE CODE FOR HOW GRAPH IS CREATED. graph.java
    I have a graph I am drawing in a seperate .java file and it is created like this:
    public class graph extends JPanel {
        public static Graphics2D g2;
        final int HPAD = 60, VPAD = 40;
        int[] data;
        Font font;
        public test() {
            data = new int[] {120, 190, 211, 75, 30, 290, 182, 65, 85, 120, 100, 101};
            font = new Font("lucida sans regular", Font.PLAIN, 8);       
            setBackground(Color.white);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setFont(font);
            FontRenderContext frc = g2.getFontRenderContext();
            int w = getWidth();
            int h = getHeight();
            // scales
            float xInc = (w - HPAD - HPAD) / 10f;
            float yInc = (h - 2*VPAD) / 10f;
            int[] dataVals = getDataVals();
            float yScale = dataVals[2] / 10f;
    //        etc... (the rest is just drawing...blah...blah)
    }HERE IS THE CODE FOR HOW MY GRAPH IS DISPLAYED AND TRYING TO BE SAVED. results.java
    The graph I created is then displayed in a JPanel and there is a button in the results window to save the graph results. This is where I am having difficulty as I am trying to save the g2 from graph.java (declared public static...not sure if this a good idea) but anyway I want to save this as a jpg heres the code:
            resultPanel = new JPanel(new PercentLayout());
            graph drawing = new graph();
            resultPanel.add (
                drawing,
                new PercentLayout.Constraint(1,41,49,50));
            resultPanel.add (
                saveButton1,
                new PercentLayout.Constraint(1,94,25,5));
        public void actionPerformed(ActionEvent e) {
            if(e.getSource() == saveButton1) {
                doSaveGraph();
        public void doSaveGraph() {
            JFileChooser fileSaver;
            fileSaver = new JFileChooser(); // The file-opening dialog
            ExampleFileFilter filter = new ExampleFileFilter("jpg");
            filter.setDescription("JPEG Picture File");
            fileSaver.addChoosableFileFilter(filter);
            try {
                if(fileSaver.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                    File f = fileSaver.getSelectedFile();
                    BufferedImage img = new BufferedImage(672,600, BufferedImage.TYPE_INT_RGB);
          // SOMEWHERE IN HERE IS WHERE I NEED TO GRAB G2?  I AM NOT SURE WHAT TO DO HERE
                    //Graphics g = img.getGraphics();
                    //panel.paint(g);
                    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));
                    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(img);
                    param.setQuality(1f, true);
                    encoder.setJPEGEncodeParam(param);
                    encoder.encode(img);
                    System.out.println("It worked");
                else{}
            catch (Exception e) {
                e.printStackTrace();
    ...If you can help me I will be very happy, and give you 10 dukes! LOL and I appreciate the help!

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class SavingGraphics
        public static void main(String[] args)
            GraphicsCreationPanel graphicsPanel = new GraphicsCreationPanel();
            GraphicsSaver saver = new GraphicsSaver(graphicsPanel);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(saver.getUIPanel(), "North");
            f.getContentPane().add(graphicsPanel);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class GraphicsCreationPanel extends JPanel
        String text;
        Font font;
        public GraphicsCreationPanel()
            text = "hello world";
            font = new Font("lucida bright regular", Font.PLAIN, 36);
            setBackground(Color.white);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth();
            int h = getHeight();
            g2.setPaint(Color.blue);
            g2.draw(new Rectangle2D.Double(w/16, h/16, w*7/8, h*7/8));
            g2.setPaint(Color.orange);
            g2.fill(new Ellipse2D.Double(w/12, h/12, w*5/6, h*5/6));
            g2.setPaint(Color.red);
            g2.fill(new Ellipse2D.Double(w/6, h/6, w*2/3, h*2/3));
            g2.setPaint(Color.black);
            g2.setFont(font);
            FontRenderContext frc = g2.getFontRenderContext();
            LineMetrics lm = font.getLineMetrics(text, frc);
            float textWidth = (float)font.getStringBounds(text, frc).getWidth();
            float x = (w - textWidth)/2;
            float y = (h + lm.getHeight())/2 - lm.getDescent();
            g2.drawString(text, x, y);
    class GraphicsSaver
        GraphicsCreationPanel graphicsPanel;
        JFileChooser fileChooser;
        public GraphicsSaver(GraphicsCreationPanel gcp)
            graphicsPanel = gcp;
            fileChooser = new JFileChooser(".");
        private void save()
            if(fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION)
                File file = fileChooser.getSelectedFile();
                String ext = file.getPath().substring(file.getPath().indexOf(".") + 1);
                BufferedImage image = getImage();
                try
                    ImageIO.write(image, ext, file);
                catch(IOException ioe)
                    System.out.println("write: " + ioe.getMessage());
        private BufferedImage getImage()
            int w = graphicsPanel.getWidth();
            int h = graphicsPanel.getHeight();
            BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = bi.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            graphicsPanel.paint(g2);
            g2.dispose();
            return bi;
        public JPanel getUIPanel()
            JButton save = new JButton("save");
            save.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    save();
            JPanel panel = new JPanel();
            panel.add(save);
            return panel;
    }

  • Converting a BufferedImage to an Image

    I have a program with some BufferedImages that the user needs to be able to drag around the screen.
    1) The dragging process is very sluggish when I use BufferedImages, but not when I use normal Images. Is this normal, or is something wrong with my program?
    2) If using Images is the only way to fix this problem, how do I draw my BufferedImages into Images or convert them to Images? They have to start out as BufferedImages so that they can undergo a one-time rescaling operation.

    Where can I find out what a profiler is and how to use one?
    Here is an abbreviated version of the code. A non-buffered Image is available for dragging here, and it too drags sluggishly unless you eliminate the line of code that draws the BufferedImages to the screen. There is probably something else wrong with this program, because at one point dragging the BufferedImages did work well. When the problem appeared I tore my code apart trying to find out what I had messed up, but after reversing all the recent changes I had not eliminated the problem and was left mystified.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.lang.*;
    import java.awt.image.*;
    import java.awt.geom.*;
    public class Hanoi2 extends JFrame implements MouseListener, MouseMotionListener, ActionListener{
         private GraphicsDevice device;
         Landscape panel=new Landscape();
         JMenuBar bar=new JMenuBar();
         JMenu menu1=new JMenu("Game");
         JMenuItem m11=new JMenuItem("New Game");
         JMenuItem m12=new JMenuItem("Save Game");
         JMenuItem m13=new JMenuItem("Load Game");
         JMenuItem m14=new JMenuItem("Exit");
         JMenu menu2=new JMenu("Options");
         JMenu m21=new JMenu("Disk Number");
         JRadioButtonMenuItem sm11=new JRadioButtonMenuItem("4");
         JRadioButtonMenuItem sm12=new JRadioButtonMenuItem("5");
         JRadioButtonMenuItem sm13=new JRadioButtonMenuItem("6");
         JRadioButtonMenuItem sm14=new JRadioButtonMenuItem("7");
         JRadioButtonMenuItem sm15=new JRadioButtonMenuItem("8");
         JRadioButtonMenuItem sm16=new JRadioButtonMenuItem("9");
         JRadioButtonMenuItem sm17=new JRadioButtonMenuItem("10");
         JMenu m22=new JMenu("Disk Set");
         JRadioButtonMenuItem sm21=new JRadioButtonMenuItem("Stone");
         JRadioButtonMenuItem sm22=new JRadioButtonMenuItem("Glass");
         JRadioButtonMenuItem sm23=new JRadioButtonMenuItem("Pattern");
         JMenu m23=new JMenu("Backdrop");
         JRadioButtonMenuItem sm31=new JRadioButtonMenuItem("Spirals");
         JRadioButtonMenuItem sm32=new JRadioButtonMenuItem("Stars");
         JRadioButtonMenuItem sm33=new JRadioButtonMenuItem("Dots and Flowers");
         JRadioButtonMenuItem sm34=new JRadioButtonMenuItem("Psychedelic");
         JRadioButtonMenuItem sm35=new JRadioButtonMenuItem("Smart Sky");
         JMenu menu3=new JMenu("Help");
         JMenuItem m31=new JMenuItem("Instructions");
         JMenuItem m32=new JMenuItem("About");
         int numberdisks=4;
         int numberdisksthisgame=0;
         int diskset=0;
         int backdrop=0;
         boolean isgame=false;
         int[] diskstack={-1,-1,-1};
         int[][] poledisks=new int[3][10];
         Image[] backs=new Image[5];
         Image[][] disks=new Image[3][10];
         Image[] poles=new Image[3];
         Image cloth;
         Image company;
         Image title;
         MediaTracker tracker=new MediaTracker(this);
         int[][] diskspot=new int[2][10];
         BufferedImage[][] disksr=new BufferedImage[3][10];
         Graphics2D[][] disksg=new Graphics2D[3][10];
         BufferedImage[] polesr=new BufferedImage[3];
         Graphics2D[] polesg=new Graphics2D[3];
         boolean goer=false;
         public Hanoi2(GraphicsDevice device){
         super(device.getDefaultConfiguration());
         this.device=device;
         setTitle("Tower of Hanoi");
         setDefaultCloseOperation(EXIT_ON_CLOSE);
         title=Toolkit.getDefaultToolkit().getImage("Hanoi/Title.gif");
         company=Toolkit.getDefaultToolkit().getImage("Hanoi/Company.gif");
         cloth=Toolkit.getDefaultToolkit().getImage("Hanoi/clothspread2.gif");
         poles[0]=Toolkit.getDefaultToolkit().getImage("Hanoi/woodpole1.gif");
         poles[1]=Toolkit.getDefaultToolkit().getImage("Hanoi/woodpole2.gif");
         poles[2]=Toolkit.getDefaultToolkit().getImage("Hanoi/woodpole3.gif");
         backs[0]=Toolkit.getDefaultToolkit().getImage("Hanoi/background1.gif");
         backs[1]=Toolkit.getDefaultToolkit().getImage("Hanoi/background2.gif");
         backs[2]=Toolkit.getDefaultToolkit().getImage("Hanoi/background3.gif");
         backs[3]=Toolkit.getDefaultToolkit().getImage("Hanoi/background4.gif");
         backs[4]=Toolkit.getDefaultToolkit().getImage("Hanoi/background5.gif");
         disks[0][0]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone1.gif");
         disks[0][1]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone2.gif");
         disks[0][2]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone3.gif");
         disks[0][3]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone4.gif");
         disks[0][4]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone5.gif");
         disks[0][5]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone6.gif");
         disks[0][6]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone7.gif");
         disks[0][7]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone8.gif");
         disks[0][8]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone9.gif");
         disks[0][9]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone10.gif");
         disks[1][0]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass1.gif");
         disks[1][1]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass2.gif");
         disks[1][2]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass3.gif");
         disks[1][3]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass4.gif");
         disks[1][4]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass5.gif");
         disks[1][5]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass6.gif");
         disks[1][6]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass7.gif");
         disks[1][7]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass8.gif");
         disks[1][8]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass9.gif");
         disks[1][9]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass10.gif");
         disks[2][0]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve1.gif");
         disks[2][1]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve2.gif");
         disks[2][2]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve3.gif");
         disks[2][3]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve4.gif");
         disks[2][4]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve5.gif");
         disks[2][5]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve6.gif");
         disks[2][6]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve7.gif");
         disks[2][7]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve8.gif");
         disks[2][8]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve9.gif");
         disks[2][9]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve10.gif");
         for(int i=0; i<10; i++){
         tracker.addImage(disks[0], 0);
         tracker.addImage(disks[1][i], 0);
         tracker.addImage(disks[2][i], 0);}
         tracker.addImage(poles[0], 0);
         tracker.addImage(poles[2], 0);
         tracker.addImage(poles[1], 0);
         try{
         tracker.waitForID(0);
         }catch(Exception e){}
         tracker.addImage(title, 0);
         tracker.addImage(company, 0);
         tracker.addImage(backs[0], 0);
         tracker.addImage(backs[1], 0);
         tracker.addImage(backs[2], 0);
         tracker.addImage(backs[3], 0);
         tracker.addImage(backs[4], 0);
         tracker.addImage(cloth, 0);
         for(int i=0; i<3; i++){
         polesr[i]=new BufferedImage(11,350,BufferedImage.TYPE_INT_RGB);
         polesg[i]=polesr[i].createGraphics();}
         for(int v=0; v<3; v++){
         for(int i=0; i<10; i++){
         disksr[v][i]=new BufferedImage(65+i*15,35,BufferedImage.TYPE_INT_RGB);
         disksg[v][i]=disksr[v][i].createGraphics();
         int y=0;
         int z=-75;
         int q=0;
         for(int x=0; x<65+i*15+2; x+=2){
         if(65+i*15<81) q=7;
         if((65+i*15>80)&&(65+i*15<111)) q=6;
         if((65+i*15>110)&&(65+i*15<141)) q=4;
         if((65+i*15>140)&&(65+i*15<186)) q=3;
         if(65+i*15>185) q=2;
         if((x<(65+i*15)/8)||(x>(65+i*15)-((65+i*15)/8))) {q=q+3;}
         else if((x<(65+i*15)/4)||(x>(65+i*15)-((65+i*15)/4))) {q=q+2;}
         else if((x<(65+i*15)/3)||(x>(65+i*15)-((65+i*15)/3))) {q=q+1;}
         if(x<(65+i*15)/4) z+=q;
         if(x>=(65+i*15)/4) z-=q;
         BufferedImage bi=new BufferedImage(65+i*15,35,BufferedImage.TYPE_INT_RGB);
         BufferedImage bi2=new BufferedImage(65+i*15,35,BufferedImage.TYPE_INT_RGB);
         Graphics2D big;
         big=bi.createGraphics();
         big.drawImage(disks[v][i],0,0,this);
         RescaleOp rop = new RescaleOp(1.1f,(float)(z), null);
    rop.filter(bi,bi2);
         Rectangle2D.Double rect=new Rectangle2D.Double(65+i*15-x,0,4,35);
         disksg[v][i].setClip(rect);
         disksg[v][i].drawImage(bi2,0,0,this);}
         if((v==2)&&(i==9))
         goer=true;}}
         setJMenuBar(bar);
         bar.add(menu1);
         bar.add(menu2);
         bar.add(menu3);
         menu1.add(m11);
         menu1.add(m12);
         menu1.add(m13);
         menu1.add(m14);
         menu2.add(m21);
         menu2.add(m22);
         menu2.add(m23);
         m11.addActionListener(this);
         m12.addActionListener(this);
         m13.addActionListener(this);
         m14.addActionListener(this);
         ButtonGroup group1 = new ButtonGroup();
         m21.add(sm11);
         m21.add(sm12);
         m21.add(sm13);
         m21.add(sm14);
         m21.add(sm15);
         m21.add(sm16);
         m21.add(sm17);
         group1.add(sm11);
         group1.add(sm12);
         group1.add(sm13);
         group1.add(sm14);
         group1.add(sm15);
         group1.add(sm16);
         group1.add(sm17);
         sm11.addActionListener(this);
         sm12.addActionListener(this);
         sm13.addActionListener(this);
         sm14.addActionListener(this);
         sm15.addActionListener(this);
         sm16.addActionListener(this);
         sm17.addActionListener(this);
         ButtonGroup group2 = new ButtonGroup();
         m22.add(sm21);
         m22.add(sm22);
         m22.add(sm23);
         group2.add(sm21);
         group2.add(sm22);
         group2.add(sm23);
         sm21.addActionListener(this);
         sm22.addActionListener(this);
         sm23.addActionListener(this);
         ButtonGroup group3 = new ButtonGroup();
         m23.add(sm31);
         m23.add(sm32);
         m23.add(sm33);
         m23.add(sm34);
         m23.add(sm35);
         group3.add(sm31);
         group3.add(sm32);
         group3.add(sm33);
         group3.add(sm34);
         group3.add(sm35);
         sm31.addActionListener(this);
         sm32.addActionListener(this);
         sm33.addActionListener(this);
         sm34.addActionListener(this);
         sm35.addActionListener(this);
         menu3.add(m31);
         menu3.add(m32);
         m31.addActionListener(this);
         m32.addActionListener(this);}
         int placex=0;
         int placey=0;
         class Landscape extends JPanel{
         public void paintComponent(Graphics g){
         super.paintComponent(g);
         Graphics2D g2 = (Graphics2D) g;
         try{
         tracker.waitForAll();
         }catch (InterruptedException exc){}
         if((tracker.checkAll())&&(goer==true)){
         if(isgame==false){
         g.drawImage(title,68,75,this);
         g.drawImage(company,77,250,this);}
         if(isgame==true){
         g.drawImage(backs[backdrop],0,0,this);
         g.drawImage(cloth,0,462,this);
         g.drawImage(disks[0][0],placex,placey,this);
         for(int i=0; i<10; i++){
         g2.drawImage(disksr[diskset][i],diskspot[0][i],diskspot[1][i],this);}}}}}
         public static void main(String[] args){
         try {
    UIManager.setLookAndFeel(
    UIManager.getCrossPlatformLookAndFeelClassName());
    } catch (Exception e) { }
         GraphicsEnvironment env = GraphicsEnvironment.
    getLocalGraphicsEnvironment();
    GraphicsDevice[] devices = env.getScreenDevices();
    for (int i = 0; i < 1 /* devices.length */; i++) {
    Hanoi2 box = new Hanoi2(devices[i]);
    box.initComponents(box.getContentPane());
    box.begin();}}
         private void initComponents(Container c) {
         panel.setBackground(new java.awt.Color(201%256, 27%256, 27%256));
         panel.setPreferredSize(new Dimension(696,500));
         setContentPane(panel);}
         public void setVisible(boolean isVis) {
    super.setVisible(isVis);}
         public void begin() {
         addMouseListener(this);
         addMouseMotionListener(this);
         pack();
         setVisible(true);
         setLocationRelativeTo(null);}
         public void actionPerformed(ActionEvent e) {
         if(e.getSource()==m11){
         isgame=true;
         numberdisksthisgame=numberdisks;
         for(int i=0; i<10; i++){
         diskspot[0][i]=25+(9-i)*7;
         diskspot[1][i]=462-numberdisks*35+i*35;}
         repaint();}
    if(e.getSource()==m14){
         System.exit(0);}}
         boolean[] dragdisk={false,false,false,false,false,false,false,false,false,false};
         boolean[] istop={true,false,false,false,false,false,false,false,false,false};
         int xcheck=0;
         int ycheck=0;
         boolean dragother=false;
         int currentpole=0;
         public void mousePressed(MouseEvent e){
         int y=e.getY()-60;
         if(isgame==true){
         if((e.getX()>placex)&&(e.getX()<placex+65)&&(y>placey)&&(y<placey+35)){
         dragother=true;}
         for(int i=0; i<numberdisksthisgame; i++){
         if((e.getX()>diskspot[0][i])&&(e.getX()<diskspot[0][i]+(65+i*15))&&(y>diskspot[1][i])&&
         (y<diskspot[1][i]+35)){
         dragdisk[i]=true;
         xcheck=e.getX()-diskspot[0][i];
         ycheck=y-diskspot[1][i];}}}}
         boolean down=true;
         public void mouseDragged(MouseEvent e){
         int y=e.getY()-60;
         if(dragother==true){
         placex=e.getX();
         placey=y;
         repaint();}
         for(int i=0; i<numberdisksthisgame; i++){
         if((isgame==true)&&(dragdisk[i]==true)){
         diskspot[1][i]=y-ycheck;
         diskspot[0][i]=e.getX()-xcheck;
         repaint();}}}
         int currentpole2=0;
         int[] diskloca={25,250,475};
         public void mouseReleased(MouseEvent e){
         for(int i=0; i<numberdisksthisgame; i++){
         if(dragdisk[i]==true){
         dragdisk[i]=false;}}}
         public void mouseMoved(MouseEvent e){}
         public void mouseEntered(MouseEvent e){}
         public void mouseExited(MouseEvent e){}
         public void mouseClicked(MouseEvent e){}}

  • I think this is a bug with rendering a string to a graphics2d

    Hiya,
    The following lines of code create the rendering error I am experiencing, to which I have tested on several computers.
    BufferedImage bi=new BufferedImage(100,100,BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d=bi.createGraphics();
    g2d.setColor(new Color(1f,0f,0f,0.5f));
    g2d.fillRect(0,0,100,100);
    RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
    RenderingHints rh=new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    renderingHints.add(rh);
    rh=new RenderingHints(RenderingHints.KEY_ALPHA_INTERPOLATION,RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    renderingHints.add(rh);
    g2d.setRenderingHints(renderingHints);
    g2d.setFont(new Font("Lucida",Font.BOLD,14));
    g2d.setColor(Color.BLACK);
    g2d.drawString("SQOWTGBC",10,30);
    When the destination image has an alpha of 1 the text is rendered with the correct antialiasing. However, in this example where the alpha is 0.5 the text is rendered with unwanted artifacts.
    [http://sphotos-b.ak.fbcdn.net/hphotos-ak-ash4/269344_590137484330481_704825569_n.jpg]
    This image has JPG artifacts but the unwanted rendering artifacts are still visible (ie the brighter edges)
    I am wondering if this is not in fact an error but the intended result. If so, how to I configure the graphics object to render the antialiased text without the artifacts?
    I could not find where to submit a bug on the oracle website for the life of me so maybe if someone would like to explain how this is achieved I will be very grateful.
    Penny
    x
    I have spent several hours trying to find if this has been reported as a bug or if there is a solution posted online but to no avail.
    Edited by: 995038 on Mar 20, 2013 5:32 AM
    Edited by: 995038 on Mar 20, 2013 5:33 AM
    Edited by: 995038 on Mar 20, 2013 5:36 AM

    I have made a work around for the moment.
    This work around uses a BufferedImage to render the antialiased text first which does not create the artefacts and then draw the image of the text to where the text should appear. I dont think this is an acceptable solution because in the case where there could be 1000s of TextLayout objects the increased overhead would be unacceptable.
    private void drawTextLayout(Graphics2D g2d,float x,float _y) {
    Rectangle r=_g2d.getClipBounds();
    bufferG2D.translate(r.x,r.y);
    Composite c=bufferG2D.getComposite();
    bufferG2D.setComposite(clearComposite);
    bufferG2D.fill(r);
    bufferG2D.setComposite(c);
    textLayout.draw(bufferG2D,_x,_y);
    bufferG2D.translate(-r.x,-r.y);
    _g2d.drawImage(buffer,r.x,r.y,null);
    the BufferedImage of bufferG2D would need to be large enough to cater for any size of text to be rendered to which I believe the size should be set to the screen size. This solution requires that there always be a _g2d clip assigned.
    Regards
    Penny

  • How does it work BufferedImage ?

    This code that I have copied from Sun docs examples doesn't
    work.There is a NullPointerException using the buffer...
    Why?
    Thanks in advance,regards Lando.
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    java.lang.NullPointerException
    at sun.java2d.pipe.DrawImage.copyImage(DrawImage.java:48)
    at sun.java2d.pipe.DrawImage.copyImage(DrawImage.java:715)
    at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2782)
    at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2772)
    at APIG2.Viewer.update(Viewer.java:77)
    at APIG2.Viewer.paint(Viewer.java:66)
    at sun.awt.RepaintArea.paint(RepaintArea.java:180)
    at
    sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:260)
    at java.awt.Component.dispatchEventImpl(Component.java:3586)
    at java.awt.Container.dispatchEventImpl(Container.java:1437)
    at java.awt.Window.dispatchEventImpl(Window.java:1566)
    at java.awt.Component.dispatchEvent(Component.java:3367)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:445)
    at
    java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.ja
    va:190)
    at
    java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java
    :144)
    at
    java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at
    java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    package APIG2;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.URL ;
    import java.awt.image.BufferedImage ;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.awt.geom.Rectangle2D;
    import java.io.*;
    public class Viewer extends Frame {
    private Image image;
    BufferedImage buffer;
    public Viewer() {
    try {
    java.net.URL theURL = getClass().getResource("cat.gif");
    image = getToolkit().getImage(theURL);
    } catch (Exception e) {
    e.printStackTrace();
    MediaTracker mediaTracker = new MediaTracker(this);
    mediaTracker.addImage(image, 0);
    try
    mediaTracker.waitForID(0);
    catch (InterruptedException ie)
    System.err.println(ie);
    System.exit(1);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    BufferedImage buffer = new BufferedImage (100,100,
    BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics2D = buffer.createGraphics();
    graphics2D.drawImage(image,0,0,this);
    setTitle("merda");
    setSize(400,300);
    show();
    public void paint(Graphics g) {
    update(g); }
    public void update(Graphics g){
    Graphics2D g2 = (Graphics2D)g;
    g.drawImage(image,0,0,this);
    // Draws the buffered image to the screen.
    g2.drawImage(buffer,100,100,this);
    public static void main(String [] args) {
    new Viewer();

    I've found my fault!

  • Saving the graphics2d to JPEG

    Hi All,
    I need a desperate solution for this problem. I am not able to save the contents of the Graphics2D content into an JPEG/GIF. could you pls tell me where I am going wrong.
    private void pathCoordinates(int iOne, int jOne, int iTwo, int jTwo,
                        double y1Diff, double x1Diff,
                      double y2Diff, double x2Diff,
                     int seriesNum, int activeTime){
       Graphics2D g2d;       
       Point2D vOne1 = at.transform(new Point2D.Double(2*jOne-1,2*iOne-1), null);
        Point2D vOne2 = at.transform(new Point2D.Double(2*jOne+1,2*iOne+1), null);
        Point2D vTwo1 = at.transform(new Point2D.Double(2*jTwo-1,2*iTwo-1), null);
        Point2D vTwo2 = at.transform(new Point2D.Double(2*jTwo+1,2*iTwo+1), null);
        double xOne = Math.floor(Math.min(vOne1.getX(),vOne2.getX()));
        double yOne = Math.floor(Math.min(vOne1.getY(),vOne2.getY()));   
        double xTwo = Math.floor(Math.min(vTwo1.getX(),vTwo2.getX()));
        double yTwo = Math.floor(Math.min(vTwo1.getY(),vTwo2.getY()));
        xOne = xOne + x1Diff + 54;
        yOne = yOne + y1Diff + 54;
        xTwo = xTwo + x2Diff + 54;
        yTwo = yTwo + y2Diff + 54;   
        Point2D.Double p1 = new Point2D.Double(xOne ,yOne );
        Point2D.Double p2 = new Point2D.Double(xTwo ,yTwo );
        debug("X1 = " + xOne + " Y1 = " + yOne  + " X2 = " + xTwo + " Y2 = " + yTwo);
        Shape line = new Line2D.Double(xOne ,yOne, xTwo ,yTwo);
             red = (int) (256 * Math.random());         
         green = (int) (256 * Math.random());          
         blue = (int) (256 * Math.random());          
        g2d = (Graphics2D)this.getGraphics();
        g2d.setPaint(new Color(red,green,blue));   
        g2d.setStroke(new BasicStroke(3));   
        g2d.draw(line);
        drawArrowHeads(yOne ,xOne, yTwo ,xTwo, g2d);
        GraphicsConfiguration gc = g2d.getDeviceConfiguration();
        // I tried this options too.. didnt work. gives me either a white or a
        // Black image.
        //  g2d.setColor(Color.white);
        //  g2d.fillRect(0, 0, width, height);
        BufferedImage image = gc.createCompatibleImage(width,height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.createGraphics();   
        g.setColor(Color.white);
        g.fillRect(0,0,width, height);
        g.dispose();
        try {
            OutputStream out = new BufferedOutputStream(new FileOutputStream("screen.jpg"));
            ImageIO.write(image, "jpeg", out);
        }catch(IOException e){
             debug(e.getLocalizedMessage());
        Timer timer = new Timer();   
        timer.schedule(new TrackingTimerTask(), activeTime);
      }thanks in advance
    Domnic

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.util.Random;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class Dynamics
        public Dynamics()
            DynamicPanel dynamicPanel = new DynamicPanel();
            ImageSupport imageSupport = new ImageSupport(dynamicPanel);
            Updater updater = new Updater(dynamicPanel, imageSupport);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(updater.getUIPanel(), "North");
            f.getContentPane().add(dynamicPanel);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
            dynamicPanel.setImage(imageSupport.createImage());
        public static void main(String[] args)
            new Dynamics();
    class DynamicPanel extends JPanel
        BufferedImage image;
        protected void paintComponent(Graphics g)
            g.drawImage(image, 0, 0, this);
        public void setImage(BufferedImage bi)
            image = bi;
            repaint();
    class Updater
        DynamicPanel dynamicPanel;
        ImageSupport imageSupport;
        Random seed;
        int R;
        BufferedImage image;
        public Updater(DynamicPanel dp, ImageSupport is)
            dynamicPanel = dp;
            imageSupport = is;
            seed = new Random();
            R = 75;
        private void addLine()
            Point p1 = getLocation(0);
            Point p2 = getLocation(0);
            updateImage(new Line2D.Double(p1.x, p1.y, p2.x, p2.y));
        private void addCircle()
            Point p = getLocation(R);
            updateImage(new Ellipse2D.Double(p.x - R/2, p.y - R/2, R, R));
        private void addSquare()
            Point p = getLocation(R);
            updateImage(new Rectangle2D.Double(p.x - R/2, p.y - R/2, R, R));
        private Point getLocation(int pad)
            Point p = new Point();
            p.x = pad/2 + seed.nextInt(imageSupport.bi.getWidth() - pad);
            p.y = pad/2 + seed.nextInt(imageSupport.bi.getHeight() - pad);
            return p;
        private void updateImage(Shape s)
            Graphics2D g2 = imageSupport.bi.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.black);
            g2.draw(s);
            g2.dispose();
            dynamicPanel.repaint();
        public JPanel getUIPanel()
            final JButton
                line   = new JButton("line"),
                circle = new JButton("circle"),
                square = new JButton("square"),
                save   = new JButton("save");
            ActionListener l = new ActionListener()
                public void actionPerformed(ActionEvent e)
                    JButton button = (JButton)e.getSource();
                    if(button == line)
                        addLine();
                    if(button == circle)
                        addCircle();
                    if(button == square)
                        addSquare();
                    if(button == save)
                        imageSupport.save();
                        dynamicPanel.setImage(imageSupport.createImage());
            line.addActionListener(l);
            circle.addActionListener(l);
            square.addActionListener(l);
            save.addActionListener(l);
            JPanel panel = new JPanel();
            panel.add(line);
            panel.add(circle);
            panel.add(square);
            panel.add(save);
            return panel;
    class ImageSupport
        DynamicPanel dynamicPanel;
        BufferedImage bi;
        public ImageSupport(DynamicPanel dp)
            dynamicPanel = dp;
        public BufferedImage createImage()
            int w = dynamicPanel.getWidth();
            int h = dynamicPanel.getHeight();
            bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = bi.createGraphics();
            g2.setPaint(Color.white);
            g2.fillRect(0, 0, w, h);
            g2.dispose();
            return bi;
        public void save()
            try
                ImageIO.write(bi, "jpg", new File("dynamics.jpg"));
            catch(IOException ioe)
                System.err.println("write: " + ioe.getMessage());
    }

  • Draw triangle in console

    How can I draw a triangle or other figures in the console mode?

    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    public class Test {
         public static void main(String args[]) {
              Polygon triangle = new Polygon();
              triangle.addPoint(0,25);
              triangle.addPoint(25,0);
              triangle.addPoint(50,25);
              Rectangle rect = triangle.getBounds();
              BufferedImage img = new BufferedImage(rect.width,rect.height,BufferedImage.TYPE_INT_RGB);
              Graphics2D g = img.createGraphics();
              g.setColor(Color.white);
              g.fill(rect);
              g.setColor(Color.black);
              g.fill(triangle);
              int x,y;
              for (y = 0;y < img.getHeight();y++) {
                   for (x = 0;x < img.getWidth();x++) {
                        if (img.getRGB(x,y) == 0xffffffff) System.out.print(" ");
                        else System.out.print("X");
                   System.out.println("");
    }

Maybe you are looking for

  • Jasper report on HTML when one image loaded from database and for the other

    How to generate jasper report on HTML when one image loaded from database and for the other we give a image path My code ByteArrayOutputStream baos = new ByteArrayOutputStream();           exporter = new JRHtmlExporter();           exporter.setParame

  • Questions about buttons: onRelease and on(release)

    I have been experimenting with buttons lately and am trying to use a function that uses the release mouse event. I was a little confused at first, since I found some tutorials that used onRelease() and some that used on(release) {...can somebody expl

  • What will happen if I accidentally overcharged my iphone?

    I accidentally fell asleep last night with my iphone on the charger. When I woke up in the morning and took it right off. It is working fine but I was just wondering can overcharging your battery ruin or affect your phone in anyway?

  • How i can see the Current Order documents

    Hi Gurus, can any body  tell me how can i see the current order number documents? in T.Code - KONK  i see that the number range status shows current order document number. but i cannt trace where it to see the document? also i check the Order Actual

  • So what's the potential downside to cache clearing?

    I am surprisingly ignorant about this, given that I've been using Macs steadily since 1986 and have actually done a little low-level consulting. I have a ridiculous amount of space being eaten up by cache files on my SSD, almost 7 gigs. I know cachin