2016-06-23 40 views
0

下載圖片如下。 buf已加載,已有內容,但setImageBitmap提出警告。任何想法我的代碼有什麼問題? bitmap應該不是null如何在Android中加載/顯示保存在getFilesDir()文件夾中的圖像?

File file = new File(context.getFilesDir(), body + ".image"); 
InputStream in = new BufferedInputStream(new FileInputStream(file)); 
byte[] buf = new byte[(int) file.length()]; 
int numRead = in.read(buf); 
Bitmap bitmap = BitmapFactory.decodeByteArray(buf, 0, numRead); 
ImageView icon = (ImageView) view.findViewById(R.id.icon); 
icon.setImageBitmap(bitmap); 

SkImageDecoder ::廠返回null

enter image description here

回答

0

至於我看到的位圖丟失。然而,你可以這樣做:

try { 
     File f = getFile(); 
     //e.g getFile can return a new File(); 
     if (!f.exists()) { return null; } 
     Bitmap tmp = BitmapFactory.decodeFile(filename); 
     return tmp; 
    } catch (Exception e) { 
     return null; 
    } 
0

首先,你沒有創建位圖(位圖使用的工廠,見下面的代碼) 您可以打開和閱讀主線程文件,什麼減慢應用程序。將所有文件處理移至單獨的線程。 爲此,您可以使用AsyncTask或(更好的)rxJava庫的Schedulers.io()調度程序。我會這樣做:

String body =「myFile」;

final Observable<Bitmap> imageSource = 
    Observable.just(body) 
     .map(new Func1<String, Bitmap>() { 
       @Override 
       public Bitmap call(String body) { 
        File file = new File(BetcadeApplication.this.getFilesDir(), body + ".image"); 
        InputStream in = null; 
        try { 
         in = new BufferedInputStream(new FileInputStream(file)); 
        }catch (FileNotFoundException e){ 
         return null; 
        } 
        return BitmapFactory.decodeStream(in); 
       } 
      } 
     ); 
    Observable.defer(new Func0<Observable<Bitmap>>() { 
     @Override 
     public Observable<Bitmap> call() { 
      return imageSource; 
     } 
    }) 
      .subscribeOn(AndroidSchedulers.mainThread()) 
      .subscribe(new Action1<Bitmap>() { 
       @Override 
       public void call(Bitmap bitmap) { 
        // set result here 
        //ImageView icon = (ImageView) view.findViewById(R.id.icon); 
        //icon.setImageBitmap(bitmap); 
       } 
      }); 
相關問題