There are also many people who asked this question. I want to take out the previous code as a document and hope it will help you learn image processing!
The Java. AWT. image. * package inherits the rgbimagefilter class and modifies the alpha (transparency) of the image pixels. The following uses the Applet as an example:
Import java. Applet .*;
Import java. AWT .*;
Import java. AWT. event .*;
Import java. AWT. Font .*;
Import java. AWT. image .*;
Public class applet6 extends applet {
Mediatracker MT;
Image IMG = NULL;
Image im = NULL;
Imagefilter imgf = NULL;
Filteredimagesource FD = NULL;
Public void Init (){
IMG = This. getimage (this. getcodebase (), "d.jpg ");
Mt = new mediatracker (this );
Mt. addimage (IMG, 0 );
Try {
Mt. waitforall (0 );
} Catch (exception ex) {system. Err. println (ex. tostring ());}
Im = This. createimage (100,100); // create a new image for text input for transparent processing.
Graphics g2 = Im. getgraphics ();
G2.setfont (new font ("", Font. Bold, 15 ));
G2.drawstring ("Translucent text", 10, 50 );
Imgf = new myimage (100,100,100); // call a custom class to construct an object
FS = new filteredimagesource (IM. getsource (), imgf); // filter the image source (image producer) and construct a filteredimagesource object instance.
Im = This. createimage (FS); // generate an image through the filteredimagesource instance
}
Public void paint (Graphics g ){
G. drawimage (IMG, this); // draw the image
G. drawimage (IM, 100,100, this); // Add translucent text
}
}
Class myimage extends rgbimagefilter {// abstract class rgbimagefilter is a subclass of imagefilter and inherits it to process the image argb.
Int width = 0;
Int Height = 0;
Int alpha = 0;
Public myimage (INT width, int height, int alpha) {// constructor, used to receive the size and transparency of the image to be filtered
This. canfilterindexcolormodel = true;
// The transparentimagefilter class inherits from rgbimagefilter. Its constructor requires that the width and height of the original image be input. This class implements the filterrgb abstract function. By default, this function passes in the argb value of the pixel identified by X and Y, after processing according to a certain program logic, the programmer returns the new argb value of the pixel.
This. width = width;
This. Height = height;
This. Alpha = Alpha;
}
Public int filterrgb (int x, int y, int RGB ){
Directcolormodel DCM = (directcolormodel) colormodel. getrgbdefault ();
// The directcolormodel class is used to separate the argb values.
Int Red = DCM. getred (RGB );
Int Green = DCM. getgreen (RGB );
Int Blue = DCM. getblue (RGB );
If (Red = 255 & green = 255 & Blue = 255) // If the pixel is white, make it transparent.
Alpha = 0;
Return Alpha <24 | red <16 | green <8 | blue; // standard argb output for Image Filtering
}
}