Android obtains images and decodes them into thumbnails to reduce memory consumption,
Content
Download Demo
Environment
- Windows 2008 R2 64-bit
- Eclipse ADT V22.6.2, Android 4.4.3
- SAMSUNG GT-I9008L, Android OS 2.2.2
Demo
Thumbnails can reduce the memory consumption of mobile phones. Network Resources are generally larger for mobile phones, decoding images to reduce their size, thus reducing the memory consumption of mobile phones.
The list of songs used in this article is the Android_Music_Demo_json_h_array.xml file, although the file suffix is. xml, but the internal format is JSON, because cnblog does not allow upload. A file in json format with large thumbnails. jpg format, and the thumbnails in the corresponding Android_Music_Demo_json_array.xml file are very small, so they are less than 10 KB. png format.
Figure 1
For example, if you want to obtain a thumbnail of an image by specifying a link address, the core code is as follows. Click here to download it:
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
// from web
try {
Bitmap bitmap = null;
URL imageUrl = 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 will automatically follow
// redirects or not.
conn.setInstanceFollowRedirects(true);
int response_code = conn.getResponseCode();
if (response_code == 200) {
InputStream is = conn.getInputStream();
OutputStream os = 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
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
final 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
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Download Demo