日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

OCR-PIL.Image与Base64 String的互相转换

發布時間:2025/3/15 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 OCR-PIL.Image与Base64 String的互相转换 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1. 基本環境

  • py2: python2.7.13
  • py3: python3.6.2
  • PIL: pip(2/3) install pillow, PIL庫已不再維護,而pillow是PIL的一個分支,如今已超越PIL

2.?Convert PIL.Image to Base64 String

  • py2 :先使用CStringIO.StringIO把圖片內容轉為二進制流,再進行base64編碼
# -*- coding: utf-8 -*-import base64 from cStringIO import StringIO# pip2 install pillow from PIL import Imagedef image_to_base64(image_path):img = Image.open(image_path)output_buffer = StringIO()img.save(output_buffer, format='JPEG')binary_data = output_buffer.getvalue()base64_data = base64.b64encode(binary_data)return base64_data
  • py3:python3中沒有cStringIO,對應的是io,但卻不能使用io.StringIO來處理圖片,它用來處理文本的IO操作,處理圖片的應該是io.BytesIO
import base64 from io import BytesIO# pip3 install pillow from PIL import Image# 若img.save()報錯 cannot write mode RGBA as JPEG # 則img = Image.open(image_path).convert('RGB') def image_to_base64(image_path):img = Image.open(image_path)output_buffer = BytesIO()img.save(output_buffer, format='JPEG')byte_data = output_buffer.getvalue()base64_str = base64.b64encode(byte_data)return base64_str

3.?Convert Base64 String to PIL.Image

  • py2:
# -*- coding: utf-8 -*-import re import base64 from cStringIO import StringIOfrom PIL import Imagedef base64_to_image(base64_str, image_path=None):base64_data = re.sub('^data:image/.+;base64,', '', base64_str)binary_data = base64.b64decode(base64_data)img_data = StringIO(binary_data)img = Image.open(img_data)if image_path:img.save(image_path)return img
  • py3:
import re import base64 from io import BytesIOfrom PIL import Imagedef base64_to_image(base64_str, image_path=None):base64_data = re.sub('^data:image/.+;base64,', '', base64_str)byte_data = base64.b64decode(base64_data)image_data = BytesIO(byte_data)img = Image.open(image_data)if image_path:img.save(image_path)return img

4. 參考網址

[1]?https://stackoverflow.com/questions/16065694/is-it-possible-to-create-encodeb64-from-image-object

[2]?https://stackoverflow.com/questions/31826335/how-to-convert-pil-image-image-object-to-base64-string

[3]?https://stackoverflow.com/questions/26070547/decoding-base64-from-post-to-use-in-pil

?

?

?

?

?

與50位技術專家面對面20年技術見證,附贈技術全景圖

總結

以上是生活随笔為你收集整理的OCR-PIL.Image与Base64 String的互相转换的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。