Re-editing a BufferedImage

Hello,
I am creating a program that uses buffered images with part of the image transparent and part of it solid.
What I need to do, is define an image with solid and transparent areas and then later, re-edit the image so that I can define new transparent and solid areas.
Here is what I am trying to do.
BufferedImage bi = new BufferedImage(100,100,BufferedImage.TYPE_INT_ARGB);
Graphics g = bufferedImage.getGraphics();
g.setColor(Color.white);
g.fillRect(0,0,100,100); // Trying to set the image blank
g.setColor(new Color(1f,0f,0f,0f)); // Transparent Color
g.fillRect(0,0,100,100);When I attempt to clear the image by painting a white rectangle followed by a drawing another rectangle using the transparent color,
the solid color is still shown.
How do I completly clear the image?
Thanks
Andrew

Hi there,
As regards getting the image as a component, I haven't
had much success - so am trying another route.Define "much success" - can't you use the library to display PDFs ?
BufferedImage out = new BufferedImage(250, 250,
BufferedImage.TYPE_INT_RGB);
Graphics g2d = out.getGraphics();
g2d.drawBytes(bytes, 0, 0, 250, 250);...
Does this image gets black ? To be quite honest, the code does not makes too much sense for me. It seems you're getting the bytes from the PDF file (which are coded in PDF) and dumping them on the buffered image (which expects RGB triplets, I guess). How/where is the conversion/rendering code ?
Rafael

Similar Messages

  • Need help: BufferedImage and zooming

    please help me understand what i am doing wrong. i am having a hard time understanding the concept behind BufferedImage and zooming. the applet code loads an image as its background. after loading, you can draw line segments on it. but when i try to zoom in, the image in the background remains the same in terms of size, line segments are the only ones that are being zoomed, and the mouse coordinates are confusing.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.imageio.*;
    import java.io.*;
    import java.util.ArrayList;
    import java.io.IOException;
    import java.net.URL;
    import java.awt.image.*;
    public class Testing extends JApplet {
         private String url;
         private Map map;
         public void init() {
         public void start()
              url = "http://localhost/image.gif";
                  map = new Map(url);
                 getContentPane().add(map, "Center");
                 validate();
                 map.validate();
    class Map extends JPanel implements MouseListener, MouseMotionListener{
         private Image image;
         private ArrayList<Point2D> points;
         private ArrayList<Line2D> lineSegment;
         private Point2D startingPoint;
         private int mouseX;
         private int mouseY;
         private BufferedImage bimg;
         private AffineTransform xform;
         private AffineTransform inverse;
         private double zoomFactor = 1;
         public Map(String url)
                         super();
              //this.image = image;
              try
                   image = ImageIO.read(new URL(url));
              catch(Exception e)
              Insets insets = getInsets();
              xform = AffineTransform.getTranslateInstance(insets.left, insets.top);
              xform.scale(zoomFactor,zoomFactor);
              try {
                   inverse = xform.createInverse();
              } catch (NoninvertibleTransformException e) {
                   System.out.println(e);
              points = new ArrayList();
              startingPoint = new Point();
              bimg = new BufferedImage(this.image.getWidth(this), this.image.getHeight(this), BufferedImage.TYPE_INT_ARGB);
              repaintBImg();
              addMouseListener(this);
              addMouseMotionListener(this);
         public void paintComponent(Graphics g)
            Graphics2D g2d = (Graphics2D)g;
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING , RenderingHints.VALUE_RENDER_QUALITY ));
            bimg = (BufferedImage)image;
            g2d.drawRenderedImage(bimg, xform);
            if(!points.isEmpty())
                 for(int i=0; i<points.size(); i++)
                      if(i > 0)
                           drawLineSegment(g2d,points.get(i-1),points.get(i));
                      drawPoint(g2d, points.get(i));
            if(startingPoint != null)
                drawTempLine(startingPoint, g2d);
            else
                mouseX = 0;
                mouseY = 0;
         private void repaintBImg()
              bimg.flush();
              Graphics2D g2d = bimg.createGraphics();
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING , RenderingHints.VALUE_RENDER_QUALITY ));
            g2d.drawRenderedImage(bimg, xform);
            g2d.dispose();
         private void drawPoint(Graphics2D g2d, Point2D p)
            int x = (int)(p.getX() * zoomFactor);
            int y = (int)(p.getY() * zoomFactor);
            int w = (int)(13 * zoomFactor);
            int h = (int)(13 * zoomFactor);
              g2d.setColor(Color.ORANGE);
              g2d.setStroke(new BasicStroke(1.0F));
            g2d.fillOval(x - w / 2, y - h / 2, w, h);
            g2d.setColor(Color.BLACK);
            g2d.drawOval(x - w / 2, y - h / 2, w - 1, h - 1);
         private void drawLineSegment(Graphics2D g2d, Point2D p1, Point2D p2)
              double x1 = p1.getX() * zoomFactor;
                 double y1 = p1.getY() * zoomFactor;
                 double x2 = p2.getX() * zoomFactor;
                 double y2 = p2.getY() * zoomFactor;
                 g2d.setColor(Color.RED);
                 g2d.setStroke(new BasicStroke(3.0F));
                 g2d.draw(new java.awt.geom.Line2D.Double(x1, y1, x2, y2));
             private void drawTempLine(Point2D p, Graphics2D g2d)
                 int startX = (int)(p.getX() * zoomFactor);
                 int startY = (int)(p.getY() * zoomFactor);
                 if(mouseX != 0 && mouseY != 0)
                         g2d.setColor(Color.RED);
                          g2d.setStroke(new BasicStroke(2.0F));
                          g2d.drawLine(startX, startY, mouseX, mouseY);
         public void mouseClicked(MouseEvent e)
         public void mouseDragged(MouseEvent e)
              mouseX = (int)(e.getX()*zoomFactor);
              mouseY = (int)(e.getY()*zoomFactor);
              repaint();
         public void mousePressed(MouseEvent e)
              if(e.getButton() == 1)
                   points.add(inverse.transform(e.getPoint(), null));
                   if(points.size() > 0)
                        startingPoint = points.get(points.size()-1);
                        mouseX = mouseY = 0;
                   repaint();
              else if(e.getButton() == 2)
                   zoomFactor = zoomFactor + .05;
                   repaintBImg();
              else if(e.getButton() == 3)
                   zoomFactor = zoomFactor - .05;
                   repaintBImg();
         public void mouseReleased(MouseEvent e)
              if(e.getButton() == 1)
                   points.add(inverse.transform(e.getPoint(), null));
              repaint();
         public void mouseEntered(MouseEvent mouseevent)
         public void mouseExited(MouseEvent mouseevent)
         public void mouseMoved(MouseEvent mouseevent)
    }Message was edited by:
    hardc0d3r

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.awt.geom.*;
    import java.io.*;
    import java.net.URL;
    import java.util.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class ZoomTesting extends JApplet {
        public void init() {
            //String dir = "file:/" + System.getProperty("user.dir");
            //System.out.printf("dir = %s%n", dir);
            String url = "http://localhost/image.gif";
                         //dir + "/images/cougar.jpg";
            MapPanel map = new MapPanel(url);
            getContentPane().add(map, "Center");
        public static void main(String[] args) {
            JApplet applet = new ZoomTesting();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(applet);
            f.setSize(400,400);
            f.setLocation(200,200);
            applet.init();
            f.setVisible(true);
    class MapPanel extends JPanel implements MouseListener, MouseMotionListener {
        private BufferedImage image;
        private ArrayList<Point2D> points;
        private Point2D startingPoint;
        private int mouseX;
        private int mouseY;
        private AffineTransform xform;
        private AffineTransform inverse;
        RenderingHints hints;
        private double zoomFactor = 1;
        public MapPanel(String url) {
            super();
            try {
                image = ImageIO.read(new URL(url));
            } catch(Exception e) {
                System.out.println(e.getClass().getName() +
                                   " = " + e.getMessage());
            Map<RenderingHints.Key, Object> map =
                        new HashMap<RenderingHints.Key, Object>();
            map.put(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            map.put(RenderingHints.KEY_RENDERING,
                    RenderingHints.VALUE_RENDER_QUALITY);
            hints = new RenderingHints(map);
            setTransforms();
            points = new ArrayList<Point2D>();
            startingPoint = new Point();
            addMouseListener(this);
            addMouseMotionListener(this);
        private void setTransforms() {
            Insets insets = getInsets();
            xform = AffineTransform.getTranslateInstance(insets.left, insets.top);
            xform.scale(zoomFactor,zoomFactor);
            try {
                inverse = xform.createInverse();
            } catch (NoninvertibleTransformException e) {
                System.out.println(e);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D)g;
            g2d.setRenderingHints(hints);
            g2d.drawRenderedImage(image, xform);
            if(!points.isEmpty()) {
                for(int i=0; i<points.size(); i++) {
                    if(i > 0)
                        drawLineSegment(g2d,points.get(i-1),points.get(i));
                    drawPoint(g2d, points.get(i));
            if(startingPoint != null) {
                drawTempLine(startingPoint, g2d);
            } else {
                mouseX = 0;
                mouseY = 0;
        private void drawPoint(Graphics2D g2d, Point2D p) {
            int x = (int)(p.getX() * zoomFactor);
            int y = (int)(p.getY() * zoomFactor);
            int w = (int)(13 * zoomFactor);
            int h = (int)(13 * zoomFactor);
            g2d.setColor(Color.ORANGE);
            g2d.setStroke(new BasicStroke(1.0F));
            g2d.fillOval(x - w / 2, y - h / 2, w, h);
            g2d.setColor(Color.BLACK);
            g2d.drawOval(x - w / 2, y - h / 2, w - 1, h - 1);
        private void drawLineSegment(Graphics2D g2d, Point2D p1, Point2D p2) {
            double x1 = p1.getX() * zoomFactor;
            double y1 = p1.getY() * zoomFactor;
            double x2 = p2.getX() * zoomFactor;
            double y2 = p2.getY() * zoomFactor;
            g2d.setColor(Color.RED);
            g2d.setStroke(new BasicStroke(3.0F));
            g2d.draw(new java.awt.geom.Line2D.Double(x1, y1, x2, y2));
        private void drawTempLine(Point2D p, Graphics2D g2d) {
            int startX = (int)(p.getX() * zoomFactor);
            int startY = (int)(p.getY() * zoomFactor);
            if(mouseX != 0 && mouseY != 0) {
                g2d.setColor(Color.RED);
                g2d.setStroke(new BasicStroke(2.0F));
                g2d.drawLine(startX, startY, mouseX, mouseY);
        public void mouseClicked(MouseEvent e) {}
        public void mouseDragged(MouseEvent e) {
            mouseX = (int)(e.getX()*zoomFactor);
            mouseY = (int)(e.getY()*zoomFactor);
            repaint();
        public void mousePressed(MouseEvent e) {
            if(e.getButton() == 1) {
                points.add(inverse.transform(e.getPoint(), null));
                if(points.size() > 0) {
                    startingPoint = points.get(points.size()-1);
                    mouseX = mouseY = 0;
            } else if(e.getButton() == 2) {
                zoomFactor = zoomFactor + .05;
                setTransforms();
            } else if(e.getButton() == 3) {
                zoomFactor = zoomFactor - .05;
                setTransforms();
            repaint();
        public void mouseReleased(MouseEvent e) {
            if(e.getButton() == 1) {
                points.add(inverse.transform(e.getPoint(), null));
            repaint();
        public void mouseEntered(MouseEvent mouseevent) {}
        public void mouseExited(MouseEvent mouseevent) {}
        public void mouseMoved(MouseEvent mouseevent) {}
    }

  • How can I make a BufferedImage out of packed and non-packed int pixels?

    Hi all,
    I'm trying to turn a byte array of pixels into an int array, then into a buffered Image. In addition to the pixels, I've also got the color (and alpha) masks, width, height, and bit depth of the image. My problem is that the bits per pixel can change, the individual bytes cannot contain the pixels, and many times an int is not fully utilized to store an entire pixel (16bit pixels, for example). When I attempt to create a WritableRaster with a DataBufferInt, I get errors that I don't get if I re-package the 16bit pixels in a short[], (using DataBufferUShort). I don't want to have to do this, since it means reprocessing the entire array yet another time. One last thing. I've already got a working method for "up-converting" the int[] to 32bit pixels, though I'd love to see somebody else's attempt at this if they'd like to share. Mostly, I'm just looking for a way to use the data I have to create a BufferedImage that preserves the data type of the data. Here's some of the code I'm using now. (The byte array may contain MIPmaps, so that's the reason for the imgIndex...)
    <edit> Sorry, I also don't want to have to use the switch (or if...else) statements. I'm looking for a way to use the info I have to write one piece of code that will work for all the data types...</edit>
    private static int[] get8888(byte[] pixels, int format, int width, int height, int imgIndex) {
       int[] pixels8888 = new int[width * height / (int)Math.pow(4, imgIndex)];
       int offset = 0;
       for(int i = 0; i < imgIndex; i++) {
          offset += (width * height) / (int)Math.pow(4, i);
       switch(format) {
          case TYPE_A8R8G8B8:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = (pixels[(i + offset) * 4] & 0xff) | (pixels[(i + offset) * 4 + 1] & 0xff) << 8 | (pixels[(i + offset) * 4 + 2] & 0xff) << 16 | (pixels[(i + offset) * 4 + 3] & 0xff) << 24;
             break;
          case TYPE_A1R5G5B5:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = pixels[(i + offset) * 2] & 0xff | (pixels[(i + offset) * 2 + 1] & 0xff) << 8;
                int a = ( ( (pixels8888[i] & 0x8000) >>> 15 ) == 1 ) ? 0xFF : 0;
                int r = (pixels8888[i] & 0x7c00) >>> 7;
                int g = (pixels8888[i] & 0x3e0) >>> 2;
                int b = (pixels8888[i] & 0x1f) << 3;
                pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
             break;
          case TYPE_A4R4G4B4:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = pixels[(i + offset) * 2] | (pixels[(i + offset) * 2 + 1] << 8);
                int a = (pixels8888[i] & 0xf000) >>> 12;
                int r = (pixels8888[i] & 0xf00) >>> 8;
                int g = (pixels8888[i] & 0xf0) >>> 4;
                int b = (pixels8888[i] & 0xf);
                a = a | (a << 4);
                r = r | (r << 4);
                g = g | (g << 4);
                b = b | (b << 4);
                pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
             break;
          case TYPE_A8R3G3B2:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = pixels[(i + offset) * 2] | (pixels[(i + offset) * 2 + 1] << 8);
                int a = (pixels8888[i] & 0xff00) >>> 8;
                int r = (pixels8888[i] & 0xe0);
                int g = (pixels8888[i] & 0x1c) << 3;
                int b = (pixels8888[i] & 0x3) << 6;
                pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
             break;
          case TYPE_R8G8B8:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = (pixels[(i + offset) * 3] & 0xff) | (pixels[(i + offset) * 3 + 1] & 0xff) << 8 | (pixels[(i + offset) * 3 + 2] & 0xff) << 16 | 0xff000000;
             break;
          case TYPE_R5G6B5:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = (pixels[(i + offset) * 2] & 0xff) | (pixels[(i + offset) * 2 + 1] & 0xff) << 8;
                int a = 0xFF;
                int r = (pixels8888[i] & 0xf800) >>> 8;
                int g = (pixels8888[i] & 0x7e0) >>> 3;
                int b = (pixels8888[i] & 0x1f) << 3;
                pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
             break;
          case TYPE_R3G3B2:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = pixels[(i + offset)];
                int a = 0xFF;
                int r = (pixels8888[i] & 0xe0);
                int g = (pixels8888[i] & 0x1c) << 3;
                int b = (pixels8888[i] & 0x3) << 6;
                pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
             break;
          case TYPE_X8R8G8B8:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = (pixels[(i + offset) * 4]) & 0xff | (pixels[(i + offset) * 4 + 1] & 0xff) << 8 | (pixels[(i + offset) * 4 + 2] & 0xff) << 16 | 0xff000000;
             break;
          case TYPE_X1R5G5B5:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = (pixels[(i + offset) * 2] & 0xff) | (pixels[(i + offset) * 2 + 1] & 0xff) << 8;
                int a = 0xff;
                int r = (pixels8888[i] & 0x7c00) >>> 7;
                int g = (pixels8888[i] & 0x3e0) >>> 2;
                int b = (pixels8888[i] & 0x1f) << 3;
                pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
             break;
          case TYPE_X4R4G4B4:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = pixels[(i + offset) * 2] | (pixels[(i + offset) * 2 + 1] << 8);
                int r = (pixels8888[i] & 0xf00) >>> 8;
                int g = (pixels8888[i] & 0xf0) >>> 4;
                int b = (pixels8888[i] & 0xf);
                r = r | (r << 4);
                g = g | (g << 4);
                b = b | (b << 4);
                pixels8888[i] = 0xff << 24 | r << 16 | g << 8 | b;  
             break;
          default:
             System.out.println("File type not recognized");
       return pixels8888;
    }After I've done this, I can just create a DataBufferInt with the returned pixel array and generate the bufferedImage. I'm doing this currently, but I'd like to be able to write code that would take the image type and return a matching BufferedImage, (of type TYPE_USHORT_565 for example). Any hints?
    Edited by: Quasi_Stomach on Jul 31, 2009 12:33 PM

    i figured it out myself !!!

  • Error when creating BufferedImage with IndexColorModel from a byte array.

    Hi, I have a 1-dimentional byte array and an IndexColorTable, and I can't figure out how to combine the 2 into an BufferedImage without unnecessary copying/reallocating of the image buffer.
    The color model I have is:
    int [] cmap = new int [numColors];
    cmap[i++] = 0xffa0f000;  /etc.
    new IndexColorModel(8, 22, cmap, 0, true,  transparentIndex,  DataBuffer.TYPE_BYTE );Thanks for your help
    -Ben
    Ps.
    I've was looking at some example code (http://javaalmanac.com/egs/java.awt.image/Mandelbrot2.html?l=rel), and can't figure out how to go from the color model they're using to the one I have (the 8 bit one specified above). When I replace the 4bit colormodel in the code below with the 8bit color model specified above, I get the following error:
    [java] java.lang.IllegalArgumentException: Raster ByteInterleavedRaster: width = 5120 height = 3520 #numDataElements 1 dataOff[0] = 0 is incompatible with ColorModel IndexColorModel: #pixelBits = 8 numComponents = 4 color space = java.awt.color.ICC_ColorSpace@c51355 transparency = 2 transIndex = 22 has alpha = true isAlphaPre = false
    [java] at java.awt.image.BufferedImage.<init>(BufferedImage.java:613)
    Code:
    byte[] pixelArray = (byte[]) getData_CHAR();                
    int width = 5120;
    int height = 3520;
    int numbytes = width*height;
    //create DataBuffer using byte buffer of pixel data.
    DataBuffer dataBuffer = new DataBufferByte(pixelArray, numbytes, 0);
    //prepare a sample model that specifies a storage 8-bits of pixel data in an 8-bit data element
    int bitMasks[] = new int[]{0xf};
    SinglePixelPackedSampleModel sampleModel = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, bitMasks);
    //create a raster using the sample model and data buffer
    WritableRaster writableRaster = Raster.createWritableRaster(sampleModel, dataBuffer, new Point(0,0));
    //generate 16-color model
    byte[] r = new byte[16];
    byte[] g = new byte[16];
    byte[] b = new byte[16];
    r[0] = 0; g[0] = 0; b[0] = 0;
    r[1] = 0; g[1] = 0; b[1] = (byte)192;
    r[2] = 0; g[2] = 0; b[2] = (byte)255;
    r[3] = 0; g[3] = (byte)192; b[3] = 0;
    r[4] = 0; g[4] = (byte)255; b[4] = 0;
    r[5] = 0; g[5] = (byte)192; b[5] = (byte)192;
    r[6] = 0; g[6] = (byte)255; b[6] = (byte)255;
    r[7] = (byte)192; g[7] = 0; b[7] = 0;
    r[8] = (byte)255; g[8] = 0; b[8] = 0;
    r[9] = (byte)192; g[9] = 0; b[9] = (byte)192;
    r[10] = (byte)255; g[10] = 0; b[10] = (byte)255;
    r[11] = (byte)192; g[11] = (byte)192; b[11] = 0;
    r[12] = (byte)255; g[12] = (byte)255; b[12] = 0;
    r[13] = (byte)80; g[13] = (byte)80; b[13] = (byte)80;
    r[14] = (byte)192; g[14] = (byte)192; b[14] = (byte)192;
    r[15] = (byte)255; g[15] = (byte)255; b[15] = (byte)255;
    //create buffered image    
    ColorModel colorModel = new IndexColorModel(4, 16, r, g, b);
    BufferedImage image = new BufferedImage(colorModel, writableRaster, false, null);Message was edited by:
    ben_weisburd
    Message was edited by:
    ben_weisburd

    I had the same problem too.
    anyone found the solution for this problem?
    thanks
    Bruno Rabino
    When I try to make a MD-form, where the base-table for the detail contains a column with a BLOB-datatype. I get following error when I finish creation of the form.
    Error: Exception from wwv_generate_component.build_procedure (WWV-01821)
    Error creating module: ORA-01403: no data found (WWV-16042)
    When I use the table with the BLOB as master or in a form, it works fine.
    Has anyone else experienced this problem? Or knows a way to fix or work around it. Thanks in advance.
    Portal version: 3.0.6.6.5
    null

  • Editing a PNG palette in AWT

    I am loading a PNG using
    ImageIO.read(new File(IMG_LOC));
    and storing the BufferedImage returned. Now I want to take that BufferedImage and modify the palette.
    The palette must first be read, analyzed, and then re-written. Basically, I am using the palette to store some meta-data about the image itself. Decoding the palette that has information, basically a hidden image, and then modifying the palette to show this hidden image, is my goal. I cannot figure out how to read individual palette entries and then modify them to create a new BufferedImage for display.
    I assume I am going about it the wrong way because I can't find a way to modify the WritableRaster or the ColorModel that can be retrieved from the BufferedImage.
    Is there a different object structure I should be looking at for reading a PNG, reading the palette, modifying the palette, and then recreating a java.awt.Image for display?
    Message was edited by:
    Zilatica

    Well, I was expecting something atrocious, but the web site looks good. The graphics look good and the colors are very nice. The markup only has a few errors that are not fatal. Adding a doctype would likely generate more errors, but that's not a bad thing. By "errors," I refer to what shows up using the w3c validators:
    html validator
    css validator
    You have no css errors. Congratulations! Of course, you have no css.
    So, here are my thoughts. If you are just a guy who wants a web site and you don't know much about web design, this site will work for you for the time being. If you are interested in learning web design, learning html, css, and dreamweaver, recreating this site would be a great project for you while the current site is online. If you are a web designer, you should bring this site up to standards using html for structure and css for layout and presentation.

  • BufferedImage causing OutOfMemoryError not getting GC'd

    I'm writing a photo library application just for practice. I'm trying to display all the jpegs in an album by displaying thumbnails of them as ImageIcons in JLabels on a JFrame.
    To get the images I use ImageIO.read(File) into a BufferedImage. Then using Image.getScaledInstance I pass the resized image to a new ImageIcon which is added to the JLabel. This all happens in a final class ThumbDisplay, method showPic which returns the JLabel.
    I call ThumbDisplay.showPic(File) in a loop, and it can read about 5 files before throwing an OutOfMemoryError. I have been able to successfully display no more than 4 images. Most of my images were taken on my digital camera and are around 2560X1920.
    I read a bit about the java heap space and I understand how 5 BufferedImages of that size open at once can easily eat up memory. But the code looks to me that any instantiated BufferedImages would be GC'd as soon as the showPic method returned the JLabel. JHAT proved otherwise and there were still 5 instances of BufferedImage when I got the OutOfMemoryError.
    So, the following is my example code block and the StackTrace. No extra stuff required. Just throw about 10 extra large jpegs in whatever path you choose to put in 'File directory' on line 9, compile and run. I'd really appreciate some help on this. I've searched countless message boards for that error and found many similar topics but ZERO answers. Can someone tell me why these aren't getting GC'd?
    code:
    1. import javax.swing.*; 
       2. import java.awt.image.*; 
       3. import javax.imageio.*; 
       4. import java.awt.*; 
       5. import java.io.*; 
       6.  
       7. public class ThumbTest{ 
       8.     public static void main(String args[]){ 
       9.         File directory = new File("c:\\pictemp\\"); 
      10.         File[] files = directory.listFiles(); 
      11.         JFrame jf = new JFrame(); 
      12.         jf.setSize(1000,1000); 
      13.         jf.setLayout(new GridLayout(10,10,15,15)); 
      14.         for(File file : files) 
      15.             jf.add(ThumbDisplay.showPic(file)); 
      16.          
      17.         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      18.         jf.setVisible(true); 
      19.  
      20.  
      21.     } 
      22. } 
      23.  
      24. final class ThumbDisplay{ 
      25.      
      26.     public static JLabel showPic(File f){ 
      27.         BufferedImage img = null; 
      28.         try{ 
      29.             img = ImageIO.read(f); 
      30.         }catch (IOException e){ 
      31.             e.printStackTrace(); 
      32.         } 
      33.         if(img != null){ 
      34.             float ratio = 100 / (float) img.getHeight(); 
      35.             int w = Math.round((float)img.getWidth() * ratio); 
      36.             int h = Math.round((float)img.getHeight() * ratio); 
      37.             return new JLabel(new ImageIcon(img.getScaledInstance(w,h,Image.SCALE_DEFAULT))); 
      38.         } else 
      39.             return new JLabel("no image"); 
      40.     } 
      41. }exception:
       1. D:\java\Projects\PhotoLibrary>java ThumbTest 
       2. Exception in thread "main" java.lang.OutOfMemoryError: Java heap space 
       3.         at java.awt.image.DataBufferByte.<init>(Unknown Source) 
       4.         at java.awt.image.ComponentSampleModel.createDataBuffer(Unknown Source) 
       5.         at java.awt.image.Raster.createWritableRaster(Unknown Source) 
       6.         at javax.imageio.ImageTypeSpecifier.createBufferedImage(Unknown Source) 
       7.         at javax.imageio.ImageReader.getDestination(Unknown Source) 
       8.         at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(Unknown Sou 
       9. rce) 
      10.         at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(Unknown Source) 
      11.         at javax.imageio.ImageIO.read(Unknown Source) 
      12.         at javax.imageio.ImageIO.read(Unknown Source) 
      13.         at ThumbDisplay.showPic(ThumbTest.java:29) 
      14.         at ThumbTest.main(ThumbTest.java:15) 

    sjasja wrote:
    ImageIO.read() does not cache images. Run ImageIO.read() in a loop for a large image. No OOME.
    Run the OP's original program under hprof. See in hprof's output how the original image data are retained. Gives an OOME, and hprof's output shows where the memory goes.
    After creating a resized image with Image.getScaledInstance(), make a copy of the resized image and discard the first resized image. (Create a BufferedImage, get a Graphics2D, and blit with g.drawImage()). Discarding the resized image will also make the pointer to the original large image go away, allowing GC. No OOME.
    In the OP's program, edit like so:
    // return new JLabel(new ImageIcon(img.getScaledInstance(w,h,Image.SCALE_DEFAULT))); 
    new JLabel(new ImageIcon(img.getScaledInstance(w,h,Image.SCALE_DEFAULT)));
    return new JLabel("yes image");You are now doing all the image loading and resizing the original program does. But because the JLabel is discarded, the pointer to the resized image is discarded, thus the pointer to the original image is discarded, and everything can be GCd. No OOME.
    If you want to see how the scaled image retains a pointer to the original image, see the interaction of Image.getScaledImage(), BufferedImage.getSource(), java.awt.image.FilteredImageSource, sun.awt.image.OffScreenImageSource, and sun.awt.image.ToolkitImage.
    By these experiments, in a reply above, I guesstimated: "As far as I can figure out, Image.getScaledInstance() keeps a pointer to the original image."
    Yes, getScaledInstance() is somewhat slow. Here is the FAQ entry for a better way to resize an image: http://java.sun.com/products/java-media/2D/reference/faqs/index.html#Q_How_do_I_create_a_resized_copy
    I have a problem with this because it should mean that the code fragment I posted in reply #5 should make no difference but I can load over a thousand images using it whereas the original code allowed me to load only 30 or so.
    I can see how creating a buffered image from the scaled image might help since discarding the scaled image will discard any reference to the original image stored in the scaled image.

  • BufferedImage from PNG : Alpha Channel disregaurded

    I'm trying to load a PNG with an alpha channel into a BufferedImage, and
    then sample the BufferedImage at various pixels for some operations.
    However, the alpha channel seems to get lost upon creation of the BufferedImage.
    For example, I'm using a PNG that is 100% transparent, and when I
    load it into a BufferedImage and display it on a panel all I see is the panel's background color.
    So far so good. Now, the problem. When I try to sample a pixel, the alpha is always 255 or 100% opaque
    which is clearly not right. Also, when I print out the BufferedImage's type, I get 0 which means the image
    type is "Custom". Care to shed any light as to how I can accurately sample an image with an alpha channel?
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import javax.imageio.*;
    import java.awt.image.*;
    public class PNGTest extends JFrame {
        public PNGTest() {
            setLocation(500,500);
            BufferedImage img = new BufferedImage(640,480,BufferedImage.TYPE_INT_RGB);
            try {
                img = ImageIO.read(new File("C:/folder/folder/myPNG.png"));
            } catch (Exception e) {
            setSize(img.getWidth(), img.getHeight());
            getContentPane().setBackground(Color.white);
            getContentPane().add(new JLabel(new ImageIcon(img)));
            setVisible(true);
            //Sample top left pixel of image and pass it to a new color
            Color color = new Color(img.getRGB(0,0));
            //print the alpha of the color
            System.out.println(color.getAlpha());
            //print the type of the bufferedimage
            System.out.println(img.getType());
        public static void main(String[] args) {
            new PNGTest();
    }Edited by: robbie.26 on May 20, 2010 4:26 PM
    Edited by: robbie.26 on May 20, 2010 4:26 PM
    Edited by: robbie.26 on May 20, 2010 4:29 PM

    Here ya go robbie, ti seems to work for the rest of the world, but not for you:
    import java.awt.*;
    import java.awt.image.*;
    import java.net.URL;
    import javax.swing.*;
    import javax.imageio.*;
    public class JTransPix{
      JTransPix(){
        JFrame f = new JFrame("Forum Junk");
        JPanel p = new MyJPanel();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(p);
        f.pack();
        f.setVisible(true);
      public static void main(String[] args) {
        new JTransPix();
      class MyJPanel extends JPanel{
        BufferedImage bi = null;
        MyJPanel(){
          try{
            bi = ImageIO.read(new URL("http://upload.wikimedia.org/wikipedia/commons/archive/4/47/20100130232511!PNG_transparency_demonstration_1.png"));  //here ya go--one liner
            this.setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
          }catch(java.io.IOException e){
            System.out.println(e.toString());
        public void paintComponent(Graphics g){
          super.paintComponent(g);
          g.setColor(Color.BLUE);
          g.fillRect(0, 0, bi.getWidth(), bi.getHeight());
          g.drawImage(bi,0, 0, this);
    }Please notice how the BufferedImage is declared and set to NULL, then allow ImageIO to set the type--Just as I said before. If you have any question about the PNG producing an ARGB image with ImageIO, then change the color painted onto the backgroun din the paintComponent to what ever you want and you'll see it show through.
    BTW: even in the short nobrainers--you still need to have VALID CATCH BLOCKS.
    To get what you are looking for, you can mask off the Alpha component by dividing each getRGB by 16777216 (256^3) or do a binary shift right 24 places.

  • Problem in creating BufferedImage

    Hi all,
    I'm trying to create a BufferdImage object from a byte array. which has the pixel values of a Gray scale image (8 bits per pixel).
    This is the code, I am trying with..
        private ColorModel colorModel;
        private SampleModel sampleModel;   
        private int bitsPerPixel;   
        private int numBands;   
        public BufferedImage convertImageDataToImage(byte[] data)
            if (bitsPerPixel == 8)
                numBands = 1;
                int[] bandOffsets = new int[numBands];
                for (int i = 0; i < numBands; i++)
                    bandOffsets[i] = numBands - 1 - i;
                sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE,
                    width, height, numBands, numBands * width, bandOffsets);
                if (ImageUtil.isIndicesForGrayscale(data, data, data))
                    colorModel = ImageUtil.createColorModel(null, sampleModel);
                else colorModel = new IndexColorModel(bitsPerPixel, data.length,
                    data, data, data);
            DataBuffer db = new DataBufferByte(data, width * height);
            WritableRaster wr = Raster.createPackedRaster(db, width, height,
                bitsPerPixel, new Point(0, 0));
            Hashtable ht = new Hashtable();
            ht.put("", "t");
            BufferedImage bi = new BufferedImage(colorModel, wr, false, null);
            return bi;
        }I'm getting the following error while executing the above code
    Exception in thread "main" java.lang.IllegalArgumentException: Raster sun.awt.image.SunWritableRaster@1bd0dd4 is incompatible with ColorModel IndexColorModel: #pixelBits = 8 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@d70d7a transparency = 1 transIndex   = -1 has alpha = false isAlphaPre = false
         at java.awt.image.BufferedImage.<init>(Unknown Source)Error occurs at..
    BufferedImage bi = new BufferedImage(colorModel,wr,false,null);
    Could any one please help me, what is the wrong here..
    Thanks and Regards
    Ramesh

    any one knows the root cause?
    Edited by: Rameshkumar.Ramasamy on Feb 22, 2008 5:10 PM

  • Copying BufferedImage to clipboard fails

    The clipboard is giving me some trouble... If I copy an image selection with transparency data and then create a BufferedImage from the clipboard contents (paste), then everything works fine everywhere. However if I have a BufferedImage with transparency data that I want to SET to the clipboard (copy) then I observe two different behaviors between Ubuntu and Windows XP -- both incorrect.
    On Ubuntu:
    getTransferDataFlavors of my Transferable is called once. isDataFlavorSupported and getTransferData are never called. The clipboard is unaltered. No exception is thrown -- nothing. It just silently fails to do anything. Calling Toolkit.getDefaultToolkit().getSystemClipboard().getAvailableDataFlavors() shows me that DataFlavor.imageFlavor is indeed present.
    On Windows:
    My getTransferData is indeed called and the clipboard is modified. However, the image is set on a BLACK background -- the transparency data is lost.
    Relevant code portions look like:
    btnCopy.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        CopyableImage img = new CopyableImage(frame.getImage());
                        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(img, null);
              });Where frame.getImage is a BufferedImage of type ARGB, with a transparent background
    private static class CopyableImage implements Transferable {
            private BufferedImage image;
            public CopyableImage(BufferedImage image) {
                this.image = image;
            // Returns supported flavors
            public DataFlavor[] getTransferDataFlavors() {
                return new DataFlavor[]{DataFlavor.imageFlavor};
            // Returns true if flavor is supported
            public boolean isDataFlavorSupported(DataFlavor flavor) {
                return DataFlavor.imageFlavor.equals(DataFlavor.imageFlavor);
            // Returns image
            public BufferedImage getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
                if (!DataFlavor.imageFlavor.equals(flavor)) {
                    throw new UnsupportedFlavorException(flavor);
                return image;
        }Any ideas...?
    Additional Notes:
    I'm am running Java 1.6
    My paste destination is in GIMP, on a new image with transparent background.
    Edited by: MichaelDGagnon on Dec 14, 2008 11:18 AM

    A fully self contained example which continues to replicate the problems observed for me is as follows. Paste works (slowly) and copy fails
    import java.io.IOException;
    import java.net.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.imageio.*;
    import java.awt.datatransfer.*;
    public class CopyTest extends JPanel{
         public static void main(String args[]) throws Exception{
              final CopyTest copyTest = new CopyTest();
              JFrame f = new JFrame();
              f.addWindowListener(new WindowListener(){
                   public void windowClosed(WindowEvent e){}
                   public void windowClosing(WindowEvent e){ System.exit(0); }
                   public void windowIconified(WindowEvent e){}
                   public void windowDeiconified(WindowEvent e){}
                   public void windowActivated(WindowEvent e){}
                   public void windowDeactivated(WindowEvent e){}
                   public void windowOpened(WindowEvent e){}
              f.setLayout(new BorderLayout());
              JButton btnCopy = new JButton("Copy");
              JButton btnPaste = new JButton("Paste");
              JPanel southPanel = new JPanel();
              southPanel.add(btnCopy);
              southPanel.add(btnPaste);
              f.add(copyTest, BorderLayout.CENTER);
              f.add(southPanel, BorderLayout.SOUTH);
              btnCopy.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){ copyTest.copy(); }
              btnPaste.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){ copyTest.paste(); }
              f.setSize(320, 240);
              f.setVisible(true);
         private static final int SQUARE_SIZE=6;
         private BufferedImage image;
         // Constructor
         public CopyTest() throws Exception{
              this.image = ImageIO.read(new URL("http://forums.sun.com/im/duke.gif"));
         // Copy
         public void copy(){
              Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
                        new Transferable(){
                             public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[]{DataFlavor.imageFlavor}; }
                             public boolean isDataFlavorSupported(DataFlavor flavor) { return DataFlavor.imageFlavor.equals(DataFlavor.imageFlavor); }
                             public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
                               if(!DataFlavor.imageFlavor.equals(flavor)){ throw new UnsupportedFlavorException(flavor); }
                               return image;
                        , null);
         // Paste
         public void paste(){
              // Get the contents
              BufferedImage clipboard = null;
              Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
              try {
                if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
                     clipboard = (BufferedImage)t.getTransferData(DataFlavor.imageFlavor);
            } catch (Exception e) { e.printStackTrace(); }
            // Use the contents
            if(clipboard != null){
                   image = clipboard;
                   repaint();
         // Paint
         public void paint(Graphics g){
              // Paint squares in the background to accent transparency
              g.setColor(Color.LIGHT_GRAY);
              g.fillRect(0, 0, getWidth(), getHeight());
              g.setColor(Color.DARK_GRAY);
              for(int x=0; x<(getWidth()/SQUARE_SIZE)+1; x=x+1){
                   for(int y=0; y<(getHeight()/SQUARE_SIZE)+1; y=y+1){
                        if(x%2 == y%2){ g.fillRect(x*SQUARE_SIZE, y*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE); }
              // Paint the image
              g.drawImage(image, 0, 0, this);
    }

  • Problem in editing drawn shape...

    Hi. I have to complete my project. The work is to create drawing tools graphical editor. I'm new to java and I have some problems with this job, so I'm looking for help where it is possible...
    I created basic shape and fiiled shape.the problem is i dont know how to edit all these shape such as its line style and its fill color similar with other paint application.I know it required mouse action when user click desired shape and desired line color and fill color.
    It should be something like windows Paintbrush. Can be simplier, but including the possibility to move and change properties of drawn objects.
    Anybody knows the solution plzzzz help me...
    i really appreciate it....

    can u plz help me with this problem..if so,i send u this progm and hoping that u will review it..
    i dont know how can i edit the shape that have been drawn..as u can see in word processor app..where the shape can be editted with their line color,fill color,line style,dash style..here is my code :it consists of 4 classes:
    Painter.java
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class Painter extends JFrame
         private CanvasPanel           canvasPanel;
         private ToolButtonPanel        toolButtonPanel;
         private ColorButtonPanel     colorButtonPanel;
         private Container                mainContainer;
         private String fileName;
         JMenuBar mainBar;
         public Painter()
              super("Drawing Tools");
              fileName = null;
              mainBar           = new JMenuBar();
              setJMenuBar(mainBar);
              canvasPanel        = new CanvasPanel();
              toolButtonPanel   = new ToolButtonPanel(canvasPanel);
              colorButtonPanel  = new ColorButtonPanel(canvasPanel);
              mainContainer = getContentPane();
              mainContainer.add(toolButtonPanel,BorderLayout.NORTH);
              mainContainer.add(canvasPanel,BorderLayout.CENTER);
              mainContainer.add(colorButtonPanel,BorderLayout.SOUTH);
              setSize(600,500);
              this.setResizable(false);
              setVisible(true);
              addWindowListener (
                    new WindowAdapter ()
                         public void windowClosing (WindowEvent e)
                              System.exit(0);
                         public void windowDeiconified (WindowEvent e)
                              canvasPanel.repaint();
                         public void windowActivated (WindowEvent e)
                              canvasPanel.repaint();
         public static void main(String args[])
              Painter application = new Painter();
              application.show();
              application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ToolButtonPanel.java
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class ToolButtonPanel extends JPanel
         private JButton lineBtn,arrowBtn, squareBtn, ovalBtn, polygonBtn, roundRectBtn, freeHandBtn, LStyleBtn, dashBtn, aStyleBtn, shadeBtn, clearBtn;          
         private JCheckBox fullChk;
         private CanvasPanel canvasPanel;
         public ToolButtonPanel(CanvasPanel inCanvasPanel)
              canvasPanel = inCanvasPanel;
              lineBtn               = new JButton("",new ImageIcon("lineBtn.gif"));
              arrowBtn          = new JButton("ARROW");
              squareBtn          = new JButton("",new ImageIcon("squareBtn.gif"));
              roundRectBtn     = new JButton("",new ImageIcon("roundRectBtn.gif"));
              ovalBtn                = new JButton("",new ImageIcon("ovalBtn.gif"));
              polygonBtn          = new JButton("",new ImageIcon("polygonBtn.gif"));
              freeHandBtn          = new JButton("",new ImageIcon("freeHandBtn.gif"));
              LStyleBtn          = new JButton("LINE STYLE");
              dashBtn               = new JButton("DASH STYLE");
              aStyleBtn          = new JButton("ARROW STYLE");
              shadeBtn          = new JButton("SHADOW");
              clearBtn          = new JButton("",new ImageIcon("clearBtn.gif"));
              lineBtn.addActionListener(new ToolButtonListener());
              lineBtn.setToolTipText("Line");
              arrowBtn.addActionListener(new ToolButtonListener());
              arrowBtn.setToolTipText("Arrow");
              squareBtn.addActionListener(new ToolButtonListener());
              squareBtn.setToolTipText("Retangle");
              roundRectBtn.addActionListener(new ToolButtonListener());
              roundRectBtn.setToolTipText("Round Rectangle");
              ovalBtn.addActionListener(new ToolButtonListener());
              ovalBtn.setToolTipText("Oval");
              polygonBtn.addActionListener(new ToolButtonListener());
              polygonBtn.setToolTipText("Polygon");
              freeHandBtn.addActionListener(new ToolButtonListener());
              freeHandBtn.setToolTipText("Free Hand");
              LStyleBtn.addActionListener(new ToolButtonListener());
              LStyleBtn.setToolTipText("Line Style");
              dashBtn.addActionListener(new ToolButtonListener());
              dashBtn.setToolTipText("Dash Style");
              aStyleBtn.addActionListener(new ToolButtonListener());
              aStyleBtn.setToolTipText("Arrow Style");
              shadeBtn.addActionListener(new ToolButtonListener());
              shadeBtn.setToolTipText("Shadow");
              clearBtn.addActionListener(new ToolButtonListener());
              clearBtn.setToolTipText("Clear Canvas");
              fullChk = new JCheckBox("Fill");
              fullChk.addItemListener(
                   new ItemListener()
                        public void itemStateChanged(ItemEvent event)
                             if(fullChk.isSelected())
                                  canvasPanel.setSolidMode(Boolean.TRUE);
                             else
                                  canvasPanel.setSolidMode(Boolean.FALSE);
              this.setLayout(new GridLayout(1,9)); // 8 Buttons & 1 CheckBox
              this.add(lineBtn);
              this.add(arrowBtn);
              this.add(ovalBtn);
              this.add(squareBtn);
              this.add(roundRectBtn);
              this.add(polygonBtn);
              this.add(freeHandBtn);
              this.add(LStyleBtn);
              this.add(dashBtn);
              this.add(aStyleBtn);
              this.add(shadeBtn);
              this.add(clearBtn);
              this.add(fullChk);                    
         private class ToolButtonListener implements ActionListener
              public void actionPerformed(ActionEvent event)
                   if(canvasPanel.isExistPolygonBuffer()!= false)
                        canvasPanel.flushPolygonBuffer();
                   if(event.getSource() == lineBtn)
                        canvasPanel.setDrawMode(canvasPanel.LINE);          
         //          if(event.getSource() == arrowBtn)
         //               canvasPanel.setDrawMode(canvasPanel.ARROW);          
                   if(event.getSource() == squareBtn)
                        canvasPanel.setDrawMode(canvasPanel.SQUARE);
                   if(event.getSource() == ovalBtn)
                        canvasPanel.setDrawMode(canvasPanel.OVAL);
                   if(event.getSource() == polygonBtn)
                        canvasPanel.setDrawMode(canvasPanel.POLYGON);
                   if(event.getSource() == roundRectBtn)
                        canvasPanel.setDrawMode(canvasPanel.ROUND_RECT);
                   if(event.getSource() == freeHandBtn)
                        canvasPanel.setDrawMode(canvasPanel.FREE_HAND);
         //          if(event.getSource() == LStyleBtn)
         //               canvasPanel.setDrawMode(canvasPanel.LINE_STYLE);
         //          if(event.getSource() == dashBtn)
         //               canvasPanel.setDrawMode(canvasPanel.DASH_STYLE);
         //          if(event.getSource() == aStyleBtn)
         //               canvasPanel.setDrawMode(canvasPanel.ARROW_STYLE);
         //          if(event.getSource() == shadeBtn)
         //               canvasPanel.setDrawMode(canvasPanel.SHADOW);
                   if(event.getSource() == clearBtn)
                        canvasPanel.clearCanvas();
    ColorButtonPanel.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class ColorButtonPanel extends JPanel
         private JPanel colorButtonPanel;
         private JButton colorBtn,fillBtn;
         private JLabel colorLbl,colorbxLbl;
         private Color colorbx,fcolor;
         private CanvasPanel canvasPanel;
         public ColorButtonPanel(CanvasPanel inCanvasPanel)
              canvasPanel = inCanvasPanel;     
              colorLbl = new JLabel("   ");
              colorLbl.setOpaque(true);
              colorLbl.setBackground(canvasPanel.getForeGroundColor());
              colorLbl.setBorder(BorderFactory.createLineBorder(Color.BLACK));
              colorBtn = new JButton("Line Color");
              colorBtn.addActionListener(     new ActionListener()
                        public void actionPerformed(ActionEvent event)
                             setForeGroundColor();
              fillBtn = new JButton("Fill");
              fillBtn.addActionListener(
                   new ActionListener()
                        public void actionPerformed(ActionEvent event)
                             setBackGroundColor();
              this.setLayout(new GridLayout(1,2));
              this.add(colorBtn);
              this.add(colorLbl);
              this.add(fillBtn);
         public void setForeGroundColor()
              colorbx = JColorChooser.showDialog(null,"Color",colorbx);
              if(colorbx!=null)
                   colorLbl.setBackground(colorbx);
                   canvasPanel.setForeGroundColor(colorbx);
         public void setBackGroundColor()
              fcolor = JColorChooser.showDialog(null,"Fill Color",fcolor);
              if(fcolor!=null)
                   //fcLbl.setBackground(fcolor);
                   canvasPanel.setBackGroundColor(fcolor);
    CanvasPanel.java
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    import javax.imageio.*;
    public class CanvasPanel extends JPanel implements MouseListener,MouseMotionListener, Serializable
         protected final static int LINE=1,SQUARE=2,OVAL=3,POLYGON=4,ROUND_RECT=5,FREE_HAND=6,
                                            SOLID_SQUARE=22, SOLID_OVAL=33, SOLID_POLYGON=44,
                                            SOLID_ROUND_RECT=55;
         protected static Vector vLine,vSquare,vOval,vPolygon,vRoundRect,vFreeHand,
                                        vSolidSquare,vSolidOval,vSolidPolygon,vSolidRoundRect,vFile,
                                        xPolygon, yPolygon;                                    
         private Color foreGroundColor, backGroundColor;
         private int x1,y1,x2,y2,linex1,linex2,liney1,liney2, drawMode=0;
         private boolean solidMode, polygonBuffer;
         public CanvasPanel()
              vLine                = new Vector();
              vSquare           = new Vector();
              vOval               = new Vector();
              vPolygon          = new Vector();
              vRoundRect          = new Vector();
              vFreeHand          = new Vector();
              vSolidSquare     = new Vector();
              vSolidOval          = new Vector();
              vSolidPolygon     = new Vector();
              vSolidRoundRect     = new Vector();
              vFile               = new Vector();
              xPolygon          = new Vector();
              yPolygon          = new Vector();
              addMouseListener(this);
              addMouseMotionListener(this);
              solidMode           = false;
              polygonBuffer      = false;
              foreGroundColor = Color.BLACK;
              backGroundColor = Color.WHITE;
              setBackground(backGroundColor);
              repaint();          
         public void mousePressed(MouseEvent event)
              x1 = linex1 = linex2 = event.getX();
            y1 = liney1 = liney2 = event.getY();
         public void mouseClicked(MouseEvent event){}
         public void mouseMoved(MouseEvent event){}
         public void mouseReleased(MouseEvent event)
              if (drawMode == LINE)
                    vLine.add(new Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor));
            if (drawMode == SQUARE)
                if(solidMode)
                         if(x1 > event.getX() || y1 > event.getY())
                           vSolidSquare.add(new Coordinate(event.getX(),event.getY(),x1,y1,foreGroundColor));
                         else
                              vSolidSquare.add(new Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor));
                else
                         if(x1 > event.getX() || y1 > event.getY())
                              vSquare.add(new Coordinate(event.getX(),event.getY(),x1,y1,foreGroundColor));
                         else
                              vSquare.add(new Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor));
            if (drawMode == this.OVAL)
                   if(solidMode)
                        if(x1 > event.getX() || y1 > event.getY())
                             vSolidOval.add(new Coordinate(event.getX(),event.getY(),x1,y1,foreGroundColor));
                        else
                             vSolidOval.add(new Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor));
                    else
                         if(x1 > event.getX() || y1 > event.getY())
                              vOval.add(new Coordinate(event.getX(),event.getY(),x1,y1,foreGroundColor));
                         else     
                              vOval.add(new Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor));
            if (drawMode == this.POLYGON || drawMode == this.SOLID_POLYGON)
                 xPolygon.add(new Integer(event.getX()));
                 yPolygon.add(new Integer(event.getY()));
                 polygonBuffer = true;
                 repaint();                 
            if (drawMode == this.ROUND_RECT)
                   if(solidMode)
                        if(x1 > event.getX() || y1 > event.getY())
                             vSolidRoundRect.add(new Coordinate(event.getX(),event.getY(),x1,y1,foreGroundColor));
                        else
                              vSolidRoundRect.add(new Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor));
                    else
                         if(x1 > event.getX() || y1 > event.getY())
                              vRoundRect.add(new Coordinate(event.getX(),event.getY(),x1,y1,foreGroundColor));
                         else
                              vRoundRect.add(new Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor));
            x1=linex1=x2=linex2=0;
            y1=liney1=y2=liney2=0;
         public void mouseEntered(MouseEvent event)
              setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
         public void mouseExited(MouseEvent event)
              setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
         public void mouseDragged(MouseEvent event)
            x2 = event.getX();
            y2 = event.getY();
            if (drawMode == this.FREE_HAND)
                linex1 = linex2;
                liney1 = liney2;          
                linex2 = x2;
                liney2 = y2;
                vFreeHand.add(new Coordinate(linex1,liney1,linex2,liney2,foreGroundColor));
             repaint();
         public void paintComponent(Graphics g)
              super.paintComponent(g);
               redrawVectorBuffer(g);
                g.setColor(foreGroundColor);
               if (drawMode == LINE)
                 g.drawLine(x1,y1,x2,y2);
               if (drawMode == OVAL)
                     if(solidMode)
                       if(x1 > x2 || y1 > y2)
                            g.fillOval(x2,y2,x1-x2,y1-y2);
                       else     
                            g.fillOval(x1,y1,x2-x1,y2-y1);
                  else
                       if(x1 > x2 || y1 > y2)
                            g.drawOval (x2,y2,x1-x2,y1-y2);
                       else
                            g.drawOval (x1,y1,x2-x1,y2-y1);
               if (drawMode == ROUND_RECT)
                  if(solidMode)
                       if(x1 > x2 || y1 > y2)
                            g.fillRoundRect(x2,y2,x1-x2,y1-y2,25,25);
                       else
                            g.fillRoundRect(x1,y1,x2-x1,y2-y1,25,25);
                  else
                       if(x1 > x2 || y1 > y2)
                            g.drawRoundRect(x2,y2,x1-x2,y1-y2,25,25);
                       else
                            g.drawRoundRect(x1,y1,x2-x1,y2-y1,25,25);
               if (drawMode == SQUARE)
                     if(solidMode)
                          if(x1 > x2 || y1 > y2)
                               g.fillRect (x2,y2,x1-x2,y1-y2);
                          else
                               g.fillRect (x1,y1,x2-x1,y2-y1);
                  else
                       if(x1 > x2 || y1 > y2)
                            g.drawRect (x2,y2,x1-x2,y1-y2);
                       else
                            g.drawRect (x1,y1,x2-x1,y2-y1);
               if (drawMode == POLYGON || drawMode == SOLID_POLYGON)
                    int xPos[] = new int[xPolygon.size()];
                     int yPos[] = new int[yPolygon.size()];
                     for(int count=0;count<xPos.length;count++)
                          xPos[count] = ((Integer)(xPolygon.elementAt(count))).intValue();
                          yPos[count] = ((Integer)(yPolygon.elementAt(count))).intValue();
                     g.drawPolyline(xPos,yPos,xPos.length);
                     polygonBuffer = true;
               if (drawMode == FREE_HAND)
                  g.drawLine(linex1,liney1,linex2,liney2);
         public void setDrawMode(int mode)
              drawMode = mode;
         public int getDrawMode()
              return drawMode;     
         public void setSolidMode(Boolean inSolidMode)
              solidMode = inSolidMode.booleanValue();
         public Boolean getSolidMode()
              return Boolean.valueOf(solidMode);
         public void setForeGroundColor(Color inputColor)
              foreGroundColor = inputColor;
         public Color getForeGroundColor()
              return foreGroundColor;
         public void setBackGroundColor(Color inputColor)
              backGroundColor = inputColor;
              this.setBackground(backGroundColor);
         public Color getBackGroundColor()
              return backGroundColor;
         public void clearCanvas()
              vFreeHand.removeAllElements();
              vLine.removeAllElements();
              vOval.removeAllElements();
              vPolygon.removeAllElements();
              vRoundRect.removeAllElements();
              vSolidOval.removeAllElements();
              vSolidPolygon.removeAllElements();
              vSolidRoundRect.removeAllElements();
              vSolidSquare.removeAllElements();
              vSquare.removeAllElements();
              repaint();
    //     this.clearCanvas();
         public boolean isExistPolygonBuffer()
              return polygonBuffer;
         public void flushPolygonBuffer()
              if(!solidMode)
                   vPolygon.add(new Coordinate(xPolygon, yPolygon, foreGroundColor));
              else
                   vSolidPolygon.add(new Coordinate(xPolygon, yPolygon, foreGroundColor));
              xPolygon.removeAllElements();
              yPolygon.removeAllElements();
              polygonBuffer = false;
              repaint();
         private class Coordinate implements Serializable
              private int x1,y1,x2,y2;
              private Color foreColor;
              private Vector xPoly, yPoly;
              public Coordinate (int inx1,int iny1,int inx2, int iny2, Color color)
                 x1 = inx1;
                  y1 = iny1;
                  x2 = inx2;
                  y2 = iny2;
                  foreColor = color;
               public Coordinate(Vector inXPolygon, Vector inYPolygon, Color color)
                    xPoly = (Vector)inXPolygon.clone();
                    yPoly = (Vector)inYPolygon.clone();
                    foreColor = color;
               public Color colour()
                 return foreColor;
               public int getX1 ()
                 return x1;
               public int getX2 ()
                 return x2;
               public int getY1 ()
                 return y1;
               public int getY2 ()
                 return y2;
               public Vector getXPolygon()
                    return xPoly;
               public Vector getYPolygon()
                    return yPoly;
         private class StepInfo implements Serializable
              private int stepType;
              private Coordinate stepCoordinate;
              public StepInfo(int inStepType, Coordinate inStepCoordinate)
                   stepType = inStepType;
                   stepCoordinate = inStepCoordinate;
              public int getStepType()
                   return stepType;
              public Coordinate getStepCoordinate()
                   return stepCoordinate;
         private RenderedImage myCreateImage()
            BufferedImage bufferedImage = new BufferedImage(600,390, BufferedImage.TYPE_INT_RGB);
            Graphics g = bufferedImage.createGraphics();
             redrawVectorBuffer(g);
               g.dispose();
               return bufferedImage;
        private void redrawVectorBuffer(Graphics g)
             for (int i=0;i<vFreeHand.size();i++){
                 g.setColor(((Coordinate)vFreeHand.elementAt(i)).colour());
                  g.drawLine(((Coordinate)vFreeHand.elementAt(i)).getX1(),((Coordinate)vFreeHand.elementAt(i)).getY1(),((Coordinate)vFreeHand.elementAt(i)).getX2(),((Coordinate)vFreeHand.elementAt(i)).getY2());
               for (int i=0;i<vLine.size();i++){
                  g.setColor(((Coordinate)vLine.elementAt(i)).colour());
                  g.drawLine(((Coordinate)vLine.elementAt(i)).getX1(),((Coordinate)vLine.elementAt(i)).getY1(),((Coordinate)vLine.elementAt(i)).getX2(),((Coordinate)vLine.elementAt(i)).getY2());
                for (int i=0;i<vOval.size();i++){     
                  g.setColor(((Coordinate)vOval.elementAt(i)).colour());
                  g.drawOval(((Coordinate)vOval.elementAt(i)).getX1(),((Coordinate)vOval.elementAt(i)).getY1(),((Coordinate)vOval.elementAt(i)).getX2()-((Coordinate)vOval.elementAt(i)).getX1(),((Coordinate)vOval.elementAt(i)).getY2()-((Coordinate)vOval.elementAt(i)).getY1());
               for (int i=0;i<vRoundRect.size();i++){
                  g.setColor(((Coordinate)vRoundRect.elementAt(i)).colour());
                  g.drawRoundRect(((Coordinate)vRoundRect.elementAt(i)).getX1(),((Coordinate)vRoundRect.elementAt(i)).getY1(),((Coordinate)vRoundRect.elementAt(i)).getX2()-((Coordinate)vRoundRect.elementAt(i)).getX1(),((Coordinate)vRoundRect.elementAt(i)).getY2()-((Coordinate)vRoundRect.elementAt(i)).getY1(),25,25);
               for (int i=0;i<vSolidOval.size();i++){
                  g.setColor(((Coordinate)vSolidOval.elementAt(i)).colour());
                  g.fillOval(((Coordinate)vSolidOval.elementAt(i)).getX1(),((Coordinate)vSolidOval.elementAt(i)).getY1(),((Coordinate)vSolidOval.elementAt(i)).getX2()-((Coordinate)vSolidOval.elementAt(i)).getX1(),((Coordinate)vSolidOval.elementAt(i)).getY2()-((Coordinate)vSolidOval.elementAt(i)).getY1());
               for (int i=0;i<vSolidRoundRect.size();i++){
                  g.setColor(((Coordinate)vSolidRoundRect.elementAt(i)).colour());
                      g.fillRoundRect(((Coordinate)vSolidRoundRect.elementAt(i)).getX1(),((Coordinate)vSolidRoundRect.elementAt(i)).getY1(),((Coordinate)vSolidRoundRect.elementAt(i)).getX2()-((Coordinate)vSolidRoundRect.elementAt(i)).getX1(),((Coordinate)vSolidRoundRect.elementAt(i)).getY2()-((Coordinate)vSolidRoundRect.elementAt(i)).getY1(),25,25);
               for (int i=0;i<vSquare.size();i++){
                  g.setColor(((Coordinate)vSquare.elementAt(i)).colour());
                  g.drawRect(((Coordinate)vSquare.elementAt(i)).getX1(),((Coordinate)vSquare.elementAt(i)).getY1(),((Coordinate)vSquare.elementAt(i)).getX2()-((Coordinate)vSquare.elementAt(i)).getX1(),((Coordinate)vSquare.elementAt(i)).getY2()-((Coordinate)vSquare.elementAt(i)).getY1());
               for (int i=0;i<vSolidSquare.size();i++){
                  g.setColor(((Coordinate)vSolidSquare.elementAt(i)).colour());
                  g.fillRect(((Coordinate)vSolidSquare.elementAt(i)).getX1(),((Coordinate)vSolidSquare.elementAt(i)).getY1(),((Coordinate)vSolidSquare.elementAt(i)).getX2()-((Coordinate)vSolidSquare.elementAt(i)).getX1(),((Coordinate)vSolidSquare.elementAt(i)).getY2()-((Coordinate)vSolidSquare.elementAt(i)).getY1());
               for(int i=0;i<vPolygon.size();i++){
                     int xPos[] = new int[((Coordinate)vPolygon.elementAt(i)).getXPolygon().size()];
                     int yPos[] = new int[((Coordinate)vPolygon.elementAt(i)).getYPolygon().size()];
                     for(int count=0;count<xPos.length;count++)
                          xPos[count] = ((Integer)((Coordinate)vPolygon.elementAt(i)).getXPolygon().elementAt(count)).intValue();
                          yPos[count] = ((Integer)((Coordinate)vPolygon.elementAt(i)).getYPolygon().elementAt(count)).intValue();
                     g.setColor(((Coordinate)vPolygon.elementAt(i)).colour());
                     g.drawPolygon(xPos,yPos,xPos.length);
                for(int i=0;i<vSolidPolygon.size();i++){
                     int xPos[] = new int[((Coordinate)vSolidPolygon.elementAt(i)).getXPolygon().size()];
                     int yPos[] = new int[((Coordinate)vSolidPolygon.elementAt(i)).getYPolygon().size()];
                     for(int count=0;count<xPos.length;count++)
                          xPos[count] = ((Integer)((Coordinate)vSolidPolygon.elementAt(i)).getXPolygon().elementAt(count)).intValue();
                          yPos[count] = ((Integer)((Coordinate)vSolidPolygon.elementAt(i)).getYPolygon().elementAt(count)).intValue();
                     g.setColor(((Coordinate)vSolidPolygon.elementAt(i)).colour());
                     g.fillPolygon(xPos,yPos,xPos.length);
      }

  • Image editing

    Hi,
    I'm trying for a long time to edit a picture on the fly and return it. This picture is used in a servlet, but I don't think that is important for my problem.
    More exactly: I want to read an image-File (score.jpg) which is used for the Background and I want to write a name on this picture.
    String name = "test";
    BufferedImage bufferedImage = null;
    try {
         bufferedImage = ImageIO.read(new File(score.jpg));
    } catch (IOException exception) {
              //TODO: handle Exception
    Graphics2D graphics = (Graphics2D)bufferedImage.getGraphics();
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    graphics.setColor(Color.WHITE);
    graphics.setFont(new Font("Pigiarniq", Font.BOLD,  12));
    graphics.drawString(name, 10, 20);
    graphics.dispose();So far so good.
    My problem is, that the name can vary between 1 and 30 characters and I would like to have the name centered on the image and readable for every length, so I think different font sizes.
    Calculating the length of the String isn't really easy cause the letters have different length, so I have to calc it for every character and try for the different font sizes if the String fits.
    I heard of ImageMagick, but I think it is like shooting with a cannons on small birds.
    Does someone know an easier solution for the problem, or give me some hints.
    Best regards
    Tobias Wilken

    Image size tends to rise linearly with font size, there is some variation, but it won't be very big at sizes larger than about 6pt. So you should be able to get the size at some standard font size such as 10pt, and then use that to calculate a better approximation of the size you need. If its not exactly what you need you can use newton's method to refine it.

  • BufferedImage memory issue.

    Hi! I'm writing an application that is basically an image filter:
    It takes a low-resolution input image and converts the grayscale value of each pixel into a font size. The font size is then used to render characters from a text file onto corresponding coordinates in a high-resolution output image, thus creating an image from words. (I call it "one image is thousand words"*. Poetic, isn't it?)
    The application performs well for moderate size output images (say 2500x2500 pixels) but since the goal is to print these images at high quality in large formats I need to achieve resolutions of roughly 7200 pixels square, which throws the OutOfMemory error when initializing the output image's BufferedImage. This happens also if I set the heap space to its maximum allowed value.
    How do I work around this problem?
    I use the BufferedImage class for all image data handling.
    Cheers/ Jomik
    *Allthough theoretically, the application can handle far more than thousand words :)
    Edited by: jomik on Apr 15, 2008 6:56 AM
    Edited by: jomik on Apr 15, 2008 6:58 AM

    I suggest working with at most a single instance of BufferedImage at any one time. Since you say the error is thrown when you initialize your output image do you still have other instances like input around?
    To help mitigate the problem also consider forcing the garbage collector to free memory right before you initialize the image, Runtime.getRuntime().gc();
    -CollegeJavaStudent

  • To obtain BufferedImage from Scene 3D

    Hi all!!! I want to obtain snapshots from Scene 3D to do a video with JMF (Java Media Framework). How I do it??
    Regards!

    // read the buffer to byteBuffer
                GL11.glReadBuffer(GL11.GL_FRONT);
                ByteBuffer pixels = ByteBuffer.allocateDirect(400*400*4);
                GL11.glReadPixels(0, 0, 400, 400, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, pixels);
                ColorModel glColorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
                                                new int[] {8,8,8,0},
                                                false,
                                                false,
                                                ComponentColorModel.OPAQUE,
                                                DataBuffer.TYPE_BYTE);
                int[] bitMasks = new int[] {8,8,8,0};
                int[] band = new int[3];
                // again, what is this?
                SinglePixelPackedSampleModel sampleModel = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, 400, 400,bitMasks);
                // make array from byteBuffer to make a DataBufferByte from array...
                byte [] byteA=new byte[400*400*3];
                System.out.println(byteA.length);
                pixels.get(byteA);
                DataBuffer db = new DataBufferByte(byteA, 400*400*3, 0);
                //make my raster
                WritableRaster raster = Raster.createInterleavedRaster(db, 400, 400, 400*3, 3, band, null);
                // make my image
                BufferedImage image = new BufferedImage(glColorModel, raster, false, null);//new java.util.Hashtable());the above produces an image! yey! it is however grayscale, can anybody help?
    Edited by: IJustWantToSayHelloWorld on Aug 5, 2009 4:12 AM

  • Creating bufferedimage from scene in different resolution than the Canvas?

    Is it possible to create a bufferedimage from a Canvas, but with a higher resolution without loosing image quality?
    Need to take high-quality screenshots of the 3d-scene.
    Thanks.

    I'm trying to back up and simultaneously organize my photos from my Mac OS 10.8.5 by dragging groups of photos from iPhoto to an external HD.
    One more thought -  if you want to backup your photos, why not simply copy your iPhoto Library to the external drive? That would save your photos as well as the work you invested in editing and tagging them.
    If you do the backup by storing only the photos on your external drive, you need to export all edited photos twice - first the original photo like described in Old Toad's screenshot, and then the edited version as well, or you will lose your editing work, if you need your backup.
    Copying the iPhoto Library would save all in one, without too much trouble.
    Your second goal, reorganizing, could be done directly in iPhoto.

  • Help with BufferedImage and JPanel

    I have a program that should display some curves, but thats not the problem, the real problem is when i copy the image contained in the JPanel to the buffered image then i draw something there and draw it back to the JPanel. My panel initialy its white but after the operation it gets gray
    Please if some one could help with this
    here is my code divided in three classes
    //class VentanaPrincipal
    package gui;
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JSeparator;
    import javax.swing.border.LineBorder;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    * This code was edited or generated using CloudGarden's Jigloo
    * SWT/Swing GUI Builder, which is free for non-commercial
    * use. If Jigloo is being used commercially (ie, by a corporation,
    * company or business for any purpose whatever) then you
    * should purchase a license for each developer using Jigloo.
    * Please visit www.cloudgarden.com for details.
    * Use of Jigloo implies acceptance of these licensing terms.
    * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
    * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
    * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
    public class VentanaPrincipal extends javax.swing.JFrame {
              //Set Look & Feel
              try {
                   javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              } catch(Exception e) {
                   e.printStackTrace();
         private JMenuItem helpMenuItem;
         private JMenu jMenu5;
         private JMenuItem deleteMenuItem;
         private JSeparator jSeparator1;
         private JMenuItem pasteMenuItem;
         private JLabel jLabel4;
         private JLabel jLabel5;
         private JLabel jLabel3;
         private JLabel jLabel2;
         private JLabel jLabel1;
         private JButton jSPLineButton;
         private JButton jHermiteButton;
         private JButton jBezierButton;
         private JPanel jPanel2;
         private JPanel jPanel1;
         private JMenuItem jResetMenuItem1;
         private JMenuItem copyMenuItem;
         private JMenuItem cutMenuItem;
         private JMenu jMenu4;
         private JMenuItem exitMenuItem;
         private JSeparator jSeparator2;
         private JMenu jMenu3;
         private JMenuBar jMenuBar1;
          * Variables no autogeneradas
         private int botonSeleccionado;
         * Auto-generated main method to display this JFrame
         public static void main(String[] args) {
              VentanaPrincipal inst = new VentanaPrincipal();
              inst.setVisible(true);
         public VentanaPrincipal() {
              super();
              initGUI();
         private void initGUI() {
              try {
                        this.setTitle("Info3 TP 2");
                             jPanel1 = new pizarra();
                             getContentPane().add(jPanel1, BorderLayout.WEST);
                             jPanel1.setPreferredSize(new java.awt.Dimension(373, 340));
                             jPanel1.setMinimumSize(new java.awt.Dimension(10, 342));
                             jPanel1.setBackground(new java.awt.Color(0,0,255));
                             jPanel1.setBorder(BorderFactory.createCompoundBorder(
                                  new LineBorder(new java.awt.Color(0, 0, 0), 1, true),
                                  null));
                             BufferedImage bufimg = (BufferedImage)jPanel1.createImage(jPanel1.getWidth(), jPanel1.getHeight());
                             ((pizarra) jPanel1).setBufferedImage(bufimg);
                             jPanel2 = new JPanel();
                             getContentPane().add(jPanel2, BorderLayout.CENTER);
                             GridBagLayout jPanel2Layout = new GridBagLayout();
                             jPanel2Layout.rowWeights = new double[] {0.0, 0.0, 0.0, 0.0};
                             jPanel2Layout.rowHeights = new int[] {69, 74, 76, 71};
                             jPanel2Layout.columnWeights = new double[] {0.0, 0.0, 0.1};
                             jPanel2Layout.columnWidths = new int[] {83, 75, 7};
                             jPanel2.setLayout(jPanel2Layout);
                                  jBezierButton = new JButton();
                                  jPanel2.add(jBezierButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                                  jBezierButton.setText("Bezier");
                                  jBezierButton.setFont(new java.awt.Font("Tahoma",0,10));
                                  jBezierButton.addActionListener(new ActionListener() {
                                       public void actionPerformed(ActionEvent evt) {
                                            bezierActionPerformed();
                                  jHermiteButton = new JButton();
                                  jPanel2.add(jHermiteButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                                  jHermiteButton.setText("Hermite");
                                  jHermiteButton.setFont(new java.awt.Font("Tahoma",0,10));
                                  jSPLineButton = new JButton();
                                  jPanel2.add(jSPLineButton, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                                  jSPLineButton.setText("SP Line");
                                  jSPLineButton.setFont(new java.awt.Font("Tahoma",0,10));
                                  jLabel1 = new JLabel();
                                  jPanel2.add(jLabel1, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
                                  jLabel1.setText("Posicion Mouse");
                                  jLabel2 = new JLabel();
                                  jPanel2.add(jLabel2, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(12, 0, 0, 0), 0, 0));
                                  jLabel2.setText("X:");
                                  jLabel3 = new JLabel();
                                  jPanel2.add(jLabel3, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.NONE, new Insets(0, 0, 12, 0), 0, 0));
                                  jLabel3.setText("Y:");
                                  jLabel4 = new JLabel();
                                  jPanel2.add(jLabel4, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(12, 0, 0, 0), 0, 0));
                                  jLabel4.setText("-");
                                  jLabel5 = new JLabel();
                                  jPanel2.add(jLabel5, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.NONE, new Insets(0, 0, 12, 0), 0, 0));
                                  jLabel5.setText("-");
                   this.setSize(600, 400);
                        jMenuBar1 = new JMenuBar();
                        setJMenuBar(jMenuBar1);
                             jMenu3 = new JMenu();
                             jMenuBar1.add(jMenu3);
                             jMenu3.setText("Archivo");
                                  jSeparator2 = new JSeparator();
                                  jMenu3.add(jSeparator2);
                                  exitMenuItem = new JMenuItem();
                                  jMenu3.add(exitMenuItem);
                                  exitMenuItem.setText("Exit");
                                  jResetMenuItem1 = new JMenuItem();
                                  jMenu3.add(jResetMenuItem1);
                                  jResetMenuItem1.setText("Reset");
                             jMenu4 = new JMenu();
                             jMenuBar1.add(jMenu4);
                             jMenu4.setText("Edit");
                                  cutMenuItem = new JMenuItem();
                                  jMenu4.add(cutMenuItem);
                                  cutMenuItem.setText("Cut");
                                  copyMenuItem = new JMenuItem();
                                  jMenu4.add(copyMenuItem);
                                  copyMenuItem.setText("Copy");
                                  pasteMenuItem = new JMenuItem();
                                  jMenu4.add(pasteMenuItem);
                                  pasteMenuItem.setText("Paste");
                                  jSeparator1 = new JSeparator();
                                  jMenu4.add(jSeparator1);
                                  deleteMenuItem = new JMenuItem();
                                  jMenu4.add(deleteMenuItem);
                                  deleteMenuItem.setText("Delete");
                             jMenu5 = new JMenu();
                             jMenuBar1.add(jMenu5);
                             jMenu5.setText("Help");
                                  helpMenuItem = new JMenuItem();
                                  jMenu5.add(helpMenuItem);
                                  helpMenuItem.setText("Help");
              } catch (Exception e) {
                   e.printStackTrace();
         private void bezierActionPerformed(){
              botonSeleccionado = 1;
              ((pizarra) jPanel1).setTipoFigura(botonSeleccionado);
              ((pizarra) jPanel1).pintarGrafico();
    //class graphUtils
    package func;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.image.BufferedImage;
    public class graphUtils {
         public static void dibujarPixel(BufferedImage img, int x, int y, int color){
              img.setRGB(x, y, color);
         public static void dibujarLinea(BufferedImage img, int x0, int y0, int x1, int y1, int color){
            int dx = x1 - x0;
            int dy = y1 - y0;
            if (Math.abs(dx) > Math.abs(dy)) {          // Pendiente m < 1
                float m = (float) dy / (float) dx;     
                float b = y0 - m*x0;
                if(dx < 0) dx = -1; else dx = 1;
                while (x0 != x1) {
                    x0 += dx;
                    dibujarPixel(img, x0, Math.round(m*x0 + b), color);
            } else
            if (dy != 0) {                              // Pendiente m >= 1
                float m = (float) dx / (float) dy;
                float b = x0 - m*y0;
                if(dy < 0) dy = -1; else dy = 1;
                while (y0 != y1) {
                    y0 += dy;
                    dibujarPixel(img, Math.round(m*y0 + b), y0, color);
         public static void dibujarBezier(BufferedImage img, Point puntos, int color){
    //class pizarra
    package gui;
    import javax.swing.*;
    import sun.awt.VerticalBagLayout;
    import sun.security.krb5.internal.bh;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.image.BufferedImage;
    import java.util.ArrayList;
    import func.graphUtils;
    * esta clase pizarra extiende la clase JPanel y se agregan las funciones de pintado
    * y rellenado que se muestra en pantalla dentro del panel que se crea con esta clase
    * @author victorg
    public class pizarra extends JPanel implements MouseListener{
         private int tipoFigura;
         BufferedImage bufferImagen;
         Image img;
         Graphics img_gc;
         private Color colorRelleno, colorLinea;
         private Point puntosBezier[] = new Point[3];
         public pizarra(){
              super();          
              addMouseListener(this);
              //this.setBackground(Color.BLUE);
              colorLinea = Color.BLUE;
         public void setTipoFigura(int seleccion){
              // se setea para ver si es bezier, hermite, SP line
              tipoFigura = seleccion;
         public void setTipoRelleno(int seleccion){
         public void setColorRelleno(Color relleno){
              colorRelleno = relleno;          
         public void setColorLinea(Color linea){
              colorLinea = linea;
         public void setBufferedImage(BufferedImage bufimg){
              bufferImagen = bufimg;
         public void pintarGrafico(){
              Graphics g = this.getGraphics();     
              g.setColor(colorLinea);
              //accion ejecutada cuando se selecciona para graficar un poligono
              if(tipoFigura == 1){// bezier
                   if(bufferImagen == null){
                        //mantiene guardada la imagen cuando la pantalla pasa a segundo plano
                        bufferImagen = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
                        this.setBackground(Color.WHITE);                                                  
                        bufferImagen = (BufferedImage)createImage(getWidth(), getHeight());
                        //bufferImagen = this.createImage(getWidth(), getHeight());
                   //g.drawImage(bufferImagen,0,0,this);
                   graphUtils.dibujarLinea(bufferImagen,10, 10, 50, 50, colorLinea.getRGB());
                   g.drawImage(bufferImagen,0,0,this);
         protected void paintComponent(Graphics g) { // llamado al repintar
              //setBackground(colorFondo);
              super.paintComponent(g);
    //          Graphics2D g2 = (Graphics2D)g;          
    //          g2.drawImage(bufferImagen, 0,0, this);          
    //          g2.dispose();     
         public void mouseClicked(MouseEvent arg0) {          
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseEntered(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseExited(MouseEvent arg0) {
              // TODO Auto-generated method stub
    }

    1) Swing related questions should be posted in the Swing forum.
    Custom painting should be done in the paintComponent(..) method. You created a "pintarGraphico" method to do the custom painting, but that method is only execute once. When Java determines that the panel needs to be repainted, the paintComponent() method is executed which simply does a super.paintComponent(), which in turn simply paints the background of the panel overwriting you custom painting.

Maybe you are looking for