楼主: NewOccidental
4041 18

Learning Java, 4th Edition [推广有奖]

11
财大小学生(未真实交易用户) 发表于 2015-5-17 15:37:06 来自手机
Converting an Image to a BufferedImage

  • Image processing can be performed only on BufferedImages, not Images. Remember that the core AWT tools all work with Image and that only if you are loading images using the ImageIO package will you get BufferedImages. Our ImageProcessor example demonstrates an important technique: how to convert a plain AWT Image to a BufferedImage. You do it by painting into the buffer, effectively copying the data. The main() method loads an Image from a file using Toolkit’s getImage() method:

  1.     Image i = Toolkit.getDefaultToolkit().getImage(filename);
复制代码

  • Next, main() uses a MediaTracker to make sure the image data is fully loaded.
  • Finally, the trick of converting an Image to a BufferedImage is to draw the Image into the drawing surface of the BufferedImage. Because we know the Image is fully loaded, we just need to create aBufferedImage, get its graphics context, and draw the Image into it:

  1.     BufferedImage bi = new BufferedImage(w, h,
  2.             BufferedImage.TYPE_INT_RGB);
  3.     Graphics2D imageGraphics = bi.createGraphics();
  4.     imageGraphics.drawImage(i, 0, 0, null);
复制代码

12
nanlou001(未真实交易用户) 发表于 2015-5-18 11:13:28

Simple Audio

  1. //file: NoisyButton.java
  2.     import java.applet.*;
  3.     import java.awt.*;
  4.     import java.awt.event.*;
  5.     import javax.swing.*;

  6.     public class NoisyButton {

  7.       public static void main(String[] args) throws Exception {
  8.         JFrame frame = new JFrame("NoisyButton");
  9.         java.io.File file = new java.io.File( args[0] );
  10.         final AudioClip sound = Applet.newAudioClip(file.toURL());

  11.         JButton button = new JButton("Woof!");
  12.         button.addActionListener(new ActionListener() {
  13.           public void actionPerformed(ActionEvent e) { sound.play(); }
  14.         });

  15.         Container content = frame.getContentPane();
  16.         content.setBackground(Color.pink);
  17.         content.setLayout(new GridBagLayout());
  18.         content.add(button);
  19.         frame.setVisible(true);
  20.         frame.setSize(200, 200);
  21.         frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  22.         frame.setVisible(true);
  23.       }
  24.     }
复制代码

已有 1 人评分论坛币 收起 理由
Nicolle + 20 鼓励积极发帖讨论

总评分: 论坛币 + 20   查看全部评分

13
cindyczy(未真实交易用户) 发表于 2015-5-19 02:24:16
Saving Image Data

We’ve spent a lot of time talking about loading images from files and generating and transforming image data, but nothing about saving it. First, let’s remember that saving an image to a file such as a JPG or GIF really implies doing two things: encoding it (highly compressing the data in a way optimized for the type of image) and then writing it to a file, possibly with various metadata. As we mentioned earlier, the core AWT does not provide tools for encoding image data, only decoding it. By contrast, the ImageIO framework has the capability of writing images in any format that it can read.

Writing a BufferedImage is simply a matter of calling the static ImageIO write() method:

  1.   File outFile = new File("/tmp/myImage.png");
  2.     ImageIO.write( bufferedImage , "png", outFile );
复制代码

The second argument is a string identifier that names the image type. You can get the list of supported formats by calling ImageIO.getWriterFormatNames(). We should note that the actual type of the image argument is something called RenderedImage, but BufferedImage implements that interface.

You can get more control over the encoding (for example, JPG quality settings) by getting an ImageWriter for the output format and using ImageWriteParams. The process is similar to that in the reader progress listener snippet from the section ImageIO.

已有 1 人评分论坛币 收起 理由
Nicolle + 20 鼓励积极发帖讨论

总评分: 论坛币 + 20   查看全部评分

14
hanszhu(未真实交易用户) 发表于 2015-6-5 11:17:27
Working with Overloaded Constructors

A constructor can refer to another constructor in the same class or the immediate superclass using special forms of the this and super references. We’ll discuss the first case here and return to that of the superclass constructor after we have talked more about subclassing and inheritance. A constructor can invoke another overloaded constructor in its class using the self-referential method call this()with appropriate arguments to select the desired constructor. If a constructor calls another constructor, it must do so as its first statement:

   
  1. class Car {
  2.         String model;
  3.         int doors;

  4.         Car( String model, int doors ) {
  5.             this.model = model;
  6.             this.doors = doors;
  7.             // other, complicated setup
  8.             ...
  9.         }

  10.         Car( String model ) {
  11.             this( model, 4 /* doors */ );
  12.         }
  13.         ...
  14.     }
复制代码

In this example, the class Car has two constructors. The first, more explicit, one accepts arguments specifying the car’s model and its number of doors. The second constructor takes just the model as an argument and, in turn, calls the first constructor with a default value of four doors. The advantage of this approach is that you can have a single constructor do all the complicated setup work; other auxiliary constructors simply feed the appropriate arguments to that constructor.

The special call to this() must appear as the first statement in our delegating constructor. The syntax is restricted in this way because there’s a need to identify a clear chain of command in the calling of constructors. At the end of the chain, Java invokes the constructor of the superclass (if we don’t do it explicitly) to ensure that inherited members are initialized properly before we proceed.

There’s also a point in the chain, just after invoking the constructor of the superclass, where the initializers of the current class’s instance variables are evaluated. Before that point, we can’t even reference the instance variables of our class. We’ll explain this situation again in complete detail after we have talked about inheritance.

For now, all you need to know is that you can invoke a second constructor (delegate to it) only as the first statement of your constructor. For example, the following code is illegal and causes a compile-time error:

   
  1. Car( String m ) {
  2.         int doors = determineDoors();
  3.         this( m, doors );   // Error: constructor call
  4.                             // must be first statement
  5.     }
复制代码

The simple model name constructor can’t do any additional setup before calling the more explicit constructor. It can’t even refer to an instance member for a constant value:

   
  1. class Car {
  2.         ...
  3.         final int default_doors = 4;
  4.         ...

  5.         Car( String m ) {
  6.             this( m, default_doors ); // Error: referencing
  7.                                       // uninitialized variable
  8.         }
  9.         ...
  10.     }
复制代码

The instance variable defaultDoors is not initialized until a later point in the chain of constructor calls setting up the object, so the compiler doesn’t let us access it yet. Fortunately, we can solve this particular problem by using a static variable instead of an instance variable:

   
  1. class Car {
  2.         ...
  3.         static final int DEFAULT_DOORS = 4;
  4.         ...

  5.         Car( String m ) {
  6.             this( m, DEFAULT_DOORS );  // Okay!
  7.         }
  8.         ...
  9.     }
复制代码

The static members of a class are initialized when the class is first loaded into the virtual machine, so it’s safe to access them in a constructor.


15
Nicolle(真实交易用户) 学生认证  发表于 2015-7-13 02:07:33
提示: 作者被禁止或删除 内容自动屏蔽

16
ReneeBK(未真实交易用户) 发表于 2015-9-25 09:57:51
  1. //file: ObserveImageLoad.java
  2.     import java.awt.*;
  3.     import java.awt.image.*;

  4.     public class ObserveImageLoad {

  5.       public static void main( String [] args)
  6.       {
  7.        ImageObserver myObserver = new ImageObserver() {
  8.           public boolean imageUpdate(
  9.              Image image, int flags, int x, int y, int width, int height)
  10.           {
  11.              if ( (flags & HEIGHT) !=0 )
  12.                System.out.println("Image height = " + height );
  13.              if ( (flags & WIDTH ) !=0 )
  14.                System.out.println("Image width = " + width );
  15.              if ( (flags & FRAMEBITS) != 0 )
  16.                System.out.println("Another frame finished.");
  17.              if ( (flags & SOMEBITS) != 0 )
  18.                 System.out.println("Image section :"
  19.                     + new Rectangle( x, y, width, height ) );
  20.              if ( (flags & ALLBITS) != 0 )
  21.                System.out.println("Image finished!");
  22.              if ( (flags & ABORT) != 0 )
  23.                System.out.println("Image load aborted...");
  24.              return true;
  25.          }
  26.        };

  27.         Toolkit toolkit = Toolkit.getDefaultToolkit();
  28.         Image img = toolkit.getImage( args[0] );
  29.         toolkit.prepareImage( img, -1, -1, myObserver );
  30.       }
  31.     }
复制代码

17
ReneeBK(未真实交易用户) 发表于 2015-9-25 09:58:53
  1.     public class StatusImage extends JComponent
  2.     {
  3.       boolean loaded = false;
  4.       String message = "Loading...";
  5.       Image image;

  6.       public StatusImage( Image image ) { this.image = image; }

  7.       public void paint(Graphics g) {
  8.         if (loaded)
  9.             g.drawImage(image, 0, 0, this);
  10.         else {
  11.           g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
  12.           g.drawString(message, 20, 20);
  13.         }
  14.       }
  15.       public void loaded() {
  16.         loaded = true;
  17.         repaint();
  18.       }
  19.       public void setMessage( String msg ) {
  20.         message = msg;
  21.         repaint();
  22.       }

  23.       public static void main( String [] args ) {
  24.         JFrame frame = new JFrame("TrackImage");
  25.         Image image = Toolkit.getDefaultToolkit().getImage( args[0] );
  26.         StatusImage statusImage = new StatusImage( image );
  27.         frame.add( statusImage );
  28.         frame.setSize(300,300);
  29.         frame.setVisible(true);

  30.         MediaTracker tracker = new MediaTracker( statusImage );
  31.         int MAIN_IMAGE = 0;
  32.         tracker.addImage( image, MAIN_IMAGE );
  33.         try {
  34.             tracker.waitForID( MAIN_IMAGE ); }
  35.         catch (InterruptedException e) {}
  36.         if ( tracker.isErrorID( MAIN_IMAGE ) )
  37.             statusImage.setMessage( "Error" );
  38.         else
  39.             statusImage.loaded();
  40.       }
  41.     }
复制代码

18
ReneeBK(未真实交易用户) 发表于 2015-9-25 09:59:41
  1. Creating an Image
  2. Let’s take a look at producing some image data. A picture is worth a thousand words, and, fortunately, we can generate a pretty picture in significantly fewer than a thousand words of Java. If we just want to render image frames byte by byte, you can put together a BufferedImage pretty easily.

  3. The following application, ColorPan, creates an image from an array of integers holding RGB pixel values:

  4.     //file: ColorPan.java
  5.     import java.awt.*;
  6.     import java.awt.image.*;
  7.     import javax.swing.*;

  8.     public class ColorPan extends JComponent {
  9.       BufferedImage image;

  10.       public void initialize() {
  11.         int width = getSize().width;
  12.         int height = getSize().height;
  13.         int[] data = new int [width * height];
  14.         int i = 0;
  15.         for (int y = 0; y < height; y++) {
  16.           int red = (y * 255) / (height - 1);
  17.           for (int x = 0; x < width; x++) {
  18.             int green = (x * 255) / (width - 1);
  19.             int blue = 128;
  20.             data[i++] = (red << 16) | (green << 8 ) | blue;
  21.           }
  22.         }
  23.         image = new BufferedImage(width, height,
  24.             BufferedImage.TYPE_INT_RGB);
  25.         image.setRGB(0, 0, width, height, data, 0, width);
  26.       }

  27.       public void paint(Graphics g) {
  28.         if (image == null)
  29.             initialize();
  30.         g.drawImage(image, 0, 0, this);
  31.       }

  32.       public void setBounds(int x, int y, int width, int height) {
  33.         super.setBounds(x,y,width,height);  
  34.         initialize();
  35.       }

  36.       public static void main(String[] args) {
  37.         JFrame frame = new JFrame("ColorPan");
  38.         frame.add(new ColorPan());
  39.         frame.setSize(300, 300);
  40.         frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  41.         frame.setVisible(true);
  42.       }
  43.     }
复制代码

19
ReneeBK(未真实交易用户) 发表于 2015-9-25 10:01:29
  1. //file: StaticGenerator.java
  2.     import java.awt.*;
  3.     import java.awt.event.*;
  4.     import java.awt.image.*;
  5.     import java.util.Random;
  6.     import javax.swing.*;

  7.     public class StaticGenerator extends JComponent implements Runnable {
  8.       byte[] data;
  9.       BufferedImage image;
  10.       Random random;

  11.       public void initialize() {
  12.         int w = getSize().width, h = getSize().height;
  13.         int length = ((w + 7) * h) / 8;
  14.         data = new byte[length];
  15.         DataBuffer db = new DataBufferByte(data, length);
  16.         WritableRaster wr = Raster.createPackedRaster(db, w, h, 1, null);
  17.         ColorModel cm = new IndexColorModel(1, 2,
  18.             new byte[] { (byte)0, (byte)255 },
  19.             new byte[] { (byte)0, (byte)255 },
  20.             new byte[] { (byte)0, (byte)255 });
  21.         image = new BufferedImage(cm, wr, false, null);
  22.         random = new Random();
  23.       }

  24.       public void run() {
  25.         if ( random == null )
  26.             initialize();
  27.         while (true) {
  28.           random.nextBytes(data);
  29.           repaint();
  30.           try { Thread.sleep(1000 / 24); }
  31.           catch( InterruptedException e ) { /* die */ }
  32.         }
  33.       }

  34.       public void paint(Graphics g) {
  35.         if (image == null) initialize();
  36.         g.drawImage(image, 0, 0, this);
  37.       }

  38.       public void setBounds(int x, int y, int width, int height) {
  39.         super.setBounds(x,y,width,height);
  40.         initialize();
  41.       }

  42.       public static void main(String[] args) {
  43.         //RepaintManager.currentManager(null).setDoubleBufferingEnabled(false);
  44.         JFrame frame = new JFrame("StaticGenerator");
  45.         StaticGenerator staticGen = new StaticGenerator();
  46.         frame.add( staticGen );
  47.         frame.setSize(300, 300);
  48.         frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  49.         frame.setVisible(true);
  50.         new Thread( staticGen ).start();
  51.       }
  52.     }
复制代码

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
jg-xs1
拉您进交流群
GMT+8, 2025-12-31 09:11