1

I am using the DALLE API to generate images, and taking that file and uploading it to spotify as a playlist cover. However I receive a 413 error when I run the following line:

sp.playlist_upload_cover_image(playlist_id=playlist_id, image_b64=image)

where 'image' is my DALLE generated image in base-64 format.

image = openai.Image.create(
  prompt=string_to_upload,
  n=1,
  size="256x256",
  response_format="b64_json"
)

image = image['data'][0]['b64_json']

Here is the error message:

requests.exceptions.HTTPError: 413 Client Error: Request Entity Too Large for url: https://api.spotify.com/v1/playlists/68jf42L1vcopcrBPZkmmre/images

I believe that the b64 file that I receive from the DALLE API is slighty larger than the max file size for the spotipy upload (256 KB). I can tell because if I download the image as a png and convert it to b64 online, it says the file is about 262 KB. Is there any way I can make the b64 file from DALLE slightly smaller?

3

2 Answers 2

1

Off course there is a way to make the b64 from DALLE smaller by compressing it. You can try the PIL library with Python. CHeck the following example where we can use the PIL library for resizing and compressing it before converting it to base64.

import io
from PIL import Image

# convert base64 image to bytes
image_bytes = io.BytesIO(base64.b64decode(image))

# open image with PIL
pil_image = Image.open(image_bytes)

# this is to resize and compress image
max_size = 256
quality = 80  # adjust quality to get smaller file size
pil_image = pil_image.resize((max_size, max_size))
pil_image.save(image_bytes, format='JPEG', quality=quality)

# convert compressed image to base64
compressed_image = base64.b64encode(image_bytes.getvalue()).decode('utf-8')
Sign up to request clarification or add additional context in comments.

Comments

0

I'm not sure why N Miaolis's code was not working for my case. I guess saving the new lower quality image in the same BytesIO object did not work for me

I created this method where the image_format is PNG or JPG and the picture.image is a bytes object of the base64 encoded image e.g. b'iVBORw0KGgoAAAA....'

The max_size parameter is used to set the dimensions squared and as for the quality I do not recommend going below 70 as far too few details can be noticed.

def compress_image(picture, quality=70, max_size=256):
    image_bytes = io.BytesIO(base64.b64decode(picture.image))
    image_format = parse_image_format(picture.image_format)

    pil_image = Image.open(image_bytes)
    pil_image = pil_image.resize((max_size, max_size))

    output_buffer = io.BytesIO()
    pil_image.save(output_buffer, format=image_format, quality=quality)
    compressed_image = output_buffer.getvalue()
    picture.image = base64.b64encode(compressed_image)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.