有时候需要一个远程图片的base64编码而不想下载图片,其实可以通过几条简单的命令就可以获取到图片的base64编码
直接看下面的例子吧
#!/usr/bin/python3 #coding:utf-8 from io import BytesIO import requests import base64 img_url = "https://sulao.cn/zb_users/theme/plain/style/images/logo.png" response = requests.get(img_url) img_bs64 = base64.b64encode(BytesIO(response.content).read()) print(img_bs64)
打印的结果是
b'iVBORw0KGgoAAAANSUhEUgAAAOYAAAA8CAYAAAByz8byAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6MzA0M0JGQTI2MTk0MTFFNTk1NjRCNDMxODIyOTRCNjciIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6MzA0M0JGQTM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9khqoem+ZeA6GOPep0hYqw8CAQPYe+AvAwxx571n4ujl1FvjJgKv5f2DbHZS5//pMsRIj3Gwr50gfdb+l6GLETzLXOwQ+YifInB5xY76s6fjOBhY9aDqv/bxG93tblt77HZVpiggTG0/otNE/NTab+T9lWxmR37C53/pwHvzhzSb9fSWX1H/hj3lE5F86tBXTOgtucoO38WhI7ZlJhz3aeygG935W1bm4Y3PpiJtrxBuXdCpezWer0OzvXDixddscWvRbc/LPQPcfizf0dGJ89ZYNXxroDRsWqDeOpBlpibyxMRfitd3ZorvEenrPCYcJ11WdG5baSMKaGHhEG/bikJtnkB5KtN7g4DB9VgtEFMha5+H1PhIz0QWCd8CMszptGP/X0xDHHs27ytH65VJPm3tF+Iwx+XbQt/lfZbae9ESMt3PZFxctDbNj/VYtqKLP8Uh+ubSg7F/Ln3z3Xc8bpy3Ny/GCcNp1pOX5HmZ9L+Jk3p3gsR0rwkTenTt7j5GEzMZlAk+rO0F6Q9L+05QbsoS91E8K72wm8L2pUhDAYTswIH2tMpe1wcbnx/Uv+tbkE4I+0BaZ9JuynturSr0j4Qh6dErnJzMe4VNJqVZTAY7eA+rgIGg4nJYDCYmAwGE5PBYDAxGQwmJoPBYGIyGExMBoPRM/xPgAEAxB8Nkb34qNwAAAAASUVORK5CYII='
如果我们需要将图片再写入到硬盘那么很简单,b64decode解码后使用二进制模式写入文件即可
with open("1.jpg", "wb") as f: f.write(base64.b64decode(img_bs64))