createImageEdit method

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

Creates an edited or extended image given an original image and a prompt.

Implementation

Future<List<GptImage>> createImageEdit({
  required String apiKey,
  required String organizationId,
  required ImageEditRequest 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/edits");
  }
  else {
    endpoint = Uri.http(
        baseUrl, "/v1/images/edits");
  }


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

  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"));


  if(maskBytes!= null) {
    requestPost.files.add(http.MultipartFile.fromBytes("mask", maskBytes, filename: "mask.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);
  }
}