我下載很多圖像形成服務器,一些圖像顯示良好,但其他沒有顯示:我的關鍵代碼:下載PIC,但PIC不會顯示
private Bitmap getBitmap(String url)
{
//I identify images by hashcode. Not a perfect solution, good for the demo.
String filename=String.valueOf(url.hashCode());
File f=new File(cacheDir, filename);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Bitmap bitmap=null;
InputStream is=new URL(url).openStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//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++;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
public class Utils {
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
我也看了http://code.google.com/p/android/issues/detail?id=6066,在這些鏈接它使用
Bitmap bmp = BitmapFactory.decodeStream(new PatchInputStream(in));
,但在我的代碼,我用
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
我DONOT知道如何形成的FileInputStream(六)變更爲p atchInputStream(in),你能給我一些建議嗎?謝謝
什麼是patchInputStream( ) 這裏? –
IH鏈接http://code.google.com/p/android/issues/detail?id=6066 – pengwang
patchInputStream正在擴展FilterInputStream的類 更多細節該類找 http://download.oracle.com /javase/1.4.2/docs/api/java/io/FilterInputStream.html – Mihir