DEV Community

Mingming Ma
Mingming Ma

Posted on

Base64 data of DALL·E 3 response

This week, I submitted a PR to ChatCraft that set DALL·E 3 generated image's format to Base64 data. Previously, we used a URL format, but it was only viable for an hour due to OpenAI's requirements.

doc

The response_format parameter

The format in which the generated images are returned. Must be one of url or b64_json. URLs are only valid for 60 minutes after the image has been generated.

Usage examples

Suppose you have an <img> tag in your component, and the src attribute is populated from a variable called imgSrc:



<img src={imgSrc} alt="..." />


Enter fullscreen mode Exit fullscreen mode

We can pass the src with the Base64 encoded image data rather than url



const imgSrc = "data:image/jpeg;base64,/9j/4AAQSkZJRgAB...";


Enter fullscreen mode Exit fullscreen mode

Now, let's take a look at the API. Here's an example of a url response:



const response = await openai.images.generate({
  model: "dall-e-3",
  prompt: "a white siamese cat",
  n: 1,
  size: "1024x1024",
});
const imgSrc = response.data[0].url;


Enter fullscreen mode Exit fullscreen mode

To obtain the response from OpenAI in Base64 format, we can update the code as follows:



const response = await openai.images.generate({
  model: "dall-e-3",
  prompt: "a white siamese cat",
  n: 1,
  size: "1024x1024",
  response_format: "b64_json",
});
const imgSrc = `data:image/jpeg;base64,${response.data[0].b64_json}`;


Enter fullscreen mode Exit fullscreen mode

I hope you find it helpful. See you in the next post!

Top comments (0)