All Products
Search
Document Center

Platform For AI:Use AI Portrait SDK for Java

Last Updated:Dec 16, 2025

The SDK for Java allows you to call the algorithm service interfaces of AI Portrait for model training and portrait creation. You can use the SDK to configure a custom LoRA model and create a portrait based on a template image. This topic describes the preparations you must make before you can use the SDK for Java to call the related interfaces. This topic also provides examples on how to call the interfaces.

Prerequisites

  • A Java environment is prepared.

  • One template image and 5 to 20 training images are prepared for model training and portrait creation. The following image formats are supported: .jpg, .jpeg, and .png.

    • For a solo portrait, the template image needs to contain only one face.

    • For a solo portrait, the faces in multiple training images must belong to the same person.

    • For a multi-person portrait, the template image must contain multiple faces, and the number of faces must be the same as the number of the model_id parameters used for model training.

    • Make sure that the size of each image is greater than 512 × 512 pixels.

Preparations

  1. Add the dependency for the ai-service SDK in the pom.xml file of the Maven project.

    <dependency>
     <groupId>com.aliyun.openservices.aiservice</groupId>
     <artifactId>aiservice-sdk</artifactId>
     <version>1.0.1</version>
    </dependency>
  1. Initialize the client.

    import com.aliyun.openservices.aiservice.ApiClient;
    
    public class AIGCImageTest {
     public static ApiClient apiClient;
     static {
     String host = 'HOST';
     String appId = 'YOUR-APPID';
     String token = 'YOUR-TOKEN';
     apiClient = new ApiClient(host, appId, token);
     }
    }

    Configure the parameters based on your business requirements. The following table describes the parameters.

    Parameter

    Description

    <HOST>

    The server address. Example: http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com.

    <YOUR-APPID>

    The application ID. After you activate AI Portrait, you can view the application ID on the AI Portrait page.

    <YOUR-TOKEN>

    The token. After you activate AI Portrait, you can view the token on the AI Portrait page.

For more information, see GitHub open source code.

Sample code

AI Portrait is a resource-intensive service, involving model training and portrait creation. In most cases, model training requires several minutes, whereas portrait creation requires only dozens of seconds.

image

Check request (api.aigcImagesCheck)

  • The following code block shows a sample request:

    import com.aliyun.openservices.aiservice.api;
    import com.aliyun.openservices.aiservice.ApiClient;
    import com.aliyun.openservices.aiservice.ApiException;
    import com.aliyun.openservices.aiservice.model.AIGCCreatRequest;
    import com.aliyun.openservices.aiservice.model.AIGCImageCheckResponse;
    import com.aliyun.openservices.aiservice.model.AIGCImageCreateResponse;
    import com.aliyun.openservices.aiservice.model.Response;
    
    import java.util.Arrays;
    import java.util.List;
    
    public class AIGCImageTest {
        public static ApiClient apiClient;
        private  AigcImagesApi api ;
        static {
            String host  = 'HOST';
            String appId = 'YOUR-APPID';
            String token = 'YOUR-TOKEN';
            apiClient = new ApiClient(host, appId, token);
            api = new AigcImagesApi(apiClient);
        }
    
        public void aigcImagesCheckTest() throws Exception {
            // Enter the URL of a training image. 
            List<String> images =Arrays.asList(
                "https://xxx/0.jpg",
                "https://xxx/1.jpg",
                "https://xxx/2.jpg"
            );
    
            AIGCImageCheckResponse response = api.aigcImagesCheck(images);
            // The ID of the request.
            String request_id = response.getRequestId();
            // The request status.
            String code = response.getCode();
            // The details of the request status.
            String message = response.getMessage();
            // The response to the request.
            AIGCImageCheckData data = response.getData();
    
            // The code of the check result. 
            List<AIGCImageCheckResult> CheckResultsList =  response.getCheckResults();
            for(int i=0; i < CheckResultsList.size(); i++ ){
                AIGCImageCheckResult result = CheckResultsList.get(i);
                Integer ResultCode = result.getCode();
                System.out.println(ResultCode);
            }
        }
    
    }

    The following table describes the parameters in the preceding code.

    Parameter

    Description

    images

    The image URLs, which are specified by List<String>.

    <HOST>

    The server address. Example: http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com.

    <YOUR-APPID>

    The application ID. After you activate AI Portrait, you can view the application ID on the AI Portrait page.

    <YOUR-TOKEN>

    The token. After you activate AI Portrait, you can view the token on the AI Portrait page.

  • The following code block shows a sample response:

    Response type: AIGCImageCheckResponse

    {
    	requestId: 3c0eeb6b-1faf-4dc4-8f9a-9a02486051c6
    	code: OK
    	message: success
    	data:
    		AIGCImageCheckData{
    			requestId = '3c0eeb6b-1faf-4dc4-8f9a-9a02486051c6', 
     			images = ["https://xxx/0.jpg",
     								"https://xxx/1.jpg",
     								"https://xxx/2.jpg"], 
    		costTime=0.5460958480834961, 
     		checkResults=[
     			AIGCImageCheckResult{
     				code=1, 
     				frontal=false, 
     				url='https://xxx/0.jpg',
     				message='success'}, 
     			AIGCImageCheckResult{
            code=1, 
              frontal=true, 
              url='https://xxx/1.jpg',
              message='success'}, 
          AIGCImageCheckResult{
            code=4,
            frontal=false, 
            url='https://xxx/2.jpg',
            message='Image detect error.'}
      		]
    		}
    }

    The following table describes the response parameters.

    Parameter

    Description

    Type

    requestId

    The ID of the request.

    String

    code

    The status code of the request. Valid values: OK and error. OK indicates that the request is completed, and error indicates that the request is not completed.

    String

    message

    The details of the request status. If the request is successful, success is returned. In other scenarios, a different message is returned.

    String

    data

    The details of the returned data.

    AIGCImageCheckData

    The following table describes the data field whose type is AIGCImageCheckData.

    Parameter

    Description

    Type

    checkResults

    The detection result of each input image. Each image corresponds to a dictionary. A dictionary contains the following keys: url, message, and frontal. The url key indicates the URL of the image, the message key indicates the detection details of the image, and the frontal key indicates whether the image is front-facing.

    List<AIGCImageCheckResult>

    costTime

    The computing time required for the server to call the API.

    float

    images

    The URLs of the images that are checked.

    List<String>

    requestId

    The ID of the request. The ID is the same as the value of the upper-level requestId parameter.

    String

    The following table describes the messages in check_results.

    Message

    Status code

    Description

    success

    1

    The image meets the requirements.

    Image decode error.

    2

    The image cannot be downloaded or decoded.

    Number of face is not 1.

    3

    The number of faces is not 1.

    Image detect error.

    4

    An error occurred while detecting the face.

    Image encoding error.

    5

    An error occurred while encoding a face as a feature vector. In most cases, the issue occurs because no face is detected.

    This photo is not the same person in photos.

    6

    If only this error is reported, the faces in multiple images do not belong to the same person.

Model training initiation (api.aigcImagesTrain)

  • The following code block shows a sample request:

    package com.aliyun.aisdk;
    
    import com.aliyun.openservices.aiservice.api.AigcImagesApi;
    import com.aliyun.openservices.aiservice.ApiClient;
    import com.aliyun.openservices.aiservice.ApiException;
    import com.aliyun.openservices.aiservice.model.*;
    
    import java.util.Arrays;
    import java.util.List;
    
    import java.io.IOException;
    
    public class AIGCImageTrain {
      public String host = 'HOST';
      public String appId = 'YOUR-APPID';
      public String token = 'YOUR-TOKEN';
    
      public ApiClient apiClient = new ApiClient(host, appId, token);
      public AigcImagesApi api = new AigcImagesApi(apiClient);
    
      public void aigcImagesTrainTest() throws Exception {
        List<String> images =Arrays.asList(
          "https://xxx/0.jpg",
          "https://xxx/1.jpg",
          "https://xxx/2.jpg"
        );
        AIGCImageTrainResponse response = api.aigcImagesTrain(images);
        int jobId = response.getData().getJobId();
        String modelId = response.getData().getModelId();
        String message = response.getMessage();
        InlineResponse200Data Data = response.getData();
    
        System.out.println(response);
        System.out.println(response.getMessage());
    
        System.out.println("jobId:" + jobId);
        System.out.println("modelId:" + modelId);
        System.out.println("Data:" + Data);
      }
    }

    The following table describes the parameters in the preceding code.

    Parameter

    Description

    images

    The image URLs, which are specified by List<String>.

    <HOST>

    The server address. Example: http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com.

    <YOUR-APPID>

    The application ID. After you activate AI Portrait, you can view the application ID on the AI Portrait page.

    <YOUR-TOKEN>

    The token. After you activate AI Portrait, you can view the token on the AI Portrait page.

  • The following code block shows a sample response:

    Response type: AIGCImageTrainResponse

    {
      requestId: 2bd438df-2358-4852-b6b0-bf7d39b6dde7
      code: OK
      message: success
      data: class InlineResponse200Data {
              	jobId: xxxx
                modelId: xxxx-xxxxxxxx-xxxxxx
              }
    }

  • The following table describes the response parameters.

    The following table describes the data field.

    Parameter

    Description

    Type

    jobId

    The job ID.

    int

    modelId

    The ID of the model that is trained, which is a string of 36 characters.

    String

    • You need to use the job_id parameter to query training results.

    • You need to use the model_id parameter to make a request for the portrait creation service.

Training result query (jobApi.getAsyncJob)

  • The following code block shows a sample request:

    import com.aliyun.openservices.aiservice.api.AiServiceJobApi;
    import com.aliyun.openservices.aiservice.api.AigcImagesApi;
    import com.aliyun.openservices.aiservice.ApiClient;
    import com.aliyun.openservices.aiservice.ApiException;
    import com.aliyun.openservices.aiservice.model.*;
    
    
    import java.util.Arrays;
    import java.util.List;
    
    import java.io.IOException;
    
    public class AIGCJobCheck {
    	public void aigcJobStateGet() throws Exception {
        Integer jobId = new Integer(xxxx); // The ID of the asynchronous job.
    
        AiServiceJobApi jobApi = new AiServiceJobApi(apiClient);
    
        AsyncJobResponse jobResponse = jobApi.getAsyncJob(jobId);
        String request_id = jobResponse.getRequestId();
        String job_code = jobResponse.getCode();
        String job_message = jobResponse.getMessage();
        Map<String, AsyncJobData> job_data = jobResponse.getData();
    
        String Result_string = (String) job_data.get("job").getResult();
        JsonObject jsonObject = new JsonParser().parse(Result_string).getAsJsonObject();
        JsonArray result_states = jsonObject.get("states").getAsJsonArray();
    
        for (int result_idx=0; result_idx < result_states.size(); result_idx++){
          JsonObject result_one = result_states.get(result_idx).getAsJsonObject();
          String result_url = result_one.get("url").getAsString();
        }
      }
    }
  • The following table describes the parameters.

    Parameter

    Type

    Description

    jobId

    Integer

    The ID of the training job.

  • The following code blocks show sample responses:

    • The following code block shows a sample response when the model training is incomplete:

      {
          requestId: 9a76c77d-c241-4691-8c93-fc6953fb668c
          code: OK
          message: success
          data: {
                job=AsyncJobData{
                  id=12746, 
                  appId='xxxxxxxxxx', 
                  state=1, 
                  message='model requesting', 
                  result="", 
                  requestId='111a6503-c2f7-4141-b17b-f8567e6a0a5f'
                  }
          }
      }
    • The following code block shows a sample response when the model training is complete:

      {
            requestId: 0fc513d1-5a9e-48e1-9b6f-2eca7c0b62e9
            code: OK
            message: success
              data: {
                job=AsyncJobData{
                  id=12744, 
                  appId='xxxxxxxxxxx', 
                  state=2, 
                  message='success', 
                  result={
                    "cost_time":232.83351230621338,
                    "model_id":"xxxxxxxxxxxx",
                    "states":[{"code":1,
                               "frontal":true,
                               "message":"success",
                               "url":"https://xxxx/train/1.jpg"}]
                  }, 
                  requestId='83146ee3-68aa-40f7-b523-06f029e1db15'
                }
              }
      }
  • The following table describes the response parameters.

    Parameter

    Description

    Type

    requestId

    The ID of the request.

    String

    code

    The status code of the request. Valid values: OK and error. OK indicates that the request is completed, and error indicates that the request is not completed.

    String

    message

    The details of the request status. If the request is successful, success is returned. In other scenarios, a different message is returned.

    String

    data

    The details of the returned data.

    Map<String, AsyncJobData>

    The following table describes the result fields returned by data.get("job").

    Parameter

    Description

    Type

    id

    The ID of the job, which is the same as the value of the job_id parameter.

    int

    appId

    The application ID of the user.

    String

    state

    The status code of the job.

    • 0: The job is initializing.

    • 1: The job is running.

    • 2: The job is complete.

    • 3: The job failed.

    int

    message

    The execution information of the job.

    String

    Result

    The results returned by the model.

    String

    The following table describes the results returned by the model. The data type of the Result parameter is string.

    Parameter

    Description

    cost_time

    The time consumed for this training.

    states

    The check result of each image.

    The detection result of each input image. Each image corresponds to a dictionary. A dictionary contains the following keys: url, message, and frontal. The url key indicates the URL of the image, the message key indicates the detection details of the image, and the frontal key indicates whether the image is front-facing.

    model_id

    The ID of the LoRA model, which is the same as the value of the model_id parameter obtained by the training request. You can enter the name during portrait creation.

  • Descriptions of related error codes

    • The following table describes the error codes of the request.

      HTTP status code

      Error code

      Message

      Description

      400

      PARAMETER_ERROR

      not found appid

      The application ID is invalid.

      401

      PARAMETER_ERROR

      sign error

      The token is invalid.

      404

      PARAMETER_ERROR

      model not found

      The requested model service is not deployed.

    • The following table describes the error codes for result queries.

      HTTP status code

      Error code

      Message

      Description

      462

      error

      Invalid input data

      An error occurred while parsing the input data.

      462

      error

      Image not provided

      Training images are not provided.

      462

      error

      Make dir in oss Error.

      Failed to create a folder in Object Storage Service (OSS). Check whether an OSS bucket is mounted.

      462

      error

      Image process error.

      An error occurred while preprocessing an image.

      469

      error

      Training - Not get best template image

      The training unexpectedly exits, resulting in the failure to generate reference images.

      469

      error

      Training - Not get lora weight

      The training unexpectedly exits, resulting in the failure to generate the LoRA weight.

Portrait creation

  • The following code blocks show sample requests:

    • Interface for solo portrait creation (api.aigcImagesCreate)

      • Predictive SD15

        import com.aliyun.openservices.aiservice.api.AiServiceJobApi;
        import com.aliyun.openservices.aiservice.api.AigcImagesApi;
        import com.aliyun.openservices.aiservice.ApiClient;
        import com.aliyun.openservices.aiservice.ApiException;
        import com.aliyun.openservices.aiservice.model.*;
        
        
        import java.io.FileOutputStream;
        import java.io.OutputStream;
        import java.util.Arrays;
        import java.util.List;
        
        import java.io.IOException;
        
        import sun.misc.BASE64Decoder;
        import sun.misc.BASE64Encoder;
        
        public class AIGCImageService {
          public String host = 'HOST';
          public String appId = 'YOUR-APPID';
          public String token = 'YOUR-TOKEN';
        
          public ApiClient apiClient = new ApiClient(host, appId, token);
          public AigcImagesApi api = new AigcImagesApi(apiClient);
        
          public void aigcImageCreateGet() throws Exception {
            String modelId = "xxx-xxxx";
            String templateImage = "https://xxxx.jpg";
            String model_name = "";
            Map<String, Object> configure = new TreeMap<String, Object>();
        
            AIGCImageCreateResponse createResponse = api.aigcImagesCreate(modelId, templateImage, model_name, configure);
        
            // The ID of the request.
            String request_id = createResponse.getRequestId();
            // The request status.
            String code = createResponse.getCode();
            // The details of the request status.
            String message = createResponse.getMessage();
            // The response to the request.
            AIGCImageCreateData data = createResponse.getData();
        
            // The Base64-encoded image.
            String imgStr = createResponse.getData().getImage();
        
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] imgBtyes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < imgBtyes.length; ++i) {
              // Modify abnormal data.
              if (imgBtyes[i] < 0) {
                imgBtyes[i] += 256;
              }
            }
        
            String imgFilePath = "test_single.jpg";
            OutputStream out = new FileOutputStream(imgFilePath);
        
            out.write(imgBtyes);
            out.flush();
            out.close();
          }
        }

        The following table describes the parameters.

        Parameter

        Type

        Description

        modelId

        String

        The name of the LoRA model. You must enter the value of the model_id parameter obtained from training.

        If the ipa_control_only parameter is set to True, set this parameter to "".

        templateImage

        String

        The URL path of the template.

        model_name

        String

        The name of the model. By default, an empty string is entered.

        configure

        Map<String, Object>

        Configuration items returned. Default value: None.

        <HOST>

        String

        The server address. Example: http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com.

        <YOUR-APPID>

        String

        The application ID. After you activate AI Portrait, you can view the application ID on the AI Portrait page.

        <YOUR-TOKEN>

        String

        The token. After you activate AI Portrait, you can view the token on the AI Portrait page.

        Parameters in the configure parameter

        Parameter

        Description

        Type

        Required

        Default value

        Value range

        lora_weights

        The LoRA weight.

        float

        No

        0.90

        0.5 to 1.0

        first_denoising_strength

        The intensity of the first image reconstruction.

        float

        No

        0.45

        0.0 to 1.0

        second_denoising_strength

        The intensity of the second image reconstruction.

        float

        No

        0.30

        0.0 to 1.0

        more_like_me

        The degree to which the image resembles the desired person.

        float

        No

        0.50

        0.0 to 1.0

        crop_face_preprocess

        Specifies whether to crop and then reconstruct the image. We recommend that you set this parameter to True for large images.

        bool

        No

        True

        True, False

        apply_face_fusion_before

        Specifies whether to perform the first portrait merging.

        bool

        No

        True

        True, False

        apply_face_fusion_after

        Specifies whether to perform the second portrait merging.

        bool

        No

        True

        True, False

        color_shift_middle

        Specifies whether to perform the first color correction.

        bool

        No

        True

        True, False

        color_shift_last

        Specifies whether to perform the second color correction.

        bool

        No

        True

        True, False

        background_restore

        Specifies whether to rebuild the background.

        bool

        No

        False

        True, False

        skin_retouching_bool

        Specifies whether to perform skin smoothing.

        If you set the parameter to True, the skin is smoothed and brightened. In most cases, this makes the image more attractive, but may excessively lighten the skin. If you set the parameter to False, the skin texture can be improved.

        bool

        No

        False

        True, False

        photo_enhancement_bool

        Specifies whether to enhance the portrait.

        If you set the parameter to True, the system restores the portrait or increases the image resolution to improve image quality.

        bool

        No

        True

        True, False

        photo_enhancement_method

        The method used to enhance the portrait.

        photo_fix is used for image restoration, which may cause some distortion but will fix unreasonable areas, and may lead to a loss of skin texture.

        super_resolution is used only for enhancing the resolution of an image, preserving more of its original appearance.

        String

        No

        photo_fix

        photo_fix, super_resolution

        makeup_transfer

        Specifies whether to perform makeup transfer.

        If you set the parameter to True, makeup transfer is performed to prevent the image from appearing too plain. However, this may result in the image not closely resembling the user.

        bool

        No

        False

        True, False

        makeup_transfer_ratio

        The intensity of makeup transfer.

        In theory, the larger the value, the higher the proportion of makeup transfer and the more closely the resulting makeup resembles the template. This may result in the image not closely resembling the user.

        float

        No

        0.5

        0.0 to 1.0

        face_shape_match

        Specifies whether to perform face shape compatibility.

        If you set the parameter to True, the control strength decreases, and the face shape and skin texture more closely resemble the user.

        bool

        No

        False

        True, False

        ipa_control

        Specifies whether to perform ip-adapter-based control.

        If you set the parameter to True, the similarity of the portrait improves, but the portrait becomes more influenced by the reference image.

        bool

        No

        False

        True, False

        ipa_control_only

        If you set the parameter to True, prediction can be performed without training.

        If you set the parameter to True, you must configure the ipa_image_path parameter.

        bool

        No

        False

        True, False

        ipa_image_path

        The URL of the reference image.

        This parameter is required only if you set the ipa_control_only to True.

        String

        No

        None

        Publicly accessible URL

        ipa_weight

        The weight of ip-adapter.

        In theory, the larger the value, the more closely the generated image resembles the user. However, if the value is excessively large, image distortion may occur.

        float

        No

        0.5

        0.0 to 1.0

        style_name

        The style of the generated image.

        Valid values: Realistic and Anime.

        str

        No

        Realistic

        Realistic,

        Anime

        lcm_accelerate

        Specifies whether to perform Latent Code Manipulation (LCM) acceleration.

        bool

        No

        False

        True, False

        sharp_ratio

        The sharpness level. An appropriate value can enhance clarity.

        An excessively large value may cause image distortion.

        float

        No

        0.15

        0.0 to 1.0

        t2i_prompt

        The prompt. If you want to use the text-based image generation feature, configure this parameter.

        If you configure the t2i_prompt parameter, you do not need to specify the URL path of the template.

        String

        No

        None

        None

      • Predictive SDXL

        import com.aliyun.openservices.aiservice.api.AiServiceJobApi;
        import com.aliyun.openservices.aiservice.api.AigcImagesApi;
        import com.aliyun.openservices.aiservice.ApiClient;
        import com.aliyun.openservices.aiservice.ApiException;
        import com.aliyun.openservices.aiservice.model.*;
        
        
        import java.io.FileOutputStream;
        import java.io.OutputStream;
        import java.util.Arrays;
        import java.util.List;
        
        import java.io.IOException;
        
        import sun.misc.BASE64Decoder;
        import sun.misc.BASE64Encoder;
        
        public class AIGCImageService {
          public String host = 'HOST';
          public String appId = 'YOUR-APPID';
          public String token = 'YOUR-TOKEN';
        
          public ApiClient apiClient = new ApiClient(host, appId, token);
          public AigcImagesApi api = new AigcImagesApi(apiClient);
        
          public void aigcImageCreateGet() throws Exception {
            String modelId = "xxx-xxxx";
            String templateImage = "https://xxxx.jpg";
            String model_name = "create_xl";
            Map<String, Object> configure = new TreeMap<String, Object>();
        
            AIGCImageCreateResponse createResponse = api.aigcImagesCreate(modelId, templateImage, model_name, configure);
        
            // The ID of the request.
            String request_id = createResponse.getRequestId();
            // The request status.
            String code = createResponse.getCode();
            // The details of the request status.
            String message = createResponse.getMessage();
            // The response to the request.
            AIGCImageCreateData data = createResponse.getData();
        
            // The Base64-encoded image.
            String imgStr = createResponse.getData().getImage();
        
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] imgBtyes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < imgBtyes.length; ++i) {
              // Modify abnormal data.
              if (imgBtyes[i] < 0) {
                imgBtyes[i] += 256;
              }
            }
        
            String imgFilePath = "test_single.jpg";
            OutputStream out = new FileOutputStream(imgFilePath);
        
            out.write(imgBtyes);
            out.flush();
            out.close();
          }
        }

        The following table describes the parameters.

        Parameter

        Type

        Description

        modelId

        string

        The name of the LoRA model. You must enter the value of the model_id parameter obtained from training. If the ipa_control_only parameter is set to True, set this parameter to "".

        templateImage

        string

        The URL path of the template.

        If you use scene_lora or prompt to generate an image, set the parameter to t2i_generate.

        model_name

        string

        The name of the model. If SDXL is used, set the parameter to create_xl.

        configure

        Map<String, Object>

        Configuration items returned. Default value: None.

        Parameters in the configure parameter

        Parameter

        Description

        Type

        Required

        Default value

        Value range

        lora_weights

        The LoRA weight.

        In theory, the larger the value, the more closely the generated image resembles the user. However, if the value is excessively large, image distortion may occur.

        float

        No

        0.90

        0.5 to 1.0

        first_diffusion_steps

        The number of steps for the first diffusion.

        We recommend that you do not change the parameter value. A significant decrease can cause the image to become distorted.

        int

        No

        50

        20-50

        first_denoising_strength

        The intensity of the first image reconstruction.

        The reconstruction intensity of the face. The greater the intensity of the face reconstruction, the more reconstruction occurs. In theory, the larger the value, the more closely the generated image resembles the user. However, if the value is excessively large, image distortion may occur.

        float

        No

        0.45

        0.0 to 1.0

        second_diffusion_steps

        The number of steps for the second diffusion.

        We recommend that you do not change the parameter value. A significant decrease can cause the image to become distorted.

        int

        No

        30

        20-50

        second_denoising_strength

        The intensity of the second image reconstruction.

        The reconstruction intensity of the facial edges. If the value is excessively large, image distortion may occur.

        float

        No

        0.30

        0.0 to 1.0

        more_like_me

        The degree to which the image resembles the desired person.

        The proportion of portrait merging. The larger the value, the more closely the generated image resembles the user. However, if the value is excessively large, the image may look unrealistic.

        float

        No

        0.60

        0.0 to 1.0

        crop_face_preprocess

        Specifies whether to crop and then reconstruct the image. We recommend that you set this parameter to True for large images.

        We recommend that you do not change the parameter value.

        bool

        No

        True

        True, False

        apply_face_fusion_before

        Specifies whether to perform the first portrait merging.

        If you set the parameter to True, portrait merging is performed. If you set the parameter to False, the similarity is reduced.

        bool

        No

        True

        True, False

        apply_face_fusion_after

        Specifies whether to perform the second portrait merging.

        If you set the parameter to True, portrait merging is performed. If you set the parameter to False, the similarity is reduced.

        bool

        No

        True

        True, False

        color_shift_middle

        Specifies whether to perform the first color correction.

        If you set the parameter to True, color correction is performed to make the skin color of the output image more closely resemble the template. If you set the parameter to False, color correction is not performed and color distortion may occur.

        bool

        No

        True

        True, False

        color_shift_last

        Specifies whether to perform the second color correction.

        If you set the parameter to True, color correction is performed to make the skin color of the output image more closely resemble the template. If you set the parameter to False, color correction is not performed and color distortion may occur.

        bool

        No

        True

        True, False

        background_restore

        Specifies whether to rebuild the background.

        If you set the parameter to True, the background is reconstructed. In theory, this makes the image more natural but changes the background and increases the time consumption.

        bool

        No

        False

        True, False

        skin_retouching_bool

        Specifies whether to perform skin smoothing.

        If you set the parameter to True, the skin is smoothed and brightened. In most cases, this makes the image more attractive, but may excessively lighten the skin. If you set the parameter to False, the skin texture can be improved.

        bool

        No

        False

        True, False

        photo_enhancement_bool

        Specifies whether to enhance the portrait.

        If you set the parameter to True, the system restores the portrait or increases the image resolution to improve image quality.

        bool

        No

        True

        True, False

        photo_enhancement_method

        The method used to enhance the portrait.

        photo_fix is used for image restoration, which may cause some distortion but will fix unreasonable areas, and may lead to a loss of skin texture.

        super_resolution is used only for enhancing the resolution of an image, preserving more of its original appearance.

        String

        No

        photo_fix

        photo_fix, super_resolution

        makeup_transfer

        Specifies whether to perform makeup transfer.

        If you set the parameter to True, makeup transfer is performed to prevent the image from appearing too plain. However, this may result in the image not closely resembling the user.

        bool

        No

        False

        True, False

        makeup_transfer_ratio

        The intensity of makeup transfer.

        In theory, the larger the value, the higher the proportion of makeup transfer and the more closely the resulting makeup resembles the template. This may result in the image not closely resembling the user.

        float

        No

        0.5

        0.0 to 1.0

        ipa_control

        Specifies whether to perform ip-adapter-based control.

        If you set the parameter to True, the similarity of the portrait improves, but the portrait becomes more influenced by the reference image.

        bool

        No

        False

        True, False

        ipa_control_only

        If you set the parameter to True, prediction can be performed without training.

        If you set the parameter to True, you must configure the ipa_image_path parameter.

        bool

        No

        False

        True, False

        ipa_image_path

        The URL of the reference image.

        This parameter is required only if you set the ipa_control_only to True.

        String

        No

        None

        Publicly accessible URL

        ipa_weight

        The weight of ip-adapter.

        In theory, the larger the value, the more the generated image resembles the user. Yet, an excessively large value may cause image distortion.

        float

        No

        0.5

        0.0 to 1.0

        lcm_accelerate

        Specifies whether to perform LCM acceleration.

        bool

        No

        False

        True, False

        sharp_ratio

        The sharpness level. An appropriate value can enhance clarity.

        An excessively large value may cause image distortion.

        float

        No

        0.15

        0.0 to 1.0

        scene_id

        If you want to use scene_lora, you must configure the scene_id parameter.

        The scene ID is obtained from the training result. The model ID that is returned when you train the SDXL_LoRA model is the scene ID.

        String

        No

        None

        None

        t2i_prompt

        The prompt. If you want to use the text-based image generation feature, configure this parameter.

        If you configure the t2i_prompt parameter, you do not need to specify the URL path of the template.

        String

        No

        None

        None

    • Interface for multi-person portrait creation (api.aigcImagesCreateByMultiModelIds)

      import com.aliyun.openservices.aiservice.api.AiServiceJobApi;
      import com.aliyun.openservices.aiservice.api.AigcImagesApi;
      import com.aliyun.openservices.aiservice.ApiClient;
      import com.aliyun.openservices.aiservice.ApiException;
      import com.aliyun.openservices.aiservice.model.*;
      
      
      import java.io.FileOutputStream;
      import java.io.OutputStream;
      import java.util.Arrays;
      import java.util.List;
      
      import java.io.IOException;
      
      import sun.misc.BASE64Decoder;
      import sun.misc.BASE64Encoder;
      
      public class AIGCImageService {
        public String host = 'HOST';
        public String appId = 'YOUR-APPID';
        public String token = 'YOUR-TOKEN';
      
        public ApiClient apiClient = new ApiClient(host, appId, token);
        public AigcImagesApi api = new AigcImagesApi(apiClient);
      
        public void aigcImageCreateMulti() throws Exception {
          String[] modelIds = new String[]{"model-id1","model-id2"};
          String templateImage = "https://xxxx.jpg";
          String model_name = "";
          Map<String, Object> configure = new TreeMap<String, Object>();
      
          AIGCImageCreateResponse createResponse = api.aigcImagesCreateByMultiModelIds(model_id, template_image, model_name, config);
      
          // The ID of the request.
          String request_id = createResponse.getRequestId();
          // The request status.
          String code = createResponse.getCode();
          // The details of the request status.
          String message = createResponse.getMessage();
          // The response to the request.
          AIGCImageCreateData data = createResponse.getData();
      
          // The Base64-encoded image.
          String imgStr = createResponse.getData().getImage();
      
          BASE64Decoder decoder = new BASE64Decoder();
          byte[] imgBtyes = decoder.decodeBuffer(imgStr);
          for (int i = 0; i < imgBtyes.length; ++i) {
            // Modify abnormal data.
            if (imgBtyes[i] < 0) {
              imgBtyes[i] += 256;
            }
          }
      
          String imgFilePath = "test_multi.jpg";
          OutputStream out = new FileOutputStream(imgFilePath);
      
          out.write(imgBtyes);
          out.flush();
          out.close();
        }
      }

      Parameter

      Type

      Description

      modelId

      String

      The ID of the model returned.

      templateImage

      String

      The URL path of the template.

      model_name

      String

      The name of the model. By default, an empty string is entered.

      configure

      Map<String, Object>

      Configuration items returned. Default value: None.

      <HOST>

      String

      The server address. Example: http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com.

      <YOUR-APPID>

      String

      The application ID. After you activate AI Portrait, you can view the application ID on the AI Portrait page.

      <YOUR-TOKEN>

      String

      The token. After you activate AI Portrait, you can view the token on the AI Portrait page.

  • The following code block shows a sample response:

    {
     requestId: 5eb7741b-540b-4a5c-9c98-fdd1d714e51f
     code: OK
     message: success
     data: com.aliyun.openservices.aiservice.model.AIGCImageCreateData@358c99f5
    }

    The following table describes the data field whose type is AIGCImageCreateData.

    Parameter

    Description

    Type

    costTime

    The time spent for creating the portrait.

    Float

    image

    The Base64-encoded image.

    String

  • Descriptions of the error codes returned during portrait creation

    • Request errors

      HTTP status code

      Error code

      Message

      Description

      400

      PARAMETER_ERROR

      not found appid

      The application ID is invalid.

      401

      PARAMETER_ERROR

      sign error

      The token is invalid.

      404

      PARAMETER_ERROR

      model not found

      The requested model service is not deployed.

    • Result query errors

      HTTP status code

      Error code

      Message

      Description

      462

      error

      Invalid input data. Please check the input dict.

      An error occurred while parsing the input data.

      462

      error

      Image not provided. Please check the template_image.

      The template image that is used for portrait creation is not provided.

      462

      error

      Prompts get error. Please check the model_id.

      The format of values of the model_id parameter is invalid.

      462

      error

      Face id image decord error. Pleace check the user's lora is trained or not.

      An error occurred while decoding the image. Check whether the model is trained.

      462

      error

      Roop image decord error. Pleace check the user's lora is trained or not.

      The Roop image does not exist. Check whether the model is trained.

      462

      error

      Template image decode error. Please Give a new template.

      An error occurred while decoding the template image. Provide a new template image.

      462

      error

      There is not face in template. Please Give a new template.

      No face can be detected in the template image. Provide a new template image.

      462

      error

      Template image process error. Please Give a new template.

      An error occurred while preprocessing the template image. Provide a new template image.

      469

      error

      First Face Fusion Error, Can't get face in template image.

      An error occurred during the first portrait merging.

      469

      error

      First Stable Diffusion Process error. Check the webui status.

      An error occurred during the first Stable Diffusion.

      469

      error

      Second Face Fusion Error, Can't get face in template image.

      An error occurred during the second portrait merging.

      469

      error

      Second Stable Diffusion Process error. Check the webui status.

      An error occurred during the second Stable Diffusion.

      469

      error

      Please confirm if the number of faces in the template corresponds to the user ID.

      Check whether the number of user IDs provided matches the number of faces.

      469

      error

      Third Stable Diffusion Process error. Check the webui status.

      An error occurred while preprocessing the background. Change the template.

Sample code of an end-to-end portrait creation process

The following code block shows a sample end-to-end portrait creation process. After the code is run, an AI portrait is created in the current directory.

  • Regular link (Stable Diffusion1.5)

    package com.aliyun.aisdk;
    
    import com.aliyun.openservices.aiservice.api.AiServiceJobApi;
    import com.aliyun.openservices.aiservice.api.AigcImagesApi;
    import com.aliyun.openservices.aiservice.ApiClient;
    import com.aliyun.openservices.aiservice.ApiException;
    import com.aliyun.openservices.aiservice.model.*;
    
    
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    import java.util.Arrays;
    import java.util.List;
    
    import java.io.IOException;
    
    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;
    
    public class AIGCImageRunner {
    
      public String host = 'HOST';
      public String appId = 'YOUR-APPID';
      public String token = 'YOUR-TOKEN';
    
      public ApiClient apiClient = new ApiClient(host, appId, token);
      public AigcImagesApi api = new AigcImagesApi(apiClient);
    
      public byte[] base64ToBytes(String imgStr) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] imgBtyes = decoder.decodeBuffer(imgStr);
        for (int i = 0; i < imgBtyes.length; ++i) {
          // Modify abnormal data.
          if (imgBtyes[i] < 0) {
            imgBtyes[i] += 256;
          }
        }
    
        return imgBtyes;
      }
    
      public void aigcImagesCheck(List<String> images) throws Exception{
        AIGCImageCheckResponse response = api.aigcImagesCheck(images);
      }
    
      public Object[] aigcImagesTrainRun(List<String> images) throws Exception {
    
        AIGCImageTrainResponse response = api.aigcImagesTrain(images);
        int jobId = response.getData().getJobId();
    
        Object[] trainOut = new Object[2];
    
        System.out.println(response);
        System.out.println(response.getMessage());
    
        System.out.println("jobId:" + jobId);
        System.out.println("modelId:" + response.getData().getModelId());
        System.out.println(response.getData());
    
        trainOut[0]=jobId;
        trainOut[1] = response.getData().getModelId();
        return trainOut;
      }
    
      public Integer aigcJobStateGet(AiServiceJobApi jobApi, int jobId_int) throws Exception {
        Integer jobId = new Integer(jobId_int); // The ID of the asynchronous task.
    
        AsyncJobResponse jobResponse = jobApi.getAsyncJob(jobId);
    
        System.out.println(jobResponse.getData().get("job").getResult());
    
        return jobResponse.getData().get("job").getState();
      }
    
      public void CreateSingle(String modelId, String templateImage) throws Exception {
    
        AIGCImageCreateResponse createResponse = api.aigcImagesCreate(modelId, templateImage);
    
        // The Base64-encoded image.
        String imgStr = createResponse.getData().getImage();
        System.out.println(createResponse.getData());
    
        byte[] imgBtyes = base64ToBytes(imgStr);
    
        String imgFilePath = "test_single.jpg";
        OutputStream out = new FileOutputStream(imgFilePath);
    
        out.write(imgBtyes);
        out.flush();
        out.close();
      }
      
      public void CreateMulti(String[] model_ids, String template_image)throws ApiException, IOException {
            
        		String imgFilePath = "test_multi.jpg";
        		AIGCImageCreateResponse createResponse = api.aigcImagesCreateByMultiModelIds(model_ids, template_image, model_name, config);
    
            // The ID of the request.
            String request_id = createResponse.getRequestId();
            // The request status.
            String code = createResponse.getCode();
            // The details of the request status.
            String message = createResponse.getMessage();
            // The response to the request.
            AIGCImageCreateData data = createResponse.getData();
    
            if (!code.equals("OK")){
                System.out.printf("aigc_images_create failed, model_id is %s, request_id is %s\n",model_ids,request_id);
            }else {
                String imgStr = createResponse.getData().getImage();
                byte[] image = base64ToBytes(imgStr);
    
              	
                OutputStream out = new FileOutputStream(output_image);
    
                out.write(image);
                out.flush();
                out.close();
    
            }
        }
    
    
      public void aigcEndtoEndCreate() throws Exception {
        List<String> images =Arrays.asList(
          "https://xxx/0.jpg",
          "https://xxx/1.jpg",
          "https://xxx/2.jpg"
        );
        String templateImage = "https://xxx.jpg";
        String multiTemplateImage = "https://xxx.jpg";
    
        Object[] o = aigcImagesTrainRun(images);
        int jobId = (int)o[0];
        String modelId = (String)o[1];
        
        AiServiceJobApi jobApi = new AiServiceJobApi(apiClient);
    
        while(true){
          Integer jobState = aigcJobStateGet(jobApi, jobId);
    
          if (jobState == AsyncJobState.JOB_STATE_WAIT) { // job running
            System.out.println("job running");
          } else if (jobState == AsyncJobState.JOB_STATE_SUCCESS) {
            System.out.println("job success");
            break;
          } else {
            System.out.println("job fail");
            throw new Exception("job fail");
          }
    
          try {
            Thread.sleep(30000);
          } catch (InterruptedException e) {
            throw new RuntimeException(e);
          }
        }
        
        
    
        CreateSingle(modelId,templateImage);
    
    
        String[] modelIds = new String[]{modelId,modelId};
        CreateMulti(model_ids, template_image)
    
      }
    
    }

    The following table describes the parameters.

    Parameter

    Description

    <HOST>

    The server address. Example: http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com.

    <YOUR-APPID>

    The application ID. After you activate AI Portrait, you can view the application ID on the AI Portrait page.

    <YOUR-TOKEN>

    The token. After you activate AI Portrait, you can view the token on the AI Portrait page.

    images

    The URL of the image that is used to train the model. If multiple URLs are specified, separate multiple URLs with commas (,).

    templateImage

    The URL of the template image, which contains a single face. The template image is used for solo portrait creation.

    multiTemplateImage

    The URL of the template image. The template image contains multiple faces and the number of faces is the same as the number of the model_id parameters provided. The template image is used for multi-person portrait creation.

  • Regular link (Stable Diffusion XL)

    Before you can use the SDXL model for model training and portrait creation, you must contact the Platform for AI (PAI) team to activate the service. Then, use the service by specifying a model name.

    package com.aliyun.aiservice.demo;
    
    import com.aliyun.openservices.aiservice.ApiClient;
    import com.aliyun.openservices.aiservice.ApiException;
    import com.aliyun.openservices.aiservice.api.AiServiceJobApi;
    import com.aliyun.openservices.aiservice.api.AigcImagesApi;
    import com.aliyun.openservices.aiservice.model.*;
    import com.google.gson.JsonArray;
    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    import org.junit.Test;
    import sun.misc.BASE64Decoder;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.*;
    
    
    public class PhotoEndtoEndTest {
    
        public String host = 'HOST';
      	public String appId = 'YOUR-APPID';
      	public String token = 'YOUR-TOKEN';
      
        public ApiClient apiClient = new ApiClient(host, appId, token);
        public AigcImagesApi api = new AigcImagesApi(apiClient);
        public AiServiceJobApi jobApi = new AiServiceJobApi(apiClient);
    
        public byte[] base64ToBytes(String imgStr) throws IOException {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] imgBtyes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < imgBtyes.length; ++i) {
                // Modify abnormal data.
                if (imgBtyes[i] < 0) {
                    imgBtyes[i] += 256;
                }
            }
    
            return imgBtyes;
        }
    
        public boolean Check(List<String> images) throws ApiException {
            AIGCImageCheckResponse response = this.api.aigcImagesCheck(images);
            // The ID of the request.
            String request_id = response.getRequestId();
            // The request status.
            String code = response.getCode();
            // The details of the request status.
            String message = response.getMessage();
            // The response to the request.
            AIGCImageCheckData data = response.getData();
    
            // Print the returned result.
            boolean is_ok = false;
            if (!code.equals("OK")){
                System.out.printf("aigc_images_check failed,request id is %\n", request_id);
            }else{
                is_ok = true;
                System.out.printf("check images done, input %d images, return %d images, %d filtered by lvwang\n",
                        images.size(),(data.getCheckResults().size()),(images.size()-data.getCheckResults().size()));
                for (int check_result_idx=0; check_result_idx < data.getCheckResults().size();check_result_idx++ ){
                    AIGCImageCheckResult checkResult = data.getCheckResults().get(check_result_idx);
                    Integer checkResultCode = checkResult.getCode();
                    if (checkResultCode.equals(1)){
                        System.out.printf("check %s success\n", checkResult.getUrl());
                    }else {
                        is_ok = false;
                        System.out.printf("check %s failed, message is %s , request_id is %s\n",
                                checkResult.getUrl(),checkResult.getMessage(),request_id);
                    }
                }
            }
            return is_ok;
        }
    
        public Object[] Train(List<String> images, String model_name, Map<String, Object> config) throws ApiException {
            Integer job_id = -1;
            String model_id = "";
    
            AIGCImageTrainResponse response = this.api.aigcImagesTrain(images,model_name,config);
            // The ID of the request.
            String request_id = response.getRequestId();
            // The request status.
            String code = response.getCode();
            // The details of the request status.
            String message = response.getMessage();
            // The response to the request.
            InlineResponse200Data Data = response.getData();
    
            // Print the returned result.
            if (!code.equals("OK")){
                System.out.printf("aigc_images_train failed, request id is %s\n", request_id);
    
            }else{
                job_id = response.getData().getJobId();
                model_id = response.getData().getModelId();
    
                System.out.printf("train job_id is %d, model id %s\n",job_id.intValue(),model_id);
    
            }
            Integer state = -1;
            while(true){
                AsyncJobResponse jobResponse = this.jobApi.getAsyncJob(job_id);
                String job_code = jobResponse.getCode();
                String job_message = jobResponse.getMessage();
                Map<String, AsyncJobData> job_data = jobResponse.getData();
    
                if (!job_code.equals("OK")){
                    System.out.printf("get_async_job failed, request id is %s, message is %s\n",
                            request_id, job_message);
                    job_id = new Integer(-1);
                    model_id = "";
    
                }else{
                    state = job_data.get("job").getState();
                    if (state.equals(2)){
                        System.out.printf("model %s trained successfully\n",model_id);
                        break;
                    }else if(!state.equals(3)){
                        System.out.printf("training model %s\n",model_id);
    
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
    
                    }else{
                        System.out.printf("model %s trained failed, message: %s\n",model_id,job_message);
                        break;
                    }
                }
    
            }
    
            if (!state.equals(2)){
                model_id = "";
            }
    
            Object[] out = new Object[2];
            out[0] = job_id;
            out[1] = model_id;
    
            return out;
    
        }
    
        public String[] QueryValidImageUrlsByJob(Integer job_id) throws ApiException {
            String[] image_urls = null;
    
            AsyncJobResponse jobResponse = this.jobApi.getAsyncJob(job_id);
            String request_id = jobResponse.getRequestId();
            String job_code = jobResponse.getCode();
            String job_message = jobResponse.getMessage();
            Map<String, AsyncJobData> job_data = jobResponse.getData();
    
            if (!job_code.equals("OK")) {
                System.out.printf("get_async_job failed, request id is %s, message is %s\n",
                        request_id, job_message);
            }else {
                Integer state = job_data.get("job").getState();
                if (state == 2){
                    System.out.printf("Job %s trained successfully\n", job_id);
                    String Result_string = (String) job_data.get("job").getResult();
                    JsonObject jsonObject = new JsonParser().parse(Result_string).getAsJsonObject();
                    JsonArray result_states = jsonObject.get("states").getAsJsonArray();
                    image_urls = new String[result_states.size()];
                    for (int result_idx=0; result_idx < result_states.size(); result_idx++){
                        JsonObject result_one = result_states.get(result_idx).getAsJsonObject();
                        String result_url = result_one.get("url").getAsString();
                        image_urls[result_idx] = result_url;
                    }
    
                }else{
                    System.out.printf("job %s not ready\n",job_id);
                }
            }
    
            return image_urls;
        }
    
        public boolean Create(String model_id, String template_image, String output_image, String model_name, Map<String, Object> config) throws IOException {
            System.out.println("Create");
            AIGCImageCreateResponse createResponse = null;
            try{
                createResponse = api.aigcImagesCreate(model_id, template_image, model_name, config);
            }catch (ApiException e){
                System.out.println();
                System.out.println(e.getResponseBody());
            }
            System.out.println(createResponse);
            // The ID of the request.
            String request_id = createResponse.getRequestId();
            // The request status.
            String code = createResponse.getCode();
            // The details of the request status.
            String message = createResponse.getMessage();
            // The response to the request.
            AIGCImageCreateData data = createResponse.getData();
    
            if (!code.equals("OK")){
                System.out.printf("aigc_images_create failed, model_id is %s, request_id is %s\n",model_id,request_id);
            }else {
                String imgStr = createResponse.getData().getImage();
                byte[] image = base64ToBytes(imgStr);
    
                OutputStream out = new FileOutputStream(output_image);
    
                out.write(image);
                out.flush();
                out.close();
    
            }
            return true;
        }
    
        public boolean CreateMulti(String[] model_ids, String template_image, String output_image, String model_name, Map<String, Object> config) throws ApiException, IOException {
            AIGCImageCreateResponse createResponse = api.aigcImagesCreateByMultiModelIds(model_ids, template_image, model_name, config);
    
            // The ID of the request.
            String request_id = createResponse.getRequestId();
            // The request status.
            String code = createResponse.getCode();
            // The details of the request status.
            String message = createResponse.getMessage();
            // The response to the request.
            AIGCImageCreateData data = createResponse.getData();
    
            if (!code.equals("OK")){
                System.out.printf("aigc_images_create failed, model_id is %s, request_id is %s\n",model_ids,request_id);
            }else {
                String imgStr = createResponse.getData().getImage();
                byte[] image = base64ToBytes(imgStr);
    
                OutputStream out = new FileOutputStream(output_image);
    
                out.write(image);
                out.flush();
                out.close();
    
            }
            return true;
        }
    
        @Test
        public void aigcEndtoEndCreate() throws Exception {
            List<String> images = Arrays.asList(
                    "https://xxx/0.jpg",
                    "https://xxx/1.jpg",
                    "https://xxx/2.jpg"
            );
    
            
    
            String template_image = "https://xxx.jpg";
            String multi_template_image = "https://xxx.jpg";
          
            String model_name = "train_xl";
            Map<String, Object> config = new HashMap<String, Object>();
    
            Object[] train_out = Train(images, model_name, config);
    
            Integer job_id= (Integer) train_out[0];
            String model_id =  (String) train_out[1];
    
    
    
            String[] model_ids = {model_id,model_id};
            model_name = "create_xl"; //""
            Map<String, Object> configure = new TreeMap<String, Object>();
    
            Create(model_id, template_image,"single_out.jpg", model_name,configure);
    
            CreateMulti(model_ids, multi_template_image,"multi_out.jpg", model_name,configure);
    
    
        }
    
    }

  • AI portrait creation based on a single reference image (without the need for model training)

    package com.aliyun.aiservice.demo;
    
    import com.aliyun.openservices.aiservice.ApiClient;
    import com.aliyun.openservices.aiservice.ApiException;
    import com.aliyun.openservices.aiservice.api.AiServiceJobApi;
    import com.aliyun.openservices.aiservice.api.AigcImagesApi;
    import com.aliyun.openservices.aiservice.model.*;
    import com.google.gson.JsonArray;
    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    import org.junit.Test;
    import sun.misc.BASE64Decoder;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.*;
    
    public class PhotoReferCreateTest {
        public String host = 'HOST';
      	public String appId = 'YOUR-APPID';
      	public String token = 'YOUR-TOKEN';
      
        public ApiClient apiClient = new ApiClient(host, appId, token);
        public AigcImagesApi api = new AigcImagesApi(apiClient);
        public AiServiceJobApi jobApi = new AiServiceJobApi(apiClient);
    
        public byte[] base64ToBytes(String imgStr) throws IOException {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] imgBtyes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < imgBtyes.length; ++i) {
                // Modify abnormal data.
                if (imgBtyes[i] < 0) {
                    imgBtyes[i] += 256;
                }
            }
    
            return imgBtyes;
        }
    
        public boolean Check(List<String> images) throws ApiException {
            AIGCImageCheckResponse response = this.api.aigcImagesCheck(images);
            // The ID of the request.
            String request_id = response.getRequestId();
            // The request status.
            String code = response.getCode();
            // The details of the request status.
            String message = response.getMessage();
            // The response to the request.
            AIGCImageCheckData data = response.getData();
    
            // Print the returned result.
            boolean is_ok = false;
            if (!code.equals("OK")){
                System.out.printf("aigc_images_check failed,request id is %\n", request_id);
            }else{
                is_ok = true;
                System.out.printf("check images done, input %d images, return %d images, %d filtered by lvwang\n",
                        images.size(),(data.getCheckResults().size()),(images.size()-data.getCheckResults().size()));
                for (int check_result_idx=0; check_result_idx < data.getCheckResults().size();check_result_idx++ ){
                    AIGCImageCheckResult checkResult = data.getCheckResults().get(check_result_idx);
                    Integer checkResultCode = checkResult.getCode();
                    if (checkResultCode.equals(1)){
                        System.out.printf("check %s success\n", checkResult.getUrl());
                    }else {
                        is_ok = false;
                        System.out.printf("check %s failed, message is %s , request_id is %s\n",
                                checkResult.getUrl(),checkResult.getMessage(),request_id);
                    }
                }
            }
            return is_ok;
        }
    
    
    
        public boolean Create(String template_image, String output_image, String ref_image) throws IOException {
            System.out.println("Create");
            AIGCImageCreateResponse createResponse = null;
    
            Map<String, Object> config = new TreeMap<String, Object>();
    
            config.put("ipa_control_only",true);
            config.put("ipa_weight",0.6);
            config.put("ipa_image_path",ref_image);
            try{
                createResponse = api.aigcImagesCreate("", template_image, "", config);
            }catch (ApiException e){
                System.out.println();
                System.out.println(e.getResponseBody());
            }
            System.out.println(createResponse);
            // The ID of the request.
            String request_id = createResponse.getRequestId();
            // The request status.
            String code = createResponse.getCode();
            // The details of the request status.
            String message = createResponse.getMessage();
            // The response to the request.
            AIGCImageCreateData data = createResponse.getData();
    
            if (!code.equals("OK")){
                System.out.printf("aigc_images_create failed, model_id is %s, request_id is %s\n",model_id,request_id);
            }else {
                String imgStr = createResponse.getData().getImage();
                byte[] image = base64ToBytes(imgStr);
    
                OutputStream out = new FileOutputStream(output_image);
    
                out.write(image);
                out.flush();
                out.close();
    
            }
            return true;
        }
    
        @Test
        public void aigcEndtoEndCreate() throws Exception {
    
            String template_image = "https://demo.jpg";
            String ref_image = "https://reference.jpg";
          
            Create(template_image,"ref_out.jpg", ref_image);
    
    
        }
    }
    

  • Template creation link based on a prompt (without the need for the template image)

    package com.aliyun.aiservice.demo;
    
    import com.aliyun.openservices.aiservice.ApiClient;
    import com.aliyun.openservices.aiservice.ApiException;
    import com.aliyun.openservices.aiservice.api.AiServiceJobApi;
    import com.aliyun.openservices.aiservice.api.AigcImagesApi;
    import com.aliyun.openservices.aiservice.model.*;
    import com.google.gson.JsonArray;
    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    import org.junit.Ignore;
    import org.junit.Test;
    import sun.misc.BASE64Decoder;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.*;
    
    public class PhotoPtomptCreateTest {
    
        public String host = 'HOST';
      	public String appId = 'YOUR-APPID';
      	public String token = 'YOUR-TOKEN';
      
        public ApiClient apiClient = new ApiClient(host, appId, token);
        public AigcImagesApi api = new AigcImagesApi(apiClient);
        public AiServiceJobApi jobApi = new AiServiceJobApi(apiClient);
    
        public byte[] base64ToBytes(String imgStr) throws IOException {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] imgBtyes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < imgBtyes.length; ++i) {
                // Modify abnormal data.
                if (imgBtyes[i] < 0) {
                    imgBtyes[i] += 256;
                }
            }
    
            return imgBtyes;
        }
    
        public boolean Check(List<String> images) throws ApiException {
            AIGCImageCheckResponse response = this.api.aigcImagesCheck(images);
            // The ID of the request.
            String request_id = response.getRequestId();
            // The request status.
            String code = response.getCode();
            // The details of the request status.
            String message = response.getMessage();
            // The response to the request.
            AIGCImageCheckData data = response.getData();
    
            // Print the returned result.
            boolean is_ok = false;
            if (!code.equals("OK")){
                System.out.printf("aigc_images_check failed,request id is %\n", request_id);
            }else{
                is_ok = true;
                System.out.printf("check images done, input %d images, return %d images, %d filtered by lvwang\n",
                        images.size(),(data.getCheckResults().size()),(images.size()-data.getCheckResults().size()));
                for (int check_result_idx=0; check_result_idx < data.getCheckResults().size();check_result_idx++ ){
                    AIGCImageCheckResult checkResult = data.getCheckResults().get(check_result_idx);
                    Integer checkResultCode = checkResult.getCode();
                    if (checkResultCode.equals(1)){
                        System.out.printf("check %s success\n", checkResult.getUrl());
                    }else {
                        is_ok = false;
                        System.out.printf("check %s failed, message is %s , request_id is %s\n",
                                checkResult.getUrl(),checkResult.getMessage(),request_id);
                    }
                }
            }
            return is_ok;
        }
    
        public Object[] Train(List<String> images, String model_name, Map<String, Object> config) throws ApiException {
            Integer job_id = -1;
            String model_id = "";
    
            AIGCImageTrainResponse response = this.api.aigcImagesTrain(images,model_name,config);
            // The ID of the request.
            String request_id = response.getRequestId();
            // The request status.
            String code = response.getCode();
            // The details of the request status.
            String message = response.getMessage();
            // The response to the request.
            InlineResponse200Data Data = response.getData();
    
            // Print the returned result.
            if (!code.equals("OK")){
                System.out.printf("aigc_images_train failed, request id is %s\n", request_id);
    
            }else{
                job_id = response.getData().getJobId();
                model_id = response.getData().getModelId();
    
                System.out.printf("train job_id is %d, model id %s\n",job_id.intValue(),model_id);
    
            }
            Integer state = -1;
            while(true){
                AsyncJobResponse jobResponse = this.jobApi.getAsyncJob(job_id);
                String job_code = jobResponse.getCode();
                String job_message = jobResponse.getMessage();
                Map<String, AsyncJobData> job_data = jobResponse.getData();
    
                if (!job_code.equals("OK")){
                    System.out.printf("get_async_job failed, request id is %s, message is %s\n",
                            request_id, job_message);
                    job_id = new Integer(-1);
                    model_id = "";
    
                }else{
                    state = job_data.get("job").getState();
                    if (state.equals(2)){
                        System.out.printf("model %s trained successfully\n",model_id);
                        break;
                    }else if(!state.equals(3)){
                        System.out.printf("training model %s\n",model_id);
    
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
    
                    }else{
                        System.out.printf("model %s trained failed, message: %s\n",model_id,job_message);
                        break;
                    }
                }
    
            }
    
            if (!state.equals(2)){
                model_id = "";
            }
    
            Object[] out = new Object[2];
            out[0] = job_id;
            out[1] = model_id;
    
            return out;
    
        }
    
        public String[] QueryValidImageUrlsByJob(Integer job_id) throws ApiException {
            String[] image_urls = null;
    
            AsyncJobResponse jobResponse = this.jobApi.getAsyncJob(job_id);
            String request_id = jobResponse.getRequestId();
            String job_code = jobResponse.getCode();
            String job_message = jobResponse.getMessage();
            Map<String, AsyncJobData> job_data = jobResponse.getData();
    
            if (!job_code.equals("OK")) {
                System.out.printf("get_async_job failed, request id is %s, message is %s\n",
                        request_id, job_message);
            }else {
                Integer state = job_data.get("job").getState();
                if (state == 2){
                    System.out.printf("Job %s trained successfully\n", job_id);
                    String Result_string = (String) job_data.get("job").getResult();
                    JsonObject jsonObject = new JsonParser().parse(Result_string).getAsJsonObject();
                    JsonArray result_states = jsonObject.get("states").getAsJsonArray();
                    image_urls = new String[result_states.size()];
                    for (int result_idx=0; result_idx < result_states.size(); result_idx++){
                        JsonObject result_one = result_states.get(result_idx).getAsJsonObject();
                        String result_url = result_one.get("url").getAsString();
                        image_urls[result_idx] = result_url;
                    }
    
                }else{
                    System.out.printf("job %s not ready\n",job_id);
                }
            }
    
            return image_urls;
        }
    
        public boolean Create(String model_id, String t2i_prompt, String template_image) throws IOException {
            System.out.println("Create");
            AIGCImageCreateResponse createResponse = null;
            HashMap<String,Object> config = new HashMap<String, Object>();
            config.put("t2i_prompt", t2i_prompt);
            try{
                createResponse = api.aigcImagesCreate(model_id, template_image, "", config);
            }catch (ApiException e){
                System.out.println();
                System.out.println(e.getResponseBody());
            }
            System.out.println(createResponse);
            // The ID of the request.
            String request_id = createResponse.getRequestId();
            // The request status.
            String code = createResponse.getCode();
            // The details of the request status.
            String message = createResponse.getMessage();
            // The response to the request.
            AIGCImageCreateData data = createResponse.getData();
    
            if (!code.equals("OK")){
                System.out.printf("aigc_images_create failed, model_id is %s, request_id is %s\n",model_id,request_id);
            }else {
                String imgStr = createResponse.getData().getImage();
                byte[] image = base64ToBytes(imgStr);
    
                OutputStream out = new FileOutputStream("prompt_out.jpg");
    
                out.write(image);
                out.flush();
                out.close();
    
            }
            return true;
        }
    
    
    
        @Test
        public void aigcEndtoEndCreate() throws Exception {
    
    
            List<String> images =Arrays.asList(
          			"https://xxx/0.jpg",
          			"https://xxx/1.jpg",
          			"https://xxx/2.jpg"
        		);
    
            String template_image = "https://demo.jpg";
    
            String model_name = "";
            Map<String, Object> config = new HashMap<String, Object>();
    
            Object[] train_out = Train(images, model_name, config);
    
            Integer job_id= (Integer) train_out[0];
            String model_id =  (String) train_out[1];
    
            String t2i_prompt = "(portrait:1.5), 1girl, bokeh, bouquet, brown_hair, cloud, flower, hairband, hydrangea, lips, long_hair, outdoors, sunlight, white_flower, white_rose, green sweater, sweater, (cloth:1.0), (best quality), (realistic, photo-realistic:1.3), film photography, minor acne, (portrait:1.1), (indirect lighting), extremely detailed CG unity 8k wallpaper, huge filesize, best quality, realistic, photo-realistic, ultra high res, raw photo, put on makeup";
            Create(model_id, t2i_prompt, template_image);
    
        }
    
    }
    

  • AI portrait creation based on the template image that is generated based on a prompt and a single reference image (without the need to provide a template image or perform model training)

    package com.aliyun.aiservice.demo;
    
    import com.aliyun.openservices.aiservice.ApiClient;
    import com.aliyun.openservices.aiservice.ApiException;
    import com.aliyun.openservices.aiservice.api.AiServiceJobApi;
    import com.aliyun.openservices.aiservice.api.AigcImagesApi;
    import com.aliyun.openservices.aiservice.model.*;
    import com.google.gson.JsonArray;
    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    import org.junit.Ignore;
    import org.junit.Test;
    import sun.misc.BASE64Decoder;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.*;
    
    public class PhotoPtomptCreateTest {
    
        public String host = 'HOST';
      	public String appId = 'YOUR-APPID';
      	public String token = 'YOUR-TOKEN';
      
        public ApiClient apiClient = new ApiClient(host, appId, token);
        public AigcImagesApi api = new AigcImagesApi(apiClient);
        public AiServiceJobApi jobApi = new AiServiceJobApi(apiClient);
    
        public byte[] base64ToBytes(String imgStr) throws IOException {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] imgBtyes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < imgBtyes.length; ++i) {
                // Modify abnormal data.
                if (imgBtyes[i] < 0) {
                    imgBtyes[i] += 256;
                }
            }
    
            return imgBtyes;
        }
    
        public boolean Check(List<String> images) throws ApiException {
            AIGCImageCheckResponse response = this.api.aigcImagesCheck(images);
            // The ID of the request.
            String request_id = response.getRequestId();
            // The request status.
            String code = response.getCode();
            // The details of the request status.
            String message = response.getMessage();
            // The response to the request.
            AIGCImageCheckData data = response.getData();
    
            // Print the returned result.
            boolean is_ok = false;
            if (!code.equals("OK")){
                System.out.printf("aigc_images_check failed,request id is %\n", request_id);
            }else{
                is_ok = true;
                System.out.printf("check images done, input %d images, return %d images, %d filtered by lvwang\n",
                        images.size(),(data.getCheckResults().size()),(images.size()-data.getCheckResults().size()));
                for (int check_result_idx=0; check_result_idx < data.getCheckResults().size();check_result_idx++ ){
                    AIGCImageCheckResult checkResult = data.getCheckResults().get(check_result_idx);
                    Integer checkResultCode = checkResult.getCode();
                    if (checkResultCode.equals(1)){
                        System.out.printf("check %s success\n", checkResult.getUrl());
                    }else {
                        is_ok = false;
                        System.out.printf("check %s failed, message is %s , request_id is %s\n",
                                checkResult.getUrl(),checkResult.getMessage(),request_id);
                    }
                }
            }
            return is_ok;
        }
    
        public Object[] Train(List<String> images, String model_name, Map<String, Object> config) throws ApiException {
            Integer job_id = -1;
            String model_id = "";
    
            AIGCImageTrainResponse response = this.api.aigcImagesTrain(images,model_name,config);
            // The ID of the request.
            String request_id = response.getRequestId();
            // The request status.
            String code = response.getCode();
            // The details of the request status.
            String message = response.getMessage();
            // The response to the request.
            InlineResponse200Data Data = response.getData();
    
            // Print the returned result.
            if (!code.equals("OK")){
                System.out.printf("aigc_images_train failed, request id is %s\n", request_id);
    
            }else{
                job_id = response.getData().getJobId();
                model_id = response.getData().getModelId();
    
                System.out.printf("train job_id is %d, model id %s\n",job_id.intValue(),model_id);
    
            }
            Integer state = -1;
            while(true){
                AsyncJobResponse jobResponse = this.jobApi.getAsyncJob(job_id);
                String job_code = jobResponse.getCode();
                String job_message = jobResponse.getMessage();
                Map<String, AsyncJobData> job_data = jobResponse.getData();
    
                if (!job_code.equals("OK")){
                    System.out.printf("get_async_job failed, request id is %s, message is %s\n",
                            request_id, job_message);
                    job_id = new Integer(-1);
                    model_id = "";
    
                }else{
                    state = job_data.get("job").getState();
                    if (state.equals(2)){
                        System.out.printf("model %s trained successfully\n",model_id);
                        break;
                    }else if(!state.equals(3)){
                        System.out.printf("training model %s\n",model_id);
    
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
    
                    }else{
                        System.out.printf("model %s trained failed, message: %s\n",model_id,job_message);
                        break;
                    }
                }
    
            }
    
            if (!state.equals(2)){
                model_id = "";
            }
    
            Object[] out = new Object[2];
            out[0] = job_id;
            out[1] = model_id;
    
            return out;
    
        }
    
        public String[] QueryValidImageUrlsByJob(Integer job_id) throws ApiException {
            String[] image_urls = null;
    
            AsyncJobResponse jobResponse = this.jobApi.getAsyncJob(job_id);
            String request_id = jobResponse.getRequestId();
            String job_code = jobResponse.getCode();
            String job_message = jobResponse.getMessage();
            Map<String, AsyncJobData> job_data = jobResponse.getData();
    
            if (!job_code.equals("OK")) {
                System.out.printf("get_async_job failed, request id is %s, message is %s\n",
                        request_id, job_message);
            }else {
                Integer state = job_data.get("job").getState();
                if (state == 2){
                    System.out.printf("Job %s trained successfully\n", job_id);
                    String Result_string = (String) job_data.get("job").getResult();
                    JsonObject jsonObject = new JsonParser().parse(Result_string).getAsJsonObject();
                    JsonArray result_states = jsonObject.get("states").getAsJsonArray();
                    image_urls = new String[result_states.size()];
                    for (int result_idx=0; result_idx < result_states.size(); result_idx++){
                        JsonObject result_one = result_states.get(result_idx).getAsJsonObject();
                        String result_url = result_one.get("url").getAsString();
                        image_urls[result_idx] = result_url;
                    }
    
                }else{
                    System.out.printf("job %s not ready\n",job_id);
                }
            }
    
            return image_urls;
        }
    
        public boolean Create(String t2i_prompt, String template_image, String ref_image) throws IOException {
            System.out.println("Create");
            AIGCImageCreateResponse createResponse = null;
            HashMap<String,Object> config = new HashMap<String, Object>();
    
            config.put("t2i_prompt", t2i_prompt);
            config.put("ipa_control_only", true);
            config.put("ipa_weight", 0.6);
            config.put("ipa_image_path", ref_image);
    
            try{
                createResponse = api.aigcImagesCreate("", template_image, "", config);
            }catch (ApiException e){
                System.out.println();
                System.out.println(e.getResponseBody());
            }
            System.out.println(createResponse);
            // The ID of the request.
            String request_id = createResponse.getRequestId();
            // The request status.
            String code = createResponse.getCode();
            // The details of the request status.
            String message = createResponse.getMessage();
            // The response to the request.
            AIGCImageCreateData data = createResponse.getData();
    
            if (!code.equals("OK")){
                System.out.printf("aigc_images_create failed, request_id is %s\n",request_id);
            }else {
                String imgStr = createResponse.getData().getImage();
                byte[] image = base64ToBytes(imgStr);
    
                OutputStream out = new FileOutputStream("ref_prompt_out.jpg");
    
                out.write(image);
                out.flush();
                out.close();
    
            }
            return true;
        }
    
    
    
        @Test
        public void aigcEndtoEndCreate() throws Exception {
    
            String template_image = "https://demo.jpg";
            String ref_image = "https://reference.jpg";
    
    
            String t2i_prompt = "(portrait:1.5), 1girl, bokeh, bouquet, brown_hair, cloud, flower, hairband, hydrangea, lips, long_hair, outdoors, sunlight, white_flower, white_rose, green sweater, sweater, (cloth:1.0), (best quality), (realistic, photo-realistic:1.3), film photography, minor acne, (portrait:1.1), (indirect lighting), extremely detailed CG unity 8k wallpaper, huge filesize, best quality, realistic, photo-realistic, ultra high res, raw photo, put on makeup";
            Create(t2i_prompt, template_image, ref_image);
    
        }
    
    }