2014-05-15 161 views
63

我可以使用Picasso庫從文件系統加載圖像嗎?Picasso從文件系統加載圖像

我使用startActivityForResult來讓用戶從他的畫廊中選擇一張照片,然後顯示所選圖像。

我已經有工作代碼來獲取圖像文件系統Uri,但無法使Picasso.load()方法工作。

回答

120

當然可以。它實際上相當直截了當:

File f = new File("path-to-file/file.png") 

File f = new File(uri) 

Picasso.with(getActivity()).load(f).into(imageView); 

Picasso.with(getActivity()).load(uri).into(imageView); 

工作

+8

我不知道這是否是畢加索要求從文件系統(以字符串格式)加載圖像的「特定」URI格式。但是我使用了從ActivityResult返回的那個,直到我傳遞一個File對象,而不是直接傳遞給String,它才工作。 – Gonan

+6

我想這樣做,但這是行不通的,我從另一個活動文件到我的應用程序緩存,但畢加索不加載它... – Loenix

21

是的,你可以。

嘗試:

Picasso.with(context).load(new File(YOUR_FILE_PATH)).into(imageView); 

編輯

您也可以撥打.load(YOUR_URI),而不是爲好。

+0

感謝您再次提醒我.. –

18

尋找在源代碼中,我還發現,你可以從文件系統加載圖像將file:字符串前綴添加到您的圖像路徑。例如:

file:path/to/your/image 

此外,使用startActivityForResult時,你會得到這樣的事情:

Uri imageContent = data.getData(); 

然後,您可以直接撥打Picasso.with(getContext()).load(imageContent.toString).into(imageView);,而無需創建一個Cursor和查詢圖像路徑。

+2

謝謝,我沒有工作,直到我看到你的答案,「文件:「需要前綴。 – henry000

+0

我不知道爲什麼它不起作用。有我的路徑 - 「file:/storage/emulated/0/Android/data/com.fittingroom.newtimezone/files/default/AvatarPackage/DEFAULT_MY_AVATAR/pose1.jpeg」,但任何結果( –

+1

@AlekseyTimoshchenko它應該以' file://'。你的Uri丟失了第二個'/'。 – Sufian

2

基本上,我們需要三樣東西,Contextimage´s pathImageView集裝箱

Picasso.with(context).load("/files/my_image.jpg").into(myImageView); 

,但我們可以利用更多的選擇:

.resize(20, 20) 
    .centerCrop() 
    .placeholder(R.drawable.user_placeholder) 
    .error(R.drawable.user_placeholder_error) 

等等

更多信息:http://square.github.io/picasso/

6

試試這個:

Picasso.with(context) 
.load("file://"+path) // Add this 
.config(Bitmap.Config.RGB_565) 
.fit().centerCrop() 
.into(imageView); 

它的工作非常適合我。

+0

mh,我會使用RGB_8888,除非你有內存限制的問題,因爲圖像很大 – Zharf

+0

我的意思是ARGB_8888 ... – Zharf