Three methods for reading images using Java

Source: Internet
Author: User

Note: The image is displayed on the label. Common APIs are used. When using jframe, close the window and exit debugging.Code.

Complete code, compiled and executed

Import javax. ImageIO. *; // For ImageIO. Read
Import java. AWT. *; // For jframe and jlabel etc
Import javax. Swing. *; // For jframe and jlabel etc
Import java.net. *; // For URL
Import java. Io. *; // For catch (ioexception E), file, inputstream, bufferedinputstream, and fileinputstream ect
Public class hellojava {
Public static void main (string [] ARGs ){
Image image = NULL;
Try {
// Read from a file
File sourceimage = new file ("source.gif"); // The source.gif image must be in the same directory as hellojava. java.
Image = ImageIO. Read (sourceimage );

// Read from an input stream
Inputstream is = new bufferedinputstream (
New fileinputstream ("mid.jpg"); // The mid.jpg image must be in the same directory as hellojava. java.
Image = ImageIO. Read (is );

// Read from a URL
URL url = new URL ("http://www.javaworld.com/images/012407-tipsbox.jpg ");
Image = ImageIO. Read (URL );
} Catch (ioexception e ){
}

// Use a label to display the image
Jframe frame = new jframe ();
Jlabel label = new jlabel (New imageicon (image ));
Frame. getcontentpane (). Add (Label, borderlayout. center );
Frame. Pack ();
Frame. setvisible (true );
// Close the window -- exit debugging
Frame. setdefaclocloseoperation (jframe. exit_on_close );
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.