我使用pillow模块用Python读取了一张jpg图片:
from PIL import Image
img = Image.open('./test.jpg')
bytes = img.tobytes()
如果我打印
bytes
,会得到类似这样的东西:print(f'{bytes}')
# b'\xbe\xb0i\xb1\xa4^\xb1\xaad\xab\xa7`\xc2\xc0v\x96\x91Oj_2\xb7...
我将这个“bytes string”发送给我的js
来显示:
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);
很遗憾,最终的图像源似乎无效,因为我得到了无效图像图标,而不是我的图像
test.jpg
。 有人知道问题出在哪里吗?
编辑1:
正如@cubrr所提到的,不要使用img.tobytes()
方法处理jpg文件。因此,请使用以下Python代码:
from PIL import Image
img = Image.open('./test.jpg')
imageBytes = io.BytesIO()
img.save(imageBytes, format='JPEG')
bytes = imageBytes.getvalue()