Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,是一种基于64个可打印字符来表示二进制数据的方法。通过http传输图片常常将图片数据转换成base64之后再进行传输。
Base64简介
Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,Base64就是一种基于64个可打印字符来表示二进制数据的方法。可查看RFC2045~RFC2049,上面有MIME的详细规范。
Base64编码是从二进制到字符的过程,可用于在HTTP环境下传递较长的标识信息。例如,在Java Persistence系统Hibernate中,就采用了Base64来将一个较长的唯一标识符(一般为128-bit的UUID)编码为一个字符串,用作HTTP表单和HTTP GET URL中的参数。在其他应用程序中,也常常需要把二进制数据编码为适合放在URL(包括隐藏表单域)中的形式。此时,采用Base64编码具有不可读性,需要解码后才能阅读。
Python中将图片转base64
# -*- coding: utf-8 -*- import base64 with open("/home/chaowei/1.png","rb") as f: # b64encode是编码,b64decode是解码 base64_data = base64.b64encode(f.read()) # base64.b64decode(base64data) print(base64_data)
在前端html中调用base64编码
<img src="data:image/jpg;base64,这里是base64的编码"/>
另外,有很多网站提供转换API,在线编码解码
base64转为图片
import os,base64 with open("C:\\Users\\wonai\\Desktop\\1.txt","r") as f: #str = "iVBORw0KGgoAAAANSUhEUgAAANwAAAAoCAIAAAAaOwPZAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAQuSURBVHhe7ZptmoMgDIR7rh6o5+lpvEwP01XUGshAokgX+8z+7PKRTF6SoN7e/KMCnSlw68wemkMF3oSSEHSnAKHsLiQ0iFCSge4UIJTdhYQGEUoy0J0ChLK7kNAgQkkGulOAUHYXEhpEKMlAdwpcG8rhcRv/HkN3stIgW4F88DYoX89nObjmANuOc0eMXpHHcyX9+mowhgHKmdlChM0BZzvzet6DSSW7xjEWk8Hu+/O1x7zF1237/Uu4t/O46V6sZuARoZb9KqbO7On4rJlykqcYYnNAjSbx3Gmrj6WTzxirVlA+90F82G+nm4fX3zOxgqyKqRaUU7b8FpRDOeyjJa7k5oByT1yWse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SAAAAABJRU5ErkJggg==" imgdata = base64.b64decode(f.read()) file = open('1.jpg','wb') file.write(imgdata) file.close()
Python中将base64转为opencv的Mat格式
import cv2 import base64 imgData = base64.b64decode(base64_data) nparr = np.fromstring(imgData, np.uint8) img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR) #cv2.imshow("test",img_np) #cv2.waitKey(0)
Python中将opencv的Mat格式转为base64
import cv2 import base64 imgData = base64.b64decode(base64_data) nparr = np.fromstring(imgData, np.uint8) img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR) image = cv2.imencode('.jpg', img_np)[1] base64_data = str(base64.b64encode(image))[2:-1])
到此这篇关于Python OpenCV实现传统图片格式与base64转换的文章就介绍到这了,更多相关OpenCV传统图片格式与base64转换内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!