-1

I'm creating a program that merges two image not stored in local, this third image, the merged one, is a PIL Image, I need to check the image filesize and, if it is over a certain size, I need to compress it.

This is my code:


def concat_image_auto(image1,image2,size_image):
    if size[0]>size[1]:
        ## vertical
        dst = Image.new('RGB', (size_image[0], image1.height + image2.height))
        dst.paste(image1, (0, 0))
        dst.paste(image2, (0, image1.height))
    else:
        ## horizontal
        dst = Image.new('RGB', (image1.width + image2.width, size_image[1]))
        dst.paste(image1, (0, 0))
        dst.paste(image2, (image1.width, 0))
    return dst


image1 = Image.open('my_first_image.jpg')     
image2 = Image.open('my_second_image.jpg') 

max_w = max(image1.size[0],image2.size[0])
max_h = max(image1.size[1],image2.size[1])
size = (max_w,max_h)
image1 = image1.resize(size)
image2 = image2.resize(size)

#Merging
file_merged = concat_image_auto(image1,image2,size)

#Check filesize and compress if needed

How can I do that? (I can't save the image in memory)

Ninja
  • 3
  • 2
  • @StrangeSorcerer I think the OP refers to the bytesize of the image, not its (width,height) – GPhilo Jul 01 '21 at 09:34
  • Oh right, sorry. In that case, does the answer by ady on this similar question help? https://stackoverflow.com/questions/11904083/how-to-get-image-size-bytes-using-pil – StrangeSorcerer Jul 01 '21 at 09:37
  • I don't need W and H values, but The filesize in Kb or Mb. – Ninja Jul 01 '21 at 09:38

1 Answers1

3

You can save the image in memory, and then see how big the result is:

with io.BytesIO() as output:
    file_merged.save(output, format="PNG")
    size = output.getbuffer().nbytes

Because you use with the data is discarded afterwards

tituszban
  • 4,797
  • 2
  • 19
  • 30
  • I can't save the image in memory – Ninja Jul 01 '21 at 09:39
  • 1
    And why is that? Please be more specific. Do you get an error? Is the image very large and you don't have enough memory? – tituszban Jul 01 '21 at 09:42
  • Because I'm working on AWS Lambda, I can't store locally until I don't finish the job. When the compressed image is ready I have to store it in S3 bucket. – Ninja Jul 01 '21 at 09:43
  • Yes. This code doesn't store it locally, on a disk/filesystem, which you can't use on Lambda. It stores it in memory, which you can use all you want on a Lambda – tituszban Jul 01 '21 at 09:45
  • Ok, but I get this error: module 'io' has no attribute 'getbuffer' – Ninja Jul 01 '21 at 09:48
  • Now that is an actual issue. It stemmed from a typo in my answer. It is fixed now. Please try again – tituszban Jul 01 '21 at 09:50
  • U ciunn d quera ciucc d sort. Thank you very much! :) – Ninja Jul 01 '21 at 10:01