Setting the color of a clipped area

Hello, I currently have a problem with clipping an image. The clipping itself is actually doing fine, however the clipped area is always black.

I tried to set the color to something else that black by setting the g2d.setBackground (I would like to have that area transparent or a least white) but that does not change anything.

Please find the code below, I would appreciate any feedback.

Many thanks

Martin

import java.awt.Color;

import java.awt.Graphics2D;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

import java.net.MalformedURLException;

import java.net.URL;

import javax.imageio.ImageIO;

import javax.swing.ImageIcon;

public class Clipping {

public static void main(String[] args) {

int width = 1024;

int height = 744;

ImageIcon image = null;

try {

image = new ImageIcon(

new URL(

"http://java.sun.com/products/jfc/tsc/sightings/S20/smartcvs/annotate.png"));

} catch (MalformedURLException e) {

e.printStackTrace();

}

BufferedImage bufferedImage = new BufferedImage(width, height,

BufferedImage.TYPE_INT_RGB);

Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();

g2d.setBackground(Color.white);

g2d.setClip(0, 0, width - 200, height);

g2d.drawImage(image.getImage(), 0, 0, null);

// clear resources

g2d.dispose();

try {

ImageIO.write(bufferedImage, "png", new File("clipped.png"));

} catch (IOException e) {

e.printStackTrace();

}

}

}

[1636 byte] By [martingia] at [2007-11-27 8:58:44]
# 1

the clipped area is always black

Yes, you must fill in the background.

I tried to set the color to something else that black by setting the g2d.setBackground

Okay.

(I would like to have that area transparent or a least white)

To have transparent pixels in an image you will need to use a different image type, one that

supports an alpha channel. Try BufferedImage.TYPE_INT_ARGB or

BufferedImage.TYPE_INT_ARGB_PRE.

For the first one you can use new Color(0,0,0,0) for the transparent portions.

but that does not change anything

You have to do everythng in this lower-level kind of work. With the background set you can

call clearRect(0,0,w,h). Or you can call setPaint instead of setBackground and then use

fillRect(0,0,w,h). Look up the clearRect method in the Graphics class api to see what it's

supposed to do.

crwooda at 2007-7-12 21:25:19 > top of Java-index,Security,Cryptography...