Content of this article
Download Demo
Environment
- Windows R2 64-bit
- Eclipse ADT v22.6.2,android 4.4.3
- SAMSUNG gt-i9008l,android OS 2.2.2
Demonstrate
Thumbnails can reduce the memory consumption of your phone. The resources on the network generally to the handset, the big point, the picture decoding, reduces its size, thus reduces the handset memory consumption.
The song list used in this article is the Android_music_demo_json_h_array.xml file, although the file suffix is. xml, but the inside is actually in JSON format, because Cnblog does not allow uploading. JSON-formatted files, which have a larger thumbnail size, are . jpg format, and the corresponding android_music_demo_json_array.xml files in the thumbnail, are very small, are less than 10k. png format.
Figure 1
Given an image link address, want to get a thumbnail image, the core code is as follows, click here to download:
Private Bitmap getbitmap (String URL) {
File f = filecache.getfile (URL);
From SD Cache
Bitmap B = DecodeFile (f);
if null)
return B;
From web
Try {
null;
New URL (URL);
HttpURLConnection conn = (httpurlconnection) imageUrl
. OpenConnection ();
Conn.setrequestmethod ("GET");
Sets the flag indicating whether this urlconnection allows input.
Conn.setdoinput (TRUE);
Conn.setconnecttimeout (3000);
Conn.setreadtimeout (3000);
Flag to define whether the protocol would automatically follow
Redirects or not.
Conn.setinstancefollowredirects (true);
int response_code = Conn.getresponsecode ();
if (Response_code = = 200) {
is = Conn.getinputstream ();
New FileOutputStream (f);
Streamutils.copystream (is, OS);
Os.close ();
Conn.disconnect ();
Bitmap = DecodeFile (f);
return bitmap;
Else {
Conn.disconnect ();
return null;
}
Catch (Throwable ex) {
Ex.printstacktrace ();
if (ex instanceof OutOfMemoryError)
Memorycache.clear ();
return null;
}
}
Private Bitmap DecodeFile (File f) {
Try {
Decode Image size
New Bitmapfactory.options ();
true;
New FileInputStream (f);
null, O);
Stream1.close ();
Find the correct scale value. It should be the power of 2.
int Required_size = 70;
int width_tmp = o.outwidth, height_tmp = o.outheight;
int scale = 1;
while (true) {
if (Width_tmp/2 < Required_size
|| HEIGHT_TMP/2 < Required_size)
break;
Width_tmp/= 2;
Height_tmp/= 2;
Scale *= 2;
}
Decode with Insamplesize
New Bitmapfactory.options ();
O2.insamplesize = scale;
New FileInputStream (f);
null, O2);
Stream2.close ();
return bitmap;
Catch (FileNotFoundException e) {
Catch (IOException e) {
E.printstacktrace ();
}
return null;
}
Download Demo