下载图片,但图片没有显示

时间:2011-09-06 05:39:14

标签: android bitmap

我从服务器下载了许多图像,一些图像显示良好,但其他图像不显示:我的密钥代码:

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);

我不知道如何将表单FileInputStream(f)更改为patchInputStream(in),你能给我一些建议吗?谢谢

1 个答案:

答案 0 :(得分:1)

试试这个::

      tran_btn_skip = (ImageView) findViewById(R.id.tran_btn_skip);
 try {
        Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
                "http://xyz/MRESC/images/test/skip.png")
                .getContent());
        tran_btn_skip.setImageBitmap(bitmap);
    } catch (Exception e) {
    }

其中tran_btn_skipimageview,或者您可以ImageButton

将图像存储在sdcard ::

save image to sdcard android Directory problem