Private void setalpha (bytearrayoutputstream OS ){
/**
* Add a test item
* Read the image and draw it as translucent
*/
Try {
Imageicon = new imageicon (OS. tobytearray ());
Bufferedimage = new bufferedimage (imageicon. geticonwidth (), imageicon. geticonheight ()
, Bufferedimage. type_4byte_abgr );
Graphics2d g2d = (graphics2d) bufferedimage. getgraphics ();
G2d. drawimage (imageicon. getimage (), 0, 0,
ImageIcon. getImageObserver ());
// Cyclically change the Alpha value of each pixel.
Int alpha = 100;
For (int j1 = bufferedImage. getMinY (); j1 <bufferedImage. getHeight (); j1 ++ ){
For (int j2 = bufferedImage. getMinX (); j2 <bufferedImage. getWidth (); j2 ++ ){
Int rgb = bufferedImage. getRGB (j2, j1 );
Rgb = (alpha + 1) <24) | (rgb & 0x00ffffff );
BufferedImage. setRGB (j2, j1, rgb );
}
}
G2d. drawimage (bufferedimage, 0, 0, imageicon. getimageobserver ());
// Generate a PNG Image
ImageIO. Write (bufferedimage, "PNG", new file (image path ));
}
Catch (exception e ){
E. printstacktrace ();
}
}
Use Java to transform the image effect (the second image overwrites the pixel of the first image and displays it)
When talking about Java, JSP, Servlet, and J2EE are the most talked about. But for the effect conversion of Images Using Java, I went to the Forum and looked at it. There were not many topics in this regard, there are not many articles on image processing on the Internet, so after several days of self-exploration and referring to anfyjava (Professional-level Java Effect Generator, I wrote a lightweight control (anfyjava inherits the applet and Applet is Java. the AWT package is a heavyweight control. Sun recommends using swing to write graphics programs. Therefore, I use japplet ).
In fact, using Java for image effects is essentially no different from other languages, but it is different in implementation, next I will share with you my experience in the project.
The conversion of the image is actually to perform some operations on the content of the two images, generate a new image, and then display it. In the end, the excessive effect is achieved from one image to another. The specific process of transformation is as follows:
In the above process, the sizes of image a and Image B should be the same. If they are different, some additional processing may be required. Here, the size of image a and Image B is the same.
First, we write it as an applet. Due to the limitations of the applet, we cannot directly use the File class to read image files. Therefore, we can only obtain image files using the following methods.
Urlclassloader urlloader = (urlclassloader) This. getclass (). getclassloader ();
URL url = urlloader. findresource ("imagea.gif ");
Image image = toolkit. getdefatooltoolkit (). getimage (URL );
After obtaining the image, you can use the pixelgrabber method in the Java. AWT. image. pixelgrabber package to completely read the pixel information in the image. Its usage is as follows:
Pixelgrabber (image IMG, int X, int y, int W, int H, int [] pix, int off, int scansize)
Here, IMG is the image to be read, x/y is to read the coordinates in the upper left corner of the image, W/H is the distance from x/y, in fact, X, Y, W, H is a rectangle. pix is an array of stored pixels. off is the starting position when the image is read. scansize refers to the scanning width, which is generally equal to W.
Int width = image. getwidth ();
Int Height = image. getheight ();
Int size = width * height;
Int [] pixels = new int [size];
Pixelgrabber = new pixelgrabber (image, 0, 0, width, height, pixels, 0, width );
Try {
Pixelgrabber. grabpixels (); // read the pixel into the Array
}
Catch (interruptedexception _ ex ){}
The pixel information is composed of alpha, red, green, and blue. The format is
Therefore, we can break down colors into separate RGB information.
Int alpha = (pixel> 24) & 0xff;
Int Red = (pixel> 16) & 0xff;
Int Green = (pixel> 8) & 0xff;
Int Blue = (pixel) & 0xff;
To display image a and expand image B from top to bottom, you can replace one row of pixels in image a with the corresponding row in B each time, and then generate new Pixel Information:
Image A's pixel array image B's pixel array
Old = pixela; // Save the pixel information of image
Oldr = Reda; // Save the r information of image
Oldg = greena; // Save the g information of image
Oldb = bluea; // save B information of image
For (INT I = 0; I <width; I ++) {// line indicates the number of rows.
Oldr [LINE * width + I] = Reda [LINE * width + I];
Oldg [LINE * width + I] = greena [LINE * width + I];
Oldb [LINE * width + I] = bluea [LINE * width + I];
Old [LINE * width + I] = oldr [LINE * width + I] <16 + oldg [LINE * width + I] <8 + oldb [LINE * width + I ];
}
After generating new pixel information, you can use Java. AWT. image. the memoryimagesource (int w, int H, colormodel cm, int [] pix, int off, int scan) method in the memoryimagesource package maps the pixel array to the image, and newpixels () can be used () method to generate a new image (For details, refer to Java api doc ).
Memoryimagesource = new memoryimagesource (imagewidth, imageheight,
New directcolormodel (24, 0xff0000, 0x00ff00, 0x0000ff), blocks, 0, imagewidth );
// Check the Java version
String javaversion;
Try {
Javaversion = system. getproperty ("Java. Version ");
}
Catch (securityexception _ ex ){
Javaversion = "unk ";
}
If (! JavaVersion. startsWith ("1.0") {// jdk1.1 or later versions only support this method
Try {
Memoryimagesource. setAnimated (true );
Memoryimagesource. setFullBufferUpdates (true );
ImageBuf = createImage (memoryimagesource );
Memoryimagesource. newPixels (); // generate a new image
}
Catch (NoSuchMethodError _ ex ){
System. out. println ("unknow java version! ");
}
}
At this point, new images have been generated and only need to be output to the screen.
Pay attention to the following issues:
1. Because the image files read by the Applet can be relatively large, for a slow network, the image may start to be transformed if it is not completely read. Therefore, we recommend that you use the MediaTracker method to ensure smooth image loading.
2. You can use double buffering to avoid flickering during display.
3. on a high-speed computer, generating new pixels can be very fast. In order to avoid the effect from being obvious due to the high speed, appropriate latency processing can be performed.
4. To ensure smooth effects, we have specially opened up a very large array to store pixel/RGB information. This is a space-for-time approach.
Complete source program attachment (run in jdk1.4/2 k Server/RedHat9 and use P4 2.4G/512 M)
Package pic;
Import java. awt .*;
Import java. io .*;
Import java.net .*;
Import java. awt. event .*;
Import java. awt. image .*;
Import javax. swing .*;
Public class effect
Extends JApplet
Implements Runnable {
// Define variables
Toolkit toolkit;
Int totalBlocks = 0; // number of blocks in the image. The default value is width X height.
Int [] blocks; // Save the number of blocks
Image [] bufferImage = new Image [2]; // Image Buffering on the screen
VolatileImage offScreenImage;
Image imageBuf; // Save the Image buffer content
Graphics2D offScreenGraphics;
Thread thread;
MediaTracker mediaTracker;
Boolean [] isImageReady; // whether the image has been loaded
MemoryImageSource memoryimagesource;
Int imageWidth, imageHeight; // image width and height
Int [] pixelA, pixelB;
Int [] Reda, greena, bluea, redb, greenb, blueb;
Public effect () throws headlessexception {
Bufferimage [0] = getimage ("a.jpg ");
Bufferimage [1] = getimage ("B .jpg ");
If (bufferimage [0]. getwidth (this )! = Bufferimage [1]. getwidth (this) |
(Bufferimage [0]. getheight (this )! = Bufferimage [1]. getheight (this ))){
System. Out. println ("inconsistent image sizes! ");
Return;
}
Toolkit = gettoolkit ();
Imagewidth = bufferimage [0]. getwidth (this );
Imageheight = bufferimage [0]. getheight (this );
Totalblocks = imagewidth * imageheight; // calculate the number of parts to be decomposed.
Blocks = new int [totalblocks];
Pixela = new int [totalblocks];
Pixelb = new int [totalblocks];
Reda = new int [totalblocks];
Greena = new int [totalblocks];
BlueA = new int [totalBlocks];
RedB = new int [totalBlocks];
GreenB = new int [totalBlocks];
BlueB = new int [totalBlocks];
GraphicsEnvironment ge = GraphicsEnvironment. getLocalGraphicsEnvironment ();
GraphicsDevice gd = ge. getdefascrescreendevice ();
GraphicsConfiguration gc = gd. getDefaultConfiguration ();
OffScreenImage = gc. createCompatibleVolatileImage (imageWidth, imageHeight); // create an image buffer
OffScreenGraphics = offScreenImage. createGraphics (); // obtain the cached graphics object.
}
Public void init (){
GetImagePixels (bufferImage [0], pixelA );
GetImagePixels (bufferImage [1], pixelB );
For (int I = 0; I <totalBlocks; I ++ ){
Blocks [I] = pixelA [I]; // Save the pixel information of image
RedA [I] = pixelA [I] & 0xff0000; // Save the red value of Image B
GreenA [I] = pixelA [I] & 0x00ff00; // Save the green value of Image B
BlueA [I] = pixelA [I] & 0x0000ff; // Save the blue value of Image B
RedB [I] = pixelB [I] & 0xff0000; // Save the red value of Image B
GreenB [I] = pixelB [I] & 0x00ff00; // Save the green value of Image B
BlueB [I] = pixelB [I] & 0x0000ff; // Save the blue value of Image B
}
PrepareImagePixels (); // restores pixel information to an image.
}
Public void run (){
// Check the java version
String javaVersion;
Try {
JavaVersion = System. getProperty ("java. version ");
}
Catch (SecurityException _ ex ){
JavaVersion = "unk ";
}
If (javaVersion. startsWith ("1.0 ")){
System. out. println ("require java 1.1 or later version! ");
Return;
}
Try {// pause for 3 seconds and wait until the effect starts
Thread. Sleep (3000l );
}
Catch (interruptedexception ex1 ){
}
Int line = 0;
Thread currentthread = thread. currentthread ();
While (line <imageheight & Thread = currentthread ){
For (INT I = 0; I <imagewidth; I ++ ){
Int offset = line * imagewidth + I;
Blocks [offset] = pixelb [offset]; // it works the same as the next commented statement.
// Blocks [offset] = redb [offset] | greenb [offset] | blueb [offset];
}
Memoryimagesource. newpixels (); // generate a new image
Line ++;
Repaint ();
// Appropriate latency
Try {
Thread. Sleep (20l );
}
Catch (interruptedexception ex ){
}
}
}
Public void paint (Graphics g ){
If (offScreenGraphics! = Null) {// ensure that no exception is thrown during destory ()
OffScreenGraphics. drawImage (imageBuf, 0, 0, this );
G. drawImage (offScreenImage, 0, 0, this );
}
}
Public void start (){
If (thread = null ){
Thread = new Thread (this );
Thread. start ();
}
}
Public void stop (){
Thread = null;
}
Public final void update (Graphics g ){
Paint (g );
}
Public void destroy (){
If (offScreenImage! = Null ){
OffScreenImage. flush ();
}
OffScreenImage = null;
If (offScreenGraphics! = Null ){
OffScreenGraphics. dispose ();
}
OffScreenGraphics = null;
System. gc ();
}
Image getImage (String filename ){
URLClassLoader urlLoader = (URLClassLoader) this. getClass (). getClassLoader ();
URL url = null;
Image image = null;
Url = urlLoader. findResource (filename );
Image = Toolkit. getdefatooltoolkit (). getImage (url );
MediaTracker mediatracker = new MediaTracker (this );
Try {
Mediatracker. addImage (image, 0 );
Mediatracker. waitForID (0 );
}
Catch (InterruptedException _ ex ){
Image = null;
}
If (mediatracker. isErrorID (0 )){
Image = null;
}
Return image;
}
Private boolean getImagePixels (Image image, int pixels []) {
Pixelgrabber = new pixelgrabber (image, 0, 0, imagewidth,
Imageheight, pixels,
0, imagewidth );
Try {
Pixelgrabber. grabpixels ();
}
Catch (interruptedexception _ ex ){
Return false;
}
Return true;
}
Void prepareimagepixels (){
Memoryimagesource = new memoryimagesource (imagewidth, imageheight,
New directcolormodel (24, 0xff0000,
0x00ff00, 0x0000ff), blocks, 0, imagewidth );
Try {
Memoryimagesource. setanimated (true );
Memoryimagesource. setfullbufferupdates (true );
Imagebuf = createimage (memoryimagesource );
Memoryimagesource. newpixels (); // generate a new image
}
Catch (nosuchmethoderror _ ex ){
}
}
Public int getWidth (){
Return imageWidth;
}
Public int getHeight (){
Return imageHeight;
}
Public static void main (String args []) {
JFrame frame = new JFrame ("Demo ");
Effect e = new effect ();
E. init ();
E. start ();
Frame. getContentPane (). setLayout (new BorderLayout ());
Frame. setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE );
Frame. setResizable (false );
Frame. getContentPane (). add (e );
Frame. setSize (new Dimension (e. getWidth () + 6, e. getHeight () + 20 ));
Dimension screenSize = Toolkit. getdefatooltoolkit (). getScreenSize ();
Dimension frameSize = frame. getSize ();
Frame. setlocation (screensize. Width-framesize. width)/2,
(Screensize. Height-framesize. Height)/2 );
Frame. Show ();
}
}
Create an HTML file and add the following statement as an applet (where width/height is the height and width of the image respectively ):
<APPLET Height = 640 width = 480 code = pic. effect. Class> </APPLET>
When running an application, enter the following command in the command line:
Java pic. Effect