Android easy to learn bitmap display pictures and cached images

Source: Internet
Author: User
Tags save file

Yesterday we learned how to connect to the network, today we will learn how to display the screen into the project

The main use of today is the bitmap class

Bitmap is one of the most important classes of image processing in an Android system. It can get image file information, image cutting, rotation, zooming and other operations, and can specify format to save image file

Specific action properties refer to the official API: Https://msdn.microsoft.com/zh-cn/library/system.drawing.bitmap (v=vs.110). aspx

Don't say more, look at the case.

Make a picture display:

Activity_main.xml

1<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"2Xmlns:tools= "Http://schemas.android.com/tools"3Android:layout_width= "Match_parent"4android:layout_height= "Match_parent"5android:orientation= "Vertical"6tools:context= "Com.example.imagelook.MainActivity" >7 8<EditText9Android:id= "@+id/et_path"TenAndroid:layout_width= "Match_parent" Oneandroid:layout_height= "Wrap_content" Aandroid:hint= "@string/edittext" > -</EditText> -  the<Button -Android:id= "@+id/button1" -Android:layout_width= "Wrap_content" -android:layout_height= "Wrap_content" +android:onclick= "click" -android:text= "@string/btn"/> +  A<ImageView atAndroid:id= "@+id/iv" -Android:layout_width= "Wrap_content" -android:layout_height= "Wrap_content"/> -  -</LinearLayout>

Mainacitivity.java

 PackageCom.example.imagelook;ImportJava.io.File;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;Importjava.net.HttpURLConnection;ImportJava.net.URL;Importandroid.app.Activity;ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;Importandroid.util.Base64;ImportAndroid.view.View;ImportAndroid.widget.EditText;ImportAndroid.widget.ImageView; Public classMainactivityextendsActivity {PrivateEditText Et_path; PrivateImageView IV; PrivateHandler Handler =NewHandler () {//processing Messages         Public voidhandlemessage (Message msg) {Bitmap Bitmap=(Bitmap) msg.obj;        Iv.setimagebitmap (bitmap);    };    }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.activity_main); //1. Find ControlsEt_path =(EditText) Findviewbyid (R.id.et_path); IV=(ImageView) Findviewbyid (R.ID.IV); }        //2, click the button to view the source code of the specified path     Public voidClick (View v)throwsIOException {NewThread () { Public voidrun () {Try {                    //2.1. Get the path to the pictureString Path =Et_path.gettext (). toString (). Trim (); File File=NewFile (Getcachedir (), Base64.encodetostring (Path.getbytes (), Base64.default));//test.pngif(File.exists () && file.length () >0 ) {                        //use a cached pictureSYSTEM.OUT.PRINTLN ("Use cached pictures"); Bitmap Cachebitmap=Bitmapfactory.decodefile (File.getabsolutepath ()); //Show the Cachebitmap on the IVMessage msg =Message.obtain (); Msg.obj=Cachebitmap;                                            Handler.sendmessage (msg); }Else{                        //first time access to networked cache picturesSystem.out.println ("First Access connection network"); //2.2 Creating a URL objectURL url =NewURL (path); //2.3 Get HttpURLConnectionHttpURLConnection conn =(HttpURLConnection) url.openconnection (); //2.4 How to set the requestConn.setrequestmethod ("GET"); //2.5 Setting the time-out periodConn.setconnecttimeout (5000); //2.6 Getting the server status code                        intCode =Conn.getresponsecode (); if(Code = = 200){                            //2.7 Get Picture data no matter what data (text pictures) are returned in a popular styleInputStream in =Conn.getinputstream (); //2.7 Cache Images Google provides a cache directoryFileOutputStream fos =Newfileoutputstream (file); intLen =-1 ; byte[] buffer =New byte[1024];//1kb                             while(len = in.read (buffer))! =-1) {fos.write (buffer,0, Len);                            } fos.close ();                                                        In.close (); //2.8 Obtaining bitmap through the bitmap factory//Bitmap Bitmap = Bitmapfactory.decodestream (in);Bitmap Bitmap = Bitmapfactory.decodefile (File.getabsolutepath ());//Read Cache//2.9 Display the bitmap on the IVMessage msg = Message.obtain ();//message pool has a message pool to take data, no new oneMsg.obj =bitmap; Handler.sendmessage (msg);//Send Message                                                    }                                    }                } Catch(Exception e) {e.printstacktrace ();        }            };            }.start (); }}

The configuration is ready to run and see the effect.

Let's talk about the small details of the case.

Because the picture if every time to load, every time from the Internet to read the data stream, display to the phone above, so it is easy to waste customer traffic, so the first visit can download pictures, access to the memory in the future directly in the good.

1, judge whether the customer is the first time to visit

2. Multi-threaded access network

  

  

First time access, create cache folder and save file

Print Log

Access again, remove from file

We can clear the cache from the phone

such as the hippocampus play Simulator: Settings--app--photo viewer, clear cache

  

If we don't give the picture a name, like this

  

The following is the generated file name

So our cell phones often come out of nowhere. We don't know the documents,

Actually just do this a small action, let the user dare not casually delete our file

Android easy to learn bitmap display pictures and cached images

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.