I set a JPanel
's background color to white. However, when I save it into JPG or another image format, the background is black. I have put this code TYPE_INT_ARGB
but it doesn't 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 开发者_JAVA百科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)
I do realize that this is a very old question but I had a similar issue myself and since I found the answer (it's in the javadocs) I thought I would post it here anyway.
When you set the background color on the graphics object this will only come into play when you clear a region. Hence, just clear the entire area right away and you will have the background in your preferred color:
graphics.clearRect(0, 0, width, height);
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.
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...
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.
精彩评论