2017-02-01 5 views
1

以下の関数を使用してURLから画像をダウンロードしています。ときどきBitmapFactory.decodeStreamがnullになっています。この問題のため、通知は画像なしで受信しています。いずれか..その問題を解決するために私たちを助けるBitmapFactory.decodeStreamはダウンロード中にヌル値を返します

は、これは私のコードです:ビットマップのサイズは、我々は、ビットマップのサイズを変更する必要が高すぎる

private Bitmap getImageBitmap(String url) 
{ 
     Bitmap bmsd = null;  
     URL aURL = new URL(url); 
     URLConnection conn = aURL.openConnection(); 
     conn.connect(); 
     InputStream is = conn.getInputStream(); 
     BufferedInputStream bis = new BufferedInputStream(is); 
     bmsd = BitmapFactory.decodeStream(bis); 
     bis.close(); 
     is.close(); 
     return bmsd; 
} 
+0

decodeStream()がnullを返す正常を終了します。ビットマップが利用可能なメモリのために大きくなる場合は、常にそうです。 – greenapps

答えて

0

は、このようにしてみてください。

private Bitmap getBitmap(String url) 
    { 
     File f=fileCache.getFile(url); 

     //from SD cache 
     Bitmap b = decodeFile(f); 
     if(b!=null) 
      return b; 

     //from web 
     try { 
      Bitmap bitmap=null; 
      URL imageUrl = new URL(url); 
      HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection(); 
      conn.setConnectTimeout(30000); 
      conn.setReadTimeout(30000); 
      conn.setInstanceFollowRedirects(true); 
      InputStream is=conn.getInputStream(); 
      OutputStream os = new FileOutputStream(f); 
      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. 
      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*=2; 
      } 

      //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 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){} 
    } 
+0

しかし、画像サイズは50KB未満です.... –

関連する問題