2013-04-25 230 views
13

我正在將圖像轉換爲base64字符串並將其從android設備發送到服務器。現在,我需要將該字符串更改爲圖像並將其保存在數據庫中。如何將base64字符串轉換爲圖像?

任何幫助?

+1

如果你知道如何轉換的東西爲Base64,想必你知道如何將其轉換回?它是同一個模塊。 – Cairnarvon 2013-04-25 12:05:09

+1

好吧,只需將您從映像轉換爲base64時所做的相反。既然你沒有提供任何細節,沒有人能比這更具體。 – 2013-04-25 12:05:10

回答

35

試試這個:

import base64 
imgdata = base64.b64decode(imgstring) 
filename = 'some_image.jpg' # I assume you have a way of picking unique filenames 
with open(filename, 'wb') as f: 
    f.write(imgdata) 
# f gets closed when you exit the with statement 
# Now save the value of filename to your database 
+0

@rmunn ...'wb'指的是什麼?! – omarsafwany 2013-05-02 01:27:09

+4

@omarsafwany它的意思是「w」rite和「b」inary http://stackoverflow.com/questions/2665866/what-is-the-wb-mean-in-this-code-using-python – HydrUra 2013-12-16 22:26:17

+0

@rmunn:非常感謝你爲這些線路!我知道,評論不是要說謝謝,但你真的節省了我的時間! – HydrUra 2013-12-16 22:28:00

0

這應該做的伎倆:

image = open("image.png", "wb") 
image.write(base64string.decode('base64')) 
image.close() 
1

只需使用方法.decode('base64')去快樂。

你需要,也檢測MIME類型/擴展的圖像,你可以正確的儲存,在一個簡單的例子,你可以使用下面的代碼Django視圖:

def receiveImage(req): 
    image_ext = req.REQUEST["image_filename"] # A field from the Android device 
    image_data = req.REQUEST["image_data"].decode("base64") # The data image 
    filehandler = fopen($image_ext, "wb+") 
    filehandler.write(image_data) 
    filehandler.close() 

而且,之後,根據需要使用$文件。

簡單。很簡單。 ;)

0

在你想不保存到顯示圖像的情況下:

from PIL import Image 
import cv2 
    # Take in base64 string and return cv image 
    def stringToRGB(base64_string): 
     imgdata = base64.b64decode(str(base64_string)) 
     image = Image.open(io.BytesIO(imgdata)) 
     return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB) 
相關問題