1.java code, download the main program of the picture
First realize the display picture, then click the Download Picture button, perform the download function.
Images obtained from the network, there are two ways to generate bitmap, one is to convert to byte[], and then generate bitmap, one is to generate bitmap directly with InputStream.
(1) Implementation in ICS4.0 and later versions
4.0 does not allow the operation of the network in the main thread, which is the UI thread, so a new thread must be opened to perform the network connection in the child thread, and the picture will be displayed in the main thread.
[Java] View plaincopy on code to see a snippet derived from my Code slice
public class Icstestactivity extends Activity {private final static String TAG = "icstestactivity"; Private final static String Album_path = Environment.getexternalstoragedirectory () + "/download_test/"; Private ImageView Mimageview; Private Button Mbtnsave; Private ProgressDialog msavedialog = null; Private Bitmap Mbitmap; Private String Mfilename; Private String msavemessage; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); Mimageview = (ImageView) Findviewbyid (R.id.imgsource); Mbtnsave = (Button) Findviewbyid (R.id.btnsave); New Thread (ConnectNet). Start (); Download Image Mbtnsave.setonclicklistener (new Button.onclicklistener () {public void OnClick (View v) { Msavedialog = Progressdialog.show (Icstestactivity.this, "Save Picture", "picture is being saved, please wait ...", true); New Thread (savefilerunnable). Start (); } }); }/** * Get image from Newwork * @param path of the path of image * @return byte[] * @throws Excepti On */public byte[] GetImage (String path) throws exception{url url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setconnecttimeout (5 * 1000); Conn.setrequestmethod ("GET"); InputStream instream = Conn.getinputstream (); if (conn.getresponsecode () = = HTTPURLCONNECTION.HTTP_OK) {return readstream (instream); } return null; }/** * Get image from Newwork * @param path of the path of image * @return InputStream * @throws Ex Ception */Public InputStream Getimagestream (String path) throws exception{url url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setconnecttimEout (5 * 1000); Conn.setrequestmethod ("GET"); if (conn.getresponsecode () = = HTTPURLCONNECTION.HTTP_OK) {return conn.getinputstream (); } return null; }/** * Get data from Stream * @param instream * @return byte[] * @throws Exception */ public static byte[] Readstream (InputStream instream) throws exception{bytearrayoutputstream OutStream = new Byt Earrayoutputstream (); byte[] buffer = new byte[1024]; int len = 0; while ((Len=instream.read (buffer))! =-1) {outstream.write (buffer, 0, Len); } outstream.close (); Instream.close (); return Outstream.tobytearray (); }/** * Save file * @param BM * @param fileName * @throws IOException */public void Savefil E (Bitmap BM, String fileName) throws IOException {file Dirfile = new File (Album_path); if (!dirfile.exists ()) { Dirfile.mkdir (); } File Mycapturefile = new file (Album_path + fileName); Bufferedoutputstream BOS = new Bufferedoutputstream (new FileOutputStream (Mycapturefile)); Bm.compress (Bitmap.CompressFormat.JPEG, N, BOS); Bos.flush (); Bos.close (); } private Runnable savefilerunnable = new Runnable () {@Override public void run () {TR y {saveFile (mbitmap, mfilename); Msavemessage = "Picture saved successfully!" "; } catch (IOException e) {msavemessage = "Picture save failed! "; E.printstacktrace (); } messagehandler.sendmessage (Messagehandler.obtainmessage ()); } }; Private Handler MessageHandler = new Handler () {@Override public void Handlemessage (Message msg) { Msavedialog.dismiss (); LOG.D (TAG, msavemessage); Toast.maketext (Icstestactivity.this, MsavemEssage, Toast.length_short). Show (); } }; /* * Connection Network * Due to not allowing access to the network in the main thread in 4.0, you need to access */private Runnable connectnet = new Runnable () { @Override public void Run () {try {String FilePath = "Http://img.my.csdn.net/uploa Ds/201402/24/1393242467_3999.jpg "; Mfilename = "Test.jpg"; Here are two ways to get a picture////////////////Method 1: Gets a byte array, generated from a byte array bitmap byte[] data = GetImage (f Ilepath); if (data!=null) {mbitmap = Bitmapfactory.decodebytearray (data, 0, data.length);//Bitmap }else{Toast.maketext (Icstestactivity.this, "Image error!", 1). Show (); }//////////////////////////////////////////////////////////******** Method 2: Obtained is Inputstrea m, generated directly from InputStream bitmap ***********/mbitmap = Bitmapfactory.decodestream (getimAgestream (FilePath)); ///Send a message informing handler to update the UI in the main thread Connecthanlder.sendemptymessage (0); LOG.D (TAG, "set image ..."); } catch (Exception e) {toast.maketext (icstestactivity.this, "Unable to link network! ", 1). Show (); E.printstacktrace (); } } }; Private Handler Connecthanlder = new Handler () {@Override public void Handlemessage (Message msg) { LOG.D (TAG, "display image"); Update UI, show picture if (mbitmap! = null) {Mimageview.setimagebitmap (MBITMAP);//Display image } } }; }
(2) 2.3 and the following versions can operate the network connection in the main thread, but it is best not to do so, because the connection network is blocked, if 5 seconds are not connected, it will cause the ANR.
[Java] View plaincopy
public class Androidtest2_3_3 extends Activity {private final static String TAG = "Androidtest2_3_3"; Private final static String Album_path = Environment.getexternalstoragedirectory () + "/download_test/"; Private ImageView ImageView; Private Button btnsave; Private ProgressDialog mydialog = null; Private Bitmap Bitmap; Private String FileName; Private String message; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); ImageView = (ImageView) Findviewbyid (R.id.imgsource); Btnsave = (Button) Findviewbyid (R.id.btnsave); String FilePath = "Http://hi.csdn.net/attachment/201105/21/134671_13059532779c5u.jpg"; FileName = "Test.jpg"; Try {////////////////gets a byte array, generates bitmap byte[] data = GetImage (FilePath) from a byte array; if (data!=null) { Bitmap = Bitmapfactory.decodebytearray (data, 0, data.length);//Bitmap Imageview.setimagebit Map (bitmap);//Display Image}else{Toast.maketext (androidtest2_3_3.this, "image error! ", 1). Show (); }//////////////////////////////////////////////////////////******** obtained is InputStream, directly from INPUTST Ream Generate bitmap ***********/bitmap = Bitmapfactory.decodestream (Getimagestream (FilePath)); if (bitmap! = null) {Imageview.setimagebitmap (bitmap);//Display image}//*** /LOG.D (TAG, "set image ..."); } catch (Exception e) {toast.maketext (Androidtest2_3_3.this, "Newwork error!", 1). Show (); E.printstacktrace (); }//Download picture Btnsave.setonclicklistener (New Button.onclicklistener() {public void OnClick (View v) {mydialog = Progressdialog.show (androidtest2_3_3.this, "save diagram "," Picture is being saved, please wait a moment ... ", true); New Thread (savefilerunnable). Start (); } }); }/** * Get image from Newwork * @param path of the path of image * @return byte[] * @throws E Xception */Public byte[] GetImage (String path) throws exception{url url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setconnecttimeout (5 * 1000); Conn.setrequestmethod ("GET"); InputStream instream = Conn.getinputstream (); if (conn.getresponsecode () = = HTTPURLCONNECTION.HTTP_OK) {return readstream (instream); } return null; }/** * Get image from Newwork * @param path of the path of image * @return InputStream * @ Throws Exception */Public InputStream Getimagestream (String path) throws exception{url url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setconnecttimeout (5 * 1000); Conn.setrequestmethod ("GET"); if (conn.getresponsecode () = = HTTPURLCONNECTION.HTTP_OK) {return conn.getinputstream (); } return null; }/** * Get data from Stream * @param instream * @return byte[] * @throws Exception * /public static byte[] Readstream (InputStream instream) throws exception{Bytearrayoutputstream Outstre am = new Bytearrayoutputstream (); byte[] buffer = new byte[1024]; int len = 0; while ((Len=instream.read (buffer))! =-1) {outstream.write (buffer, 0, Len); } outstream.close (); Instream.close (); Return outstream.toByteArray (); }/** * Save file * @param BM * @param fileName * @throws IOException */public void Savefi Le (Bitmap BM, String fileName) throws IOException {file Dirfile = new File (Album_path); if (!dirfile.exists ()) {Dirfile.mkdir (); } File Mycapturefile = new file (Album_path + fileName); Bufferedoutputstream BOS = new Bufferedoutputstream (new FileOutputStream (Mycapturefile)); Bm.compress (Bitmap.CompressFormat.JPEG, N, BOS); Bos.flush (); Bos.close (); } private Runnable savefilerunnable = new Runnable () {@Override public void run () {TR Y {saveFile (bitmap, fileName); Message = "Picture saved successfully!" "; } catch (IOException e) {message = "Picture save failed! "; E.printstacktrace (); } messagehandler.sendmessage (Messagehandler.obtainmessage ()); } }; Private Handler MessageHandler = new Handler () {@Override public void Handlemessage (Message msg) { Mydialog.dismiss (); LOG.D (TAG, message); Toast.maketext (androidtest2_3_3.this, message, Toast.length_short). Show (); } }; }
Download the progress bar can refer to one of my other posts: Android update download progress bar
2.main.xml file with only one button and one ImageView
[XHTML] View plaincopy
<?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" > <button android:id= "@+id/btnsave" android:layout_width= "Wrap_ Content " android:layout_height=" wrap_content " android:text=" save Picture " /> <imageview Android:id= "@+id/imgsource" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:adjustviewbounds= "true" /> </LinearLayout>
3. Increase Internet access and write SD card permissions in the Mainfest file
[XHTML] View plaincopy
<uses-permission android:name= "Android.permission.INTERNET"/> <uses-permission android:name= " Android.permission.WRITE_EXTERNAL_STORAGE "/> <uses-permission android:name=" android.permission.MOUNT_ Unmount_filesystems "/>
ANDROID for picture saving