What’s Image Kit?

In an era of ubiquitous social media and instantly sharable images, photo editing apps have become fixtures on so many user’s phones. HUAWEI Image Kit endows apps with powerful smart editing and scene-specific animation capabilities, offering up to 24 ready-made image rendering effects and design functions.

By integrating the Kit, your app will be equipped to provide the enthralling, and enriching photo editing that today’s users demand.

Function Demonstration and Sample Code

You can view the demo below to better understand what Image Kit may bring to you:                                              

If you are interested in how to implement filters with Image Kit, download the source code from Github at the following address and optimize the code based on your application scenarios.

Github address: https://github.com/HMS-Core/hms-image-vision

Getting Started

Step 1

Configure app information in AppGallery Connect.

To integrate HUAWEI Audio Kit, you must complete the following preparations:

  • Register as a Huawei developer.

  • Create an app in AppGallery Connect.

  • Create an Android Studio project.

  • Generate a signing certificate.

  • Generate a signing certificate fingerprint.

  • Configure the signing certificate fingerprint

  • Add the app package name and save the configuration file.

  • Configure the Maven repository address and AppGallery Connect gradle plug-in.

  • Configure the signature file in Android Studio.

For details, please refer to Preparations for Integrating HUAWEI HMS Core.

Step 2

Start Android Studio.

Step 3

Choose File > Open, go to the directory where the sample project is decompressed, and click OK.

Step 4

Configure the AppGallery Connect plug-in, Maven repository address, build dependencies, obfuscation scripts, and permissions. (These items have been configured in the sample code. If any of them does not meet your requirements, change it in your own project.)

1. Configure the Maven repository address and AppGallery Connect plug-in in the project’s build.gradle file.

1

2

3

4

5

6

allprojects {     

     repositories {

          maven { url 'https://developer.huawei.com/repo/' }

          

     }

  }

1

2

3

4

5

6

7

buildscript {

      repositories {

          maven {url 'https://developer.huawei.com/repo/'}

          

      }

      

 }

1

2

3

4

5

buildscript{     

        dependencies {         

                classpath 'com.huawei.agconnect:agcp:1.3.1.300'

        

}

 

2. Configure the dependency package in the app’s build.gradle file.

1

2

3

4

5

dependencies {     

        …             

                implementation 'com.huawei.hms:image-vision:1.0.2.301'     

        … 

}

1

2

3

4

5

6

7

8

9

android {

     ...

     defaultConfig {

         ...

         minSdkVersion 26

         ...

     }

     ...

 }

1

apply plugin: 'com.huawei.agconnect'

Note: Make sure that you configure apply plugin: ‘com.huawei.agconnect’ after apply plugin:’com.android.application’.

3. Configure obfuscation scripts.

1

2

3

4

5

6

7

8

9

-ignorewarnings

 -keepattributes *Annotation*

 -keepattributes Exceptions

 -keepattributes InnerClasses

 -keepattributes Signature

 -keepattributes SourceFile,LineNumberTable

 -keep class com.hianalytics.android.**{*;}

 -keep class com.huawei.updatesdk.**{*;}

 -keep class com.huawei.hms.**{*;}

1

2

3

4

5

6

7

8

9

10

11

12

13

"R.string.hms*"

"R.string.connect_server_fail_prompt_toast"

"R.string.getting_message_fail_prompt_toast"

"R.string.no_available_network_prompt_toast"

"R.string.third_app_*"

"R.string.upsdk_*"

"R.layout.hms*"

"R.layout.upsdk_*",  

"R.drawable.upsdk*"

"R.color.upsdk*",  

"R.dimen.upsdk*"

"R.style.upsdk*"

"R.string.agc*"

4. Configure permissions in the AndroidManifest.xml file.

1

2

3

<uses-permission android:name="android.permission.INTERNET"/>

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

Step 5: In the Android Studio window, choose File > Sync Project with Gradle Files to synchronize the project.

Developing Your App

Step 1

Create an activity and import the service packages.

Example:

1

public class ImageKitVisionDemoActivity extends AppCompatActivity implements View.OnClickListener

Import the service packages.

1

2

import com.huawei.hms.image.vision.*;

import com.huawei.hms.image.vision.bean.ImageVisionResult;

Implement the onCreate method and associate the activity_main.xml layout in the method.

1

setContentView(R.layout.activity_filter);

Step 2

Create an activity_main.xml layout file.

Define a button and text box layout.

Example:

1

2

3

4

5

6

7

8

9

10

11

<EditText    

        android:id="@+id/btn_filter"    

        android:layout_width="wrap_content"    

        android:layout_height="wrap_content"    

        android:hint="filterType(0-24)" />

  

<Button    

        android:id="@+id/btn_init"    

        android:layout_width="wrap_content"    

        android:layout_height="wrap_content"    

        android:text="Init_Service" />

Step 3

Define variables in ImageKitVisionDemoActivity and associate them with the button and text box layout of activity_main.xml in the onCreate method.

Example:

1

2

3

4

5

6

7

8

9

//Define the text box and button.

private EditText btn_filter;

private Button btn_init;

// Associate the text editing variable with the text box in the layout based on the layout ID.

btn_filter = findViewById(R.id.btn_filter);

//Associate the button variable with the button in the layout based on the layout ID.

btn_init = findViewById(R.id.btn_init);

//Create a listener for button click events.

btn_init.setOnClickListener(this);

Step 4

Override the onClick method to define the callback for each click event. 

Example:

1

2

3

4

5

6

7

8

@Override

public void onClick(View v) {    

    switch (v.getId()) {        

        case R.id.btn_init:            

            initFilter(context);            

            break;    

    }

}

Step 5

In initFilter of the onClick method, write the method of obtaining an ImageVisionImpl object that is used to obtain the filter effect.

1

2

// Method for obtaining an ImageVisionImpl object.

ImageVisionImpl imageVisionAPI = ImageVision.getInstance(this);

Step 6

In initFilter of the onClick method, write the method of initializing the ImageVision instance.

To call setVisionCallBack during service initialization, you must implement the VisionCallBack API by overriding its onSuccess(ImageVisionImpl imageVision) and onFailure(int errorCode) methods. If the ImageVision instance is successfully initialized, the onSuccess method is called and then the Image Vision service is initialized. If the ImageVision instance fails to be initialized, the onFailure method is called and an error code is returned. Your app is allowed to use the Image Vision service only after the successful verification. That is, the service can be used only if the initialization is successful.

1

2

3

4

5

6

7

8

9

10

11

imageVisionAPI.setVisionCallBack(new ImageVision.VisionCallBack() {

     @Override

     public void onSuccess(int successCode) {

     imageVisionAPI.init(context, authJson);

        ...

     }

     @Override

    public void onFailure(int errorCode) {

         ...

     }

 }); 

Description of authJson parameters:                                                                                          

Parameter 

Type  

Mandatory or Not 

Description  

 

projectId

 

 

String

 

 

Yes

 

Project   ID you obtained when registering with HUAWEI Developers. 

 

appId

 

 

String

 

 

Yes

 

App   ID you obtained during registration.

 

authApiKey

 

 

String

 

 

Yes

 

API   key used for authentication, which is provided by HUAWEI Developers.

clientSecret 

String 

Yes

Client Key 

clientId

String

Yes

Client  ID

 

token

 

 

String

 

 

No

 

Session   token, which is used to verify an app. It is recommended that the app server   obtain the session token from the AppGallery using clientId and ClientSecret.

Note: You can find the preceding parameters except token in the agconnect-services.json file. For details, please refer to the Development Guide. For security purposes, the authentication information used in the sample code is not real. You need to enter the actual authentication information during app development.

Step 7

Construct requestJson parameters.

Description of requestJson and imageBitmap parameters:                                             

Parameter  

Type  

Mandatory or Not  

Description  

requestJson

 

JSONObject

 

Yes

 

JSON string containing image   processing request parameters. 

 

imageBitmap

 

 

Bitmap

 

 

Yes

 

Image to be processed. The aspect ratio is between 1:3 and 3:1, and the width and height pixels are less than or equal to 8000. 

Description of requestJson parameters:                                            

Parameter  

Type  

Mandatory or Not  

Description  

requestId

 

String

 

No

 

Request ID provided by the Image   Vision service. 

taskJson

 

JSONObject

 

Yes

 

JSON string containing detailed   service request information. 

authJson

 

JSONObject

 

Yes

 

JSON string containing authentication   parameters. 

Description of taskJson parameters:                                              

Parameter  

Type  

Mandatory or Not  

Description

 

Index

 

 

int

 

 

No

 

Image index for color mapping. The   value ranges from 0 to 24. Value 0 indicates the original image. 

intensity

float

No

Filter strength. Generally, set this parameter to 1.

compressRate

 

Float

 

No

 

Compression rate. Compression is not   performed by default. The value range is (0-1]. 

For details, see the description of authJson parameters in step 3.

filterType mapping:                                                         

4

5

6

7

8  

9

10

11  

12 

Black-and-white  

 

Brown tone

Lazy

Freesia

Fuji

Peach   pink

 

Sea   salt

 

Mint

 

Reed

 

Vintage

Marshmallow

 

 

Moss

 

                                                                                             

13 

14 

15 

16

17 

18  

19  

20  

21  

22  

23  

24  

Sunlight

Time

Haze blue

Sunflower

Hard

Bronzeyellow

Monochromic tone

Yellow-green   tone

Yellow tone 

Green   tone 

Cyan  tone 

Violet tone

 

 Example requestJson

1

{"requestId":"1","taskJson":{"intensity":"1","filterType":"1","compressRate":"1"},"authJson":{"projectId":"projectIdTest","appId":"appIdTest","authApiKey":"authApiKeyTest","clientSecret":"clientSecretTest","clientId":"clientIdTest","token":"tokenTest"}}

Step 8

Obtain the rendering result from visionResult. Define an API to listen for button click events. Note that the API must be called in a sub-thread other than in the main thread.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

//Obtain the rendering result from visionResult.

Runnable runnable = new Runnable() {    

    @Override    

    public void run() {            

        JSONObject jsonObject = new JSONObject();            

        JSONObject taskJson = new JSONObject();            

        taskJson.put("intensity", intensity);            

        taskJson.put("filterType", filterType);            

        taskJson.put("compressRate", compress);            

        jsonObject.put("requestId""requestId");            

        jsonObject.put("taskJson", taskJson);            

        jsonObject.put("authJson", authJson);            

ImageVisionResult visionResult = imageVisionAPI.getColorFilter(jsonObject,bitmap);     

    }

};

Description of visionResult parameters:                                                   

Parameter  

Type  

Mandatory  or Not  

Description  

resultCode

int

Yes

Result code.

response

JsonObject

No

JSON string containing the returned result.

 

image

 

 

Bitmap

 

 

No

 

Processed image. For an API that   directly returns images, this parameter is used by the API to transfer the   processed image.

Description of response parameters:                              

Parameter  

Type 

Mandatory  or Not  

Description  

 

requestId

 

 

String

 

 

No

 

Request ID provided by the Image   Vision service. This parameter is available only if it is carried in the   service request.

serviceId 

String

Yes

ID of the service being called.

Step 9

Stop the service.

If you do not need to use filters any longer, call the imageVisionAPI.stop() API to stop the Image Vision service. If the returned stopCode is 0, the service is successfully stopped.

1

2

3

if  (null != imageVisionAPI) {

    int stopCode = imageVisionAPI.stop();

 }

Summary

So far, we have finished building the filter function into your app. The entire process is simple yet convenient. What you need to do is simply call the Image Vision service APIs. By integrating Image Kit, your app will be able to access up to 24 ready-made filters, providing a better image editing experience for your users.

To learn more about HUAWEI Image Kit, please visit: 

https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Guides/service-introduction-0000001050040060.



Source link

Write A Comment