Base64 encoding images in Python 3

A memo of the code used to encode the image with WebSocket and then send it with Base64. Is there an easier way?

import base64

img_file = 'hoge.jpg'
b64 = base64.encodestring(open(img_file, 'rb').read())
try:
    # Python2                                                                                                                                                          
    print('b64=' + b64)
except TypeError:
    # Python3                                                                                                                                                          
    print('b64=' + b64.decode('utf8'))

Recommended Posts

Base64 encoding images in Python 3
Encoding judgment in Python
Python encoding
Number recognition in images with Python
Pixel manipulation of images in Python
How to collect images in Python
Extract text from images in Python
Working with DICOM images in Python
Quadtree in Python --2
Python in optimization
CURL in python
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Mosaic images in various shapes (Python, OpenCV)
What I was addicted to with json.dumps in Python base64 encoding
To set default encoding to utf-8 in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
[python, openCV] base64 Face recognition with images
Download images from URL list in Python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
Get rid of DICOM images in Python
DirectLiNGAM in Python
Read text in images with python OCR
LiNGAM in Python
Flatten in python
flatten in python
[Python] Save images drawn in canvas using Selenium (ActionChains, PyAutoGUI, base64, etc.)
Convert PDFs to images in bulk with Python
Note on encoding when LANG = C in Python
Getting rid of DICOM images in Python Part 2
Character encoding when dealing with files in Python 3