2016-03-03 61 views
0

我有一個網址的gravatar形象的Python:從URL來檢索文件,並生成數據:URI

url = "http://www.gravatar.com/avatar/0eee0fa5a325a984dab6c1e9c7a1968f?d=retro&s=40" 

我想生成的數據:URI它像蟒蛇以下

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAIAAAADnC86AAAAjklEQVRYhWP0E3dnIAUY9jdiFT9fWE+SOUwkqaYiGHkWs+CSQI5LUuOPGL0jL6gHzGJGYvIxrryLCxCTJkZeUI9aPGoxzQDOshoXwJVHSc3rIy+oB0dZTa32FDHmjLygHnz5GDk+KKmPcekdeUE9OPIxMsDVNiYmj462qweVxUS1q2kBRl5Qj1o8ajHNAABQ3ieujBTqugAAAABJRU5ErkJggg==

+0

請提供您的代碼嘗試。並解釋什麼目前沒有爲你工作。 – idjaw

回答

1

使用base64requests

import base64 
import requests 

url = "https://www.gravatar.com/avatar/0eee0fa5a325a984dab6c1e9c7a1968f?d=retro&s=40" 
response = requests.get(url) 
content_type = response.headers["content-type"] 
encoded_body = base64.b64encode(response.content) 
print("data:{};base64,{}".format(content_type, encoded_body.decode())) 

響應:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAIAAAADnC86AAAAjklEQVRYhWP0E3dnIAUY9jdiFT9fWE+SOUwkqaYiGHkWs+CSQI5LUuOPGL0jL6gHzGJGYvIxrryLCxCTJkZeUI9aPGoxzQDOshoXwJVHSc3rIy+oB0dZTa32FDHmjLygHnz5GDk+KKmPcekdeUE9OPIxMsDVNiYmj462qweVxUS1q2kBRl5Qj1o8ajHNAABQ3ieujBTqugAAAABJRU5ErkJggg== 
+0

顯示錯誤'AttributeError:'模塊'對象沒有屬性'encodebytes'' – Satwik

+0

您使用的是什麼版本的Python? – 2016-03-03 14:17:40

+1

我使用python 2.7 – Satwik