python3使用base64将图片转码解码

工作中经常遇到,注意不是将图片名字和路径转码,而是将图片对象转码进行网络间传递,之前用了php写了一个,可以参考之前的笔记:https://sulao.cn/post/544.html

现在主要的代码如下:

将图片转码成base64

#!/usr/bin/python3
#coding:utf-8
import base64

def conv_bs64(image_path):
    with open(image_path, 'rb') as f:
        _obiect = f.read()
    bs64_object = base64.b64encode(_obiect)
    return bs64_object


if __name__ == "__main__":
    print(conv_bs64('d://www/suyang.jpg'))

转换结果如下图

menu.saveimg.savepath20181224200134.jpg

将base64对象解码为图片

#!/usr/bin/python3
#coding:utf-8
import base64

bs64_object = b'/9j/4AAQSkZJRgABAQEAkACQAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCABVAEADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJ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W3059wVBMzEuMYzk88d660zhd0uxn2fM4UZY+wFeGaVrOpafDBLBfIkMEu8wMAAwzyCfevYpRM0W6CZoiRngA4/OuaurSTO3DO8WjRbVo9SiIW3kBiPzkrhSPY+orL8T6kkPhN0kLFDcxbRnByCT/Sq1mt/LL81zLweF8tQD+Vcb4+1wXN8NMgfEdkx83/AGpemPoBx+JqqOsrjxDUYWNW58daxZSiJLO3kTYro4ViCp6d/T9a0P8AhMtZmtYYI7ZbfUJGUfOmB8xwOG9fesnwks92ukRNbmZpHlZGdW2BEDE5KnJA9Md66+LTIJpN2pWjhklUxrHLKqHBBBBbnI4/lWlSVOm7uKOWHtJq3MeK6ZpM/iC+ktrCzvZZwN7R2sRl4z1x/CPqa67TfhR4hv2Ma2ctvGW2NNc4j2+vX/2UH61714d8M6X4Q0z7FpkIG4hp5yB5kzerH+Q6CtEyMWwTwDg03IlRPOdP+Dug6RpsLyxf2jfxP5rSTE7cjoqr0wPfrVTVBIjl4WIY9R616mW+Xk8iuc1fR43f7REg2k5YDsf8DXLXi37yOrDzS0ZxGjfaGucSnqfpgVt33wp8NeJrUanCslleXOZJJEYsrnJySpPGevBFWhZIOVj2sRiuzs41trGGIDCogX8KdCT1HibOx5WPhlrPhspc6Fq91cyJC8RhQKvlAgkFNxOQX25HXArm5YviN54tbvVLYyLgtHJEMr+a+1e7Xl39hsri6xvMULuB/ewMj88Vz9pCXjiTVPJa9mTzC7KZZpHIGdqj7qA8D6VtJXVzKlFt2Rf0LWG13RINQeEQtKDuRWyAQccflV9sbj160UVT3Mx/BYA56VHJtwwIyuOmaKKlgtzPNqglVsk7TnFaO/COOeB60UUopLYuUm9zN1e/On6DfXnliXyIHkCMeCQM4rA8MwHVP7R1C+nmdYpzGYo3MfmMoB3Ow5I5wF4UDsetFFUF2o27n//Z'
_object = base64.b64decode(bs64_object)
with open("d://test.jpg", "wb") as f:
    f.write(_object)


总体感觉python的php要简单些

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://sulao.cn/post/608.html