taga
taga

Reputation: 3895

Converting Image to Bytearray with Python

I want to convert Image file to Bytearray. I extracted image from pdf file with minecart lib, but I cant find a way to convert it to bytearray. This is my code:

import minecart
from PIL import Image
import io

pdffile = open('sample6.pdf', 'rb')
doc = minecart.Document(pdffile)


for page in doc.iter_pages():
    print(page)
    img = page.images[0].as_pil()

    print(img) # <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=1641x2320 at 0x7FBDF02E6A00>

    print(type(img)) # <class 'PIL.JpegImagePlugin.JpegImageFile'>

I have tried to use bytearray(img) but It does not work. Do you have solution for this (solution that does not consume to much time)?

Upvotes: 0

Views: 4429

Answers (1)

รยקคгรђשค
รยקคгรђשค

Reputation: 1979

Create io.BytesIO buffer and write to it using PIL.Image.save. Set appropriate quality and other parameters as per requirement.

import io
from PIL import Image

def convert_pil_image_to_byte_array(img):
    img_byte_array = io.BytesIO()
    img.save(img_byte_array, format='JPEG', subsampling=0, quality=100)
    img_byte_array = img_byte_array.getvalue()
    return img_byte_array

References:

Why is the quality of JPEG images produced by PIL so poor?

Upvotes: 3

Related Questions