Android - 縦横比を守ってネットから画像を取得
IMAGE_MAX_HEIGHT、IMAGE_MAX_WIDTHを適当に設定してあげれば、引数のURLの画像をBitmapにして返します。Android端末において、Bitmapがメモリ的にかなりくせものなので、finallyでgcしてます。本当にこれが最適なのかは謎^^
public static Bitmap getBitmapFromURL(String strUrl) throws IOException {
HttpURLConnection con = null;
InputStream in = null;
Bitmap bitmap = null;
Matrix matrix = null;
try {
URL url = new URL(strUrl);
con = (HttpURLConnection) url.openConnection();
con.setUseCaches(true);
con.setRequestMethod("GET");
con.setReadTimeout(500000);
con.setConnectTimeout(50000);
con.connect();
in = con.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
options.inPreferredConfig = Bitmap.Config.RGB_565;
bitmap = BitmapFactory.decodeStream(in, null, options);
int h = bitmap.getHeight();
int w = bitmap.getWidth();
float resizeScaleHeight = IMAGE_MAX_HEIGHT / Float.valueOf(h);
float resizeScaleWidth = IMAGE_MAX_WIDTH / Float.valueOf(w);
if (resizeScaleHeight > resizeScaleWidth && w > IMAGE_MAX_WIDTH) {
resizeScaleHeight = IMAGE_MAX_WIDTH / Float.valueOf(w);
resizeScaleWidth = IMAGE_MAX_WIDTH / Float.valueOf(w);
} else if (h > IMAGE_MAX_HEIGHT) {
resizeScaleHeight = IMAGE_MAX_HEIGHT / Float.valueOf(h);
resizeScaleWidth = IMAGE_MAX_HEIGHT / Float.valueOf(h);
}
matrix = new Matrix();
matrix.postScale(resizeScaleWidth, resizeScaleHeight);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
} finally {
try {
if (con != null)
con.disconnect();
if (in != null)
in.close();
} catch (Exception e) {
}
bitmap = null;
matrix = null;
System.gc();
}
}