Base64可以将任何二进制文件以可打印字符的方式表示,也就是说,任何二进制文件都可以通过Base64编码技术转成字符串。在Java中,可以使用Base64类实现。
1、图片(二进制文件)转字符串
import base64
f = open('E://cc.jpg','rb')
imagebytes = base64.b64encode(f.read())
f.close()
imagestr = str(imagebytes)
##转成base64后的字符串格式为 b'图片base64字符串',前面多了 b',末尾多了 ',所以需要截取一下
realimagestr = imagestr[2:len(imagestr)-1]
print(realimagestr)
2、字符串转图片(二进制文件)
import base64
## 图片的base64字符串
imagestr = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDAkKCgr/2wBDAQICAgICAgUDAwUKBwYHCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgr/wAARCACkADoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6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XCeeqdPsiaL4F/ArQoBpum/BHwkkIP3W0GFv1K5p17pPhvQbcRaB4R0mwAGxfsenpHtXPQYHFFFbw1Wp0ezp6aIz9IImlKuigeY3CqAOp9O/f3q81tFk/L39aKK8qaXOz3sG3yH/2Q=="
## 新图片保存路径
imagepath = "E://aabb.jpg"
file = open(imagepath, 'wb')
file.write(base64.b64decode(imagestr))