简体   繁体   中英

Encode part image in python

Now I want to encode part image in base64 and I did do it. For example, here is an image 1080x1920, but part of this image is needed.

Top:160, left:340, right:1024, bottom: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.

You can use tobytes for a raw image

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.

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:

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. Examples of compressed formats are 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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