generateImagePngFromImage method

Future<Uint8List> generateImagePngFromImage({
  1. required String apiKey,
  2. required String engineId,
  3. required ImageToImageRequestParams params,
  4. required Uint8List initImage,
  5. String? organization,
  6. String? clientId,
  7. String? clientVersion,
})

Modify an image based on a text prompt and returns the image PNG bytes.

Implementation

Future<Uint8List> generateImagePngFromImage({
  required String apiKey,
  required String engineId,
  required ImageToImageRequestParams params,
  required Uint8List initImage,
  String? organization,
  String? clientId,
  String? clientVersion,
}) async {
  Map<String, String> headers = {
    "Authorization": apiKey,
    "Accept": "image/png",
    'Content-Type': 'application/json',
    "Access-Control-Allow-Origin": "*", // Required for CORS support to work
  };

  if (organization != null) {
    headers.putIfAbsent("Organization", () => organization);
  }

  if (clientId != null) {
    headers.putIfAbsent("Stability-Client-ID", () => clientId);
  }

  if (clientVersion != null) {
    headers.putIfAbsent("Stability-Client-Version", () => clientVersion);
  }

  Uri endpoint;
  if (secure) {
    endpoint = Uri.https(baseUrl, "/v1/generation/$engineId/image-to-image");
  } else {
    endpoint = Uri.http(baseUrl, "/v1/generation/$engineId/image-to-image");
  }

  var request = http.MultipartRequest('POST', endpoint)
    ..headers.addAll(headers)
    ..fields.addAll(
        params.toJson().map((key, value) => MapEntry(key, value.toString())))
    ..fields.remove("text_prompts")
    ..files.add(http.MultipartFile.fromBytes("init_image", initImage));

  List<TextPrompt> prompts = params.textPrompts;
  int index = 0;
  for (var element in prompts) {
    request.fields['text_prompts[$index][text]'] = element.text;
    request.fields['text_prompts[$index][weight]'] =
        element.weight.toString();
    index++;
  }
  var response = await request.send();

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