2

I'm trying to make a rest API, and I came across this line of code-

_, img_encoded = cv2.imencode('.jpg', image)

What does this do? I unfortunately can't use OpenCV for m project, so is there any way I can achieve the same thing with PIL? Thanks, in advance!

CatCoder
  • 39
  • 5
  • Basically, cv2.imencode encodes an image to memory instead of writing the encoded image to an image file. – Micka Dec 08 '21 at 12:37
  • 1
    Use this answer and replace the png by jpg: https://stackoverflow.com/questions/646286/how-to-write-png-image-to-string-with-the-pil – Micka Dec 08 '21 at 12:38

1 Answers1

5

It writes a JPEG-compressed image into a memory buffer (RAM) instead of to disk.

With PIL:

#!/usr/bin/env python3

from PIL import Image
from io import BytesIO

# Create dummy red PIL Image
im = Image.new('RGB', (320,240), 'red')

# Create in-memory JPEG
buffer = BytesIO()
im.save(buffer, format="JPEG")

# Check first few bytes
JPEG = buffer.getvalue()
print(JPEG[:25])
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • Why is the JPEG being sliced? Hmm... So now let's say I want to post this image to my server, do I pass in Bufferm or JPEG? – CatCoder Dec 08 '21 at 15:40
  • As per the comment in the code, I only sliced and printed the first 25 bytes so you could see it looks like a regular JPEG without having to see thousands of pages of hex go past. You would pass `JPEG` to the server as it contains the entire image. – Mark Setchell Dec 08 '21 at 15:54
  • Its giving me this error :( ``` File "c:\Users\aadhi\Desktop\Code\Python\Scavenger Hunt\Server\test\client.py", line 21, in image.save(buffer, format="JPG") File "C:\Users\aadhi\AppData\Local\Programs\Python\Python39\lib\site-packages\PIL\Image.py", line 2229, in save save_handler = SAVE[format.upper()] KeyError: 'JPG'``` – CatCoder Dec 08 '21 at 16:10
  • Changing format to JPEG seems to work! – CatCoder Dec 08 '21 at 16:16
  • Oh, sorry! I have updated the code - thanks for letting me know. Good luck with your project! – Mark Setchell Dec 08 '21 at 16:33
  • Oh no, it's fine! Thanks, again! – CatCoder Dec 08 '21 at 16:34