简体   繁体   English

用python编码零件图像

[英]Encode part image in python

Now I want to encode part image in base64 and I did do it. 现在,我想在base64中编码零件图像,并且做到了。 For example, here is an image 1080x1920, but part of this image is needed. 例如,这是一个1080x1920的图像,但是需要该图像的一部分。

Top:160, left:340, right:1024, bottom:650. 上:160,左:340,右:1024,下:650。

# first crop
im = Image.open(original)
region = im.crop((160, 340, 1024, 650))
clip_image = os.path.join(screenshot_dir, 'clip.png')
region.save(clip_image)
// then read
f = open(clip_image, 'rb')
ls_f = base64.b64encode(f.read())
f.close()
s = bytes.decode(ls_f)

In my opinion, maybe I do not have to save resized image and I can read part of this image directly. 我认为,也许我不必保存调整大小的图像,并且可以直接读取该图像的一部分。 If so, the program can run faster because there is no extra IO operation. 如果是这样,则由于没有额外的IO操作,程序可以运行得更快。

You can use tobytes for a raw image 您可以使用tobytes来获取原始图像

This method returns the raw image data from the internal storage. 此方法从内部存储器返回原始图像数据。 For compressed image data (eg PNG, JPEG) use save(), with a BytesIO parameter for in-memory data. 对于压缩的图像数据(例如PNG,JPEG),请使用save(),并将BytesIO参数用于内存中的数据。

im = Image.open(original)
region = im.crop((160, 340, 1024, 650))

ls_f = base64.b64encode(region.tobytes())
s = bytes.decode(ls_f)

If it is a png or jpg, you need to use BytesIO , perhaps like this: 如果是png或jpg,则需要使用BytesIO ,也许像这样:

im = Image.open(original)
region = im.crop((160, 340, 1024, 650))
with io.BytesIO() as temp_file:
    region.save(temp_file)
    ls_f = base64.b64encode(temp_file.getvalue())

s = bytes.decode(ls_f)

it depends on the format of the input image. 它取决于输入图像的格式。 If it is not compressed, like a bitmap bmp, it's raw. 如果未压缩(如位图bmp),则为原始数据。 Examples of compressed formats are png, jpeg, gif. 压缩格式的示例包括png,jpeg,gif。 Easiest way is to look at the extension, or to try it out. 最简单的方法是查看扩展名或进行尝试。 If you try the first approach on a compressed image, it'll probably raise an Exception, or return a distorted image 如果您对压缩图像尝试第一种方法,则可能会引发Exception或返回变形的图像

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM