Java tutorial
//package com.java2s; //License from project: Apache License import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.UUID; public class Main { public static Bitmap decodeSampledBitmapFromUrl(String urlpath, long allowedBmpMaxMemorySize) { String tmpDir = System.getProperty("java.io.tmpdir", "."); File saveFile = new File(tmpDir, UUID.randomUUID().toString()); if (saveFile.exists()) { saveFile.delete(); } try { saveFile.createNewFile(); File ret = downloadFile(urlpath, saveFile); if (ret == null) {// fail. return null; } Bitmap bmp = decodeSampledBitmapFromPath(saveFile.getAbsolutePath(), allowedBmpMaxMemorySize); return bmp; } catch (Throwable err) { err.printStackTrace(); } finally { if (saveFile.exists()) { saveFile.delete();// true. } } return null; } public static File downloadFile(String urlstr, File saveFile) { try { URL url = new URL(urlstr);// cause speed low. URLConnection con = url.openConnection(); con.setDoInput(true); con.connect(); InputStream ins = con.getInputStream(); final int bufsize = 102400; byte[] buffer = new byte[bufsize]; int len = -1; FileOutputStream bos = new FileOutputStream(saveFile); while ((len = ins.read(buffer)) != -1) { bos.write(buffer, 0, len); } ins.close(); bos.close(); return saveFile; } catch (Error e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static Bitmap decodeSampledBitmapFromPath(String localpath, long allowedBmpMaxMemorySize) { try { final Options options = new Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(localpath, options); options.inSampleSize = calculateInSampleSize(options, allowedBmpMaxMemorySize); options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(localpath, options); } catch (Throwable err) { err.printStackTrace(); } return null; } /** * assume one pix use 4 bytes.Bitmap.Config.ARGB_8888. */ private final static int calculateInSampleSize(Options options, long reqMemorySize) { final int onePixBytes = 4; int reqPixs = (int) (reqMemorySize / onePixBytes); final int height = options.outHeight; final int width = options.outWidth; int orgPixs = height * width; int inSampleSize = 1; while (orgPixs / Math.pow(inSampleSize, 2) > reqPixs) { inSampleSize *= 2; } return inSampleSize; } }