自定义imagegetter()的实现。
安卓软件开发--关于自定义imagegetter()的实现。
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.text.Html;
/*
* @Author H3R3T1C
* Email: th3h3r3t1c@gmail.com
*/
public class CustomImageGetter implements Html.ImageGetter{
// NOTE: The directories must already exist
final static String CACHE_DIR = "/sdcard/DIC/image_cache/";
@Override
public Drawable getDrawable(String url) {
try{
// get name of image
String name = url.substring(url.lastIndexOf("/")+1);
// cache dir + name of image + the image save format
File f = new File(CACHE_DIR+name+".png");
if(!f.exists())// if it does not exist in the cache folder we need to download it
downloadImage(url,f);
Drawable d = Drawable.createFromPath(f.getAbsolutePath());
d.setBounds(0, 0, 32, 32);// make it the size of the image
return d;
}catch(Exception e)
{
e.printStackTrace();
}
return null;
}
private void downloadImage(String url,File f) throws IOException
{
URL myFileUrl =new URL(url);
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
Bitmap bm = BitmapFactory.decodeStream(is);
FileOutputStream out = new FileOutputStream(f);
bm.compress(Bitmap.CompressFormat.PNG, 90, out);
}
}