2011-09-12 18 views
0

我正在從gallery中搜索圖像,然後顯示出來。現在我想要在onDraw(Canvas canvas)中顯示圖像。我該怎麼做。請親切地幫助我。 在此先感謝如何將uri圖像轉換成canvas抽取方法

selectedImageUri = data.getData(); 
         selectedImagePath = getPath(selectedImageUri); 
         Toast.makeText(getBaseContext(),"selected"+selectedImagePath,Toast.LENGTH_LONG).show(); 
         System.out.println("Image Path : " + selectedImagePath); 
         img.setImageURI(selectedImageUri); 

這裏uri selectedImageUri;

OnDraw(canvas Canvas)代碼:

Bitmap myBitmap1 = BitmapFactory.decodeResource(getResources(),selectedImageUri); 

我的錯誤消息

在類型BitmapFactory方法decodeResource(資源,INT)是不適用的參數(資源URI)

回答

1

從選取器中取回的路徑是一個Uri,並且您試圖將其作爲一個int的資源ID加載。從getData()返回的路徑是直接到SD卡上的文件或MediaStore Uri的文件路徑。如果應用程序將文件保存到磁盤並且不使用任何MediaStore api方法將其插入MediaStore數據庫,則會得到文件路徑。否則,你會得到一個MediaStore Uri。出於這個原因,我使用其確定它是與返回的實際路徑的包裝方法,包括:

public static String getRealPathFromURI(Activity activity, Uri contentUri) {  


    String realPath = null; 

    // Check for valid file path 
    File f = new File(contentUri.getPath()); 
    if(f.exists()) 
     realPath = contentUri.getPath(); 
    // Check for valid MediaStore path 
    else 
    {   
     String[] proj = { MediaStore.Images.Media.DATA }; 
     Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null); 
     if(cursor != null) 
     { 
      int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
      cursor.moveToFirst(); 
      realPath = cursor.getString(column_index); 
      cursor.close(); 
     } 
    } 
    return realPath; 
} 

一旦我有,我加載它從BitmapFactory流:

大量的代碼在這裏省略,所以你可能會遺漏一些東西,但這應該給你一般的方法

FileInputStream in = null; 
    BufferedInputStream buffer = null; 
    Bitmap image = null; 

    try 
    { 
     in = new FileInputStream(path); 
     buffer = new BufferedInputStream(in); 
     image = BitmapFactory.decodeStream(buffer); 
    } 
    catch (FileNotFoundException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    finally 
    { 
     try 
     { 
      if(in != null) 
       in.close(); 
     } 
     catch (IOException e) 
     { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     try 
     { 
      if(buffer != null) 
       buffer.close(); 
     } 
     catch (IOException e) 
     { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
}