2019-02-25
Python 將 Base64 字串還原為圖片
markdown
## 取得 Base64 格式
從網站取得
```
import base64
img_data_base64 = request.POST.get("img_data")
img_b64decode = base64.b64decode(img_data_base64)
```
從檔案取得 Base64 然後將 base64 再解碼
```
import base64
img_file = open(r'image.jpg','rb')
img_b64encode = base64.b64encode(img_file.read())
img_file.close()
img_b64decode = base64.b64decode(img_b64encode)
```
# Python 圖片 Base64 解碼還原 PIL.Image 或 Opencv
Base64 解碼為 OpenCV 圖片:
```
import base64
import numpy as np
img_data_base64= request.POST.get("img_data")
img_data=base64.b64decode(img_data_base64)
img_array = np.fromstring(img_data,np.uint8)
img=cv2.imdecode(img_array,cv2.COLOR_BGR2RGB)
cv2.imshow("img",img)
cv2.waitKey()
```
Base64 解碼為 PIL.Image 圖片:
```
from io import BytesIO
from PIL import Image #pillow
img_data_base64= request.POST.get("img_data")
img_data=base64.b64decode(img_data_base64)
image = BytesIO(img_data)
img = Image.open(image)
```
OpenCV 轉換成 PIL.Image 格式:
```
import cv2
from PIL import Image
import numpy as np
img = cv2.imread("image.jpg")
cv2.imshow("OpenCV",img)
image = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
image.show()
cv2.waitKey()
```
PIL.Image 轉換成 OpenCV 格式:
```
import cv2
from PIL import Image
import numpy as np
image = Image.open("image.jpg")
image.show()
img = cv2.cvtColor(np.asarray(image),cv2.COLOR_RGB2BGR)
cv2.imshow("OpenCV",img)
cv2.waitKey()
```
參考資料來源:
https://blog.csdn.net/dcrmg/article/details/80542665
https://blog.csdn.net/qq_19707521/article/details/78403904
https://blog.csdn.net/qq_19707521/article/details/78367617
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言