Reputation: 14843
I read an jpg image with python using pillow module:
from PIL import Image
img = Image.open('./test.jpg')
bytes = img.tobytes()
If I print bytes
I get something like this:
print(f'{bytes}')
# b'\xbe\xb0i\xb1\xa4^\xb1\xaad\xab\xa7`\xc2\xc0v\x96\x91Oj_2\xb7...
I send then this 'bytes string' to my js
to display it:
var b64imgData = btoa(bytes); // bytes is the 'bytes string' show upper
var img = new Image();
img.src = "data:image/jpg;base64," + b64imgData;
$('#imgCtn').append(img);
Sadly the final image source doesn't seem to be valid because I get the invalid image icon instead of my image test.jpg
.
Has someone an idea where the issue is ?
EDIT 1:
As it is mentionned by @cubrr don't use img.tobytes()
method for jpg files. So for the python code please use this one:
from PIL import Image
img = Image.open('./test.jpg')
imageBytes = io.BytesIO()
img.save(imageBytes, format='JPEG')
bytes = imageBytes.getvalue()
Upvotes: 3
Views: 555
Reputation: 13652
From the documentation of Pillow:
Image.tobytes(encoder_name='raw', *args)
...
Warning: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use save(), with a BytesIO parameter for in-memory data.
So try using save
to get the JPG bytes instead of the raw internal image data:
img = Image.open('./test.jpg')
imageBytes = io.BytesIO()
img.save(imageBytes, format='JPEG')
bytes = imageBytes.getvalue()
If if still does not work, please elaborate on what you mean by "send this bytes string to my js". How are you sending and receiving it (code please)?
Upvotes: 1