feng
feng

Reputation: 11

How to download the pictures produced by OpenAI through the returned URL?

I have tried a lot of methods, but any OpenAI produced picture URL will time out? Even if using HttpsURLConnection, setting connection timeout and read timeout doesn't work? METHOD1: FileUtils.copyURLToFile(source, destination, connectionTimeout, readTimeout);

METHOD2: code:

1

ERROR: enter image description here

ERROR: Connect to oaidalleapiprodscus.blob.core.windows.net:443 [oaidalleapiprodscus.blob.core.windows.net/20.150.70.100] failed: Connection timed out (Connection timed out)

Upvotes: 1

Views: 1042

Answers (1)

Sang Tran
Sang Tran

Reputation: 9

The response URL of the API maybe is not support blob. You can try by using response_format = "b64_json". Example code:

function base64ToFile(b64Data, filename, contentType) {
  const sliceSize = 512;
  const byteCharacters = atob(b64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }

  const blob = new Blob(byteArrays, { type: contentType });
  const file = new File([blob], filename, { type: contentType });
  return file;
}

export async function createImageByDescription(
  description,
  numberImgs = 2,
  size = "1024x1024",
  response_format = "b64_json"
) {
  try {
    const response = await axios.post(
      "https://api.openai.com/v1/images/generations",
      {
        prompt: description,
        n: numberImgs,
        size,
        response_format,
      },
      {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer {token}`,
        },
      }
    );

    const imageFiles = await Promise.all(
      response.data.data.map(async (item, index) => {
        const file = await base64ToFile(
          item.b64_json,
          `image${index}.png`,
          "image/png"
        );
        return file;
      })
    );

    return imageFiles;
  } catch (error) {
    console.log("Error createImageByDescription:", error);
    throw error;
  }
}

Upvotes: 0

Related Questions