Android Development Series (12): Get pictures on the web

Source: Internet
Author: User

The process of acquiring a network slice:

Get a picture of the url-> by URL Connection picture Object--read the binary data of the picture to write to memory--and return to memory data--show it


First, we want to add permissions

Because we want to access the network, we will always add network access to the Androidmanifest.xml file:

<!--access to INTERNET rights--><uses-permission android:name= "Android.permission.INTERNET"/>


Then there is the Setup interface: Main.xml:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/    Android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" Fill_parent " ><textview android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:text= "@stri     Ng/imagepath "/> <edittext android:layout_width=" fill_parent "android:layout_height=" Wrap_content " Android:text= "http://b.hiphotos.baidu.com/image/w%3D310/sign=1d7f12db95dda144da096ab382b5d009/ 8d5494eef01f3a293c5d63069b25bc315d607c64.jpg "android:id=" @+id/imagepath "/> <button android:layout_ Width= "Wrap_content" android:layout_height= "wrap_content" android:text= "@string/button" android:id= "@+id/button "/> <imageview android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Android : id= "@+id/imageview"/></linearlayout>

Next is the Mainactivity.java file:

Package Cn.itcast.image;import Cn.itcast.service.imageservice;import Android.app.activity;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.bundle;import Android.view.View; Import Android.widget.button;import Android.widget.edittext;import Android.widget.imageview;import    Android.widget.toast;public class Mainactivity extends Activity {private EditText pathtext;        Private ImageView ImageView;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (R.layout.main);        Pathtext = (EditText) This.findviewbyid (R.id.imagepath);        ImageView = (ImageView) This.findviewbyid (R.id.imageview);        Button button = (button) This.findviewbyid (R.id.button);    Button.setonclicklistener (New Buttonclicklistener ()); } Private Final class Buttonclicklistener implements View.onclicklistener{public void OnClick (View v) {String path = Pathtext.gettext (). toStRing (); Get the URL path of the text box try{//get the binary data of the picture byte[] data = imageservice.getimage (path);//convert the picture to bitmap type bitmap bitmap = Bitmapfactory.decodebytearray (data, 0, data.length); Imageview.setimagebitmap (bitmap);//Display Picture}catch (Exception e) { E.printstacktrace ();    Toast.maketext (Getapplicationcontext (), R.string.error, 1). Show ();}} }}
Then we will also configure the Imageservice.java file:

Package Cn.itcast.service;import Java.io.inputstream;import Java.net.httpurlconnection;import java.net.URL;import Cn.itcast.utils.streamtool;public class ImageService {/** * get data for a network picture * @param path network picture paths * @return */public static byte[ ] GetImage (String path) throws exception{//get urlurl url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection ();//HTTP protocol-based Connection object Conn.setconnecttimeout (5000); Conn.setrequestmethod ("get");//set to submit if (conn.getresponsecode () = = 200) {//If the response code equals 200 is the request succeeds InputStream instream = Conn.getinputstream (); Get input stream return Streamtool.read (instream); Get picture binary data}return null;}}

Finally we will add a tool class:

Package Cn.itcast.utils;import Java.io.bytearrayoutputstream;import Java.io.inputstream;public class StreamTool {/** * Read data in stream * @param instream * @return * @throws Exception */public static byte[] Read (InputStream instream) throws Excepti On{bytearrayoutputstream OutStream = new Bytearrayoutputstream (); byte[] buffer = new Byte[1024];int len = 0;while (len = Instream.read (buffer))! =-1) {//instream.read (buffer) returns INT: The length of the data read, and when read-1 is finished reading Outstream.write (buffer, 0, Len); Writes the read data to the memory}instream.close (); return Outstream.tobytearray (); Returns the data in Memory}}



As follows:


Android Development Series (12): Get pictures on the web

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.