createImageVariation method

Future<List<GptImage>> createImageVariation({
  1. required String apiKey,
  2. required String organizationId,
  3. required ImageVariationRequest request,
})

Creates a variation of a given image.

Implementation

Future<List<GptImage>> createImageVariation({
  required String apiKey,
  required String organizationId,
  required ImageVariationRequest request,
}) async {

  Map<String, String> headers = {
    "Authorization": "Bearer $apiKey",
    "OpenAI-Organization": organizationId,
    'Content-Type': 'application/json',
    "Access-Control-Allow-Origin": "*", // Required for CORS support to work
  };


  Uri endpoint;
  if(secure) {
    endpoint = Uri.https(
        baseUrl, "/v1/images/variations");
  }
  else {
    endpoint = Uri.http(
        baseUrl, "/v1/images/variations");
  }


  Uint8List imageBytes = request.imageBytes;
  // Remove the image fields, we need to send them as files.
  var jsonRequest = request.toJson()..remove("imageBytes");

  var requestPost = http.MultipartRequest('POST', endpoint)
    ..headers.addAll(headers)
    ..fields.addAll(
        jsonRequest.map((key, value) => MapEntry(key, value.toString())))
    ..files.add(http.MultipartFile.fromBytes("image", imageBytes, filename: "image.png"));

  var response = await requestPost.send();

  if (response.statusCode == 200 || response.statusCode == 201) {
    GptImageResponse responseDto =  GptImageResponse.fromJson(jsonDecode(const Utf8Decoder().convert(await response.stream.toBytes())));
    return responseDto.data;
  }
  else {
    var error = ServerError.fromJson(jsonDecode(const Utf8Decoder().convert(await response.stream.toBytes())));
    throw ImageException(statusCode: response.statusCode, message: error.message);
  }
}