Created
June 1, 2011 20:32
-
-
Save hwrdprkns/1003242 to your computer and use it in GitHub Desktop.
BitmapScalingAndroid
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private Drawable LoadThumbnailFromURL(String url) { | |
if(downloader.getBitmapFromCache(url) != null){ | |
Bitmap b = downloader.getBitmapFromCache(url); | |
//HERE IS WHERE I WANT TO SCALE THE IMAGE IF ITS IN THE CACHE | |
} | |
try { | |
URLConnection connection = new URL(url).openConnection(); | |
String contentType = connection.getHeaderField("Content-Type"); | |
boolean isImage = contentType.startsWith("image/"); | |
if (isImage) { | |
HttpGet httpRequest = new HttpGet(url); | |
HttpClient httpclient = new DefaultHttpClient(); | |
HttpResponse response = (HttpResponse) httpclient | |
.execute(httpRequest); | |
HttpEntity entity = response.getEntity(); | |
BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity( | |
entity); | |
InputStream is = bufferedHttpEntity.getContent(); | |
downloader.putBitmapInCache(url,BitmapFactory.decodeStream(is)); | |
// Decode image size | |
BitmapFactory.Options o = new BitmapFactory.Options(); | |
o.inJustDecodeBounds = true; | |
BitmapFactory.decodeStream(is, null, o); | |
// The new size we want to scale to | |
final int REQUIRED_SIZE = 150; | |
// Find the correct scale value. It should be the power of 2. | |
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 | |
is = bufferedHttpEntity.getContent(); | |
BitmapFactory.Options o2 = new BitmapFactory.Options(); | |
o2.inSampleSize = scale; | |
Bitmap b = BitmapFactory.decodeStream(is, null, o2); | |
Drawable d = new BitmapDrawable(b); | |
return d; | |
} else { | |
Bitmap b = BitmapFactory.decodeResource(getResources(), | |
R.drawable.no_image); | |
Drawable d = new BitmapDrawable(b); | |
return d; | |
} | |
} catch (Exception e) { | |
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG) | |
.show(); | |
Log.e(e.getClass().getName(), e.getMessage(), e); | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment