views:

354

answers:

3

I set the JPanel background color as white. However when I save it into JPG or other image format, the background are all in black. I have put this code TYPE_INT_ARGB but it doesnt work. How can I set the background to other color? e.g. blue, white etc.

    public void paintComponent(Graphics g) {
       int width = getWidth();
       int height = getHeight();

       // Create a buffered image in which to draw
       BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

       // Create a graphics contents on the buffered image
       Graphics2D g2d = bufferedImage.createGraphics();  
       g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
       g2d.setStroke(new BasicStroke(1)); // set the thickness of polygon line
       g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.00f));
       g2d.setPaint(Color.black);//color of the polygon line
       g2d.setBackground(Color.WHITE);

       //draw polygon
       for (Polygon triangle : triangles)  
         g2d.drawPolygon(triangle);

       try {
           File file = new File("newimage.jpg");
           ImageIO.write(bufferedImage, "jpg", file);
       } catch (IOException e) {
         }    
 }//public void paint(Graphics g)
A: 

You give the solution in your question. You set the background of the panel to white, not the BufferedImage. You save the image as a JPEG, not the panel, so the JPEG has the default background, which shows up as black.

MennoH
A: 

what do you expect to have as a background when saving as JPEG? JPEG is meant for photographies, it cannot have transparent areas, so those must be converted to some color, that is why you have black (I suppose). Why don't you save image as PNG? Or if you want to stick with JPEG first fill area with white color, then start drawing onto it...

ante.sabo
A: 

Your approach to creating the image is backwards if you ask me. All you other questions have been about painting polygons on a panel. Now you are changing the code to paint on an image?

When you extend JPanel and invoke super.paintComponent() guess what happens? The background gets painted! Then you do your custom polygon painting. In the above code you just create the image and then paint the polygons.

The easier approach is to just create a routine the paints the panel to the image, then you can reuse the code without overriding the paintComponent method of every component.

The ScreenImage class does this for you.

camickr