Borrow graphic smart typesetting to make beautiful lock screen pictures

1 Introduction

Insert picture description here

Does the above exquisite picture and text after the phone lock screen look beautiful?

These lock screen pictures are included with the phone. Sometimes our photography-loving classmates take beautiful pictures by themselves. Do you want to add pictures and texts as lock screen pictures?

The intelligent typesetting capability of graphics and text provided by our HMS Core can realize this function, allowing users to experience the exquisite pictures taken by themselves directly on the mobile phone. Through the graphics and text can only be typeset into exquisite magazine lock screen pictures.

2- scene

Refer to the current classic picture text typesetting, HMS Core graphic smart typesetting currently provides 9 text typesetting styles. Developers can use this ability to quickly and easily integrate this ability, providing photography enthusiasts and graphic editors to add refinement to photographic pictures. Typeset text and pictures with both pictures and texts can be used to record classic moments in life, and can also be used as lock screen pictures.

3- Integrate key step instructions and codes

Development preparation

1- Configure Huawei Maven warehouse address

Open the build.gradle file in the AndroidStudio project

Insert picture description here

Add the Maven warehouse address of the SDK in "buildscript> repositories" and "allprojects> repositories":

buildscript {
    repositories{
      ...   
        maven {url 'http://developer.huawei.com/repo/'}
    }    
}
allprojects {
    repositories {      
         maven { url 'http://developer.huawei.com/repo/'}
    }
}

2- Add compile SDK dependency

Open the application-level "build.gradle" file

Insert picture description here

Add the SDK package of the graphics engine in dependencies, use Full-SDK, and the SDK package of AR Engine

dependencies {
….
   implementation "com.huawei.hms:image-vision:1.0.3.301"
   implementation "com.huawei.hms:image-vision-fallback:1.0.3.301"
}

3- Add permissions in AndroidManifest.xml

Open the AndroidManifest.xml file in main, and add relevant usage permissions before <application

<!—Access to the network and read and write storage permissions-->

<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" />
   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Development steps

1- Layout
is the content that needs to be entered as follows, which is used for the intelligent display of graphics and text:

  1. title: The title of the copy, a required field, no more than 7 Chinese characters (the total number of characters is no more than 10), if it exceeds the word limit, it will be forcibly truncated.

  2. description: The content of the copy, no more than 44 Chinese characters (the total number of characters is no more than 66), truncated if the number of characters exceeds the limit, and replaced by'…'

  3. copyRight: The name of the individual/company to which the copyright of the image belongs. It is recommended that no more than 7 Chinese characters (the total number of characters is not more than 10), and the number of characters exceeds the limit will be truncated and replaced with'…'.

  4. Anchor: "details" or "see more", it is recommended that 4 Chinese characters (the total number of characters does not exceed 6) should be truncated if the number of characters exceeds the limit, and replaced with'...'.

  5. info: The layout of info1-info9 can choose one of them, note info8 is vertical layout, currently only supports Chinese layout, and does not support other language layouts; info3 is the default pocket layout; if the user enters info8 and the input label and text description are not Chinese Language, return user info3 format.

Insert picture description here

Button functions:

INIT_SERVICE corresponds to service initialization,

SOTP_SERVICE stop service

IMAGE Select to open the picture on the phone

GET_RESULT: Get the displayed layout image

2- INIT_SERVICE-service initialization
service initialization, when calling setVisionCallBack, you need to implement the ImageVision.VisionCallBack interface, and rewrite the onSuccess(int successCode) and onFailure(int errorCode) methods. After the framework is initialized successfully, the onSuccess method will be called back. In the onSuccess method, the graphic intelligent typesetting service needs to be initialized again.

1.  private void initTag(final Context context) {  

2.  // 获取ImageVisionImpl 对象  

3.      imageVisionTagAPI = ImageVision.getInstance(this);  

4.      imageVisionTagAPI.setVisionCallBack(new ImageVision.VisionCallBack() {  

5.          @Override  

6.          public void onSuccess(int successCode) {  

7.              int initCode = imageVisionTagAPI.init(context, authJson);  

8.          }  

9.    

10.         @Override  

11.         public void onFailure(int errorCode) {  

12.             LogsUtil.e(TAG, "getImageVisionAPI failure, errorCode = " + errorCode);   

13.         }  

14.     });  

15. }  

The format of authJson refers to the following link

https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Guides/vision-service-dev_filter-0000001054127298

Token is a required value, refer to the following link for the method of obtaining token

https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Guides-V5/get_token-0000001055139693-V5

1.  /** 

2.   * Gets token. 

3.   * 

4.   * @param context the context 

5.   * @param client_id the client id 

6.   * @param client_secret the client secret 

7.   * @return the token 

8.   */  

9.  public static String getToken(Context context, String client_id, String client_secret) {  

10.     String token = "";  

11.     try {  

12.         String body = "grant_type=client_credentials&client_id=" + client_id + "&client_secret=" + client_secret;  

13.         token = commonHttpsRequest(context, body, context.getResources().getString(R.string.urlToken));  

14.         if (token != null && token.contains(" ")) {  

15.             token = token.replaceAll(" ", "+");  

16.             token = URLEncoder.encode(token, "UTF-8");  

17.         }  

18.     } catch (UnsupportedEncodingException e) {  

19.         LogsUtil.e(TAG, e.getMessage());  

20.     }  

21.     return token;  

22. }  

3- Image-Open the local picture of the phone:

1.  public static void getByAlbum(Activity act) {  

2.      Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);  

3.      String[] mimeTypes = {"image/jpeg", "image/png", "image/webp"};  

4.      getAlbum.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);  

5.      getAlbum.setType("image/*");  

6.      getAlbum.addCategory(Intent.CATEGORY_OPENABLE);  

7.      act.startActivityForResult(getAlbum, 801);  

8.  }  
1.  /** 

2.       * Process the obtained image. 

3.       */  

4.      @Override  

5.      public void onActivityResult(int requestCode, int resultCode, Intent data) {  

6.          super.onActivityResult(requestCode, resultCode, data);  

7.          if (data != null) {  

8.              if (resultCode == Activity.RESULT_OK) {  

9.                  switch (requestCode) {  

10.                     case 801:  

11.                         try {  

12.                             imageBitmap = Utility.getBitmapFromUri(data, this);  

13.                             iv.setImageBitmap(imageBitmap);  

14.                             break;  

15.                         } catch (Exception e) {  

16.                             LogsUtil.e(TAG, "Exception: " + e.getMessage());  

17.                         }  

18.                 }  

19.             }  

20.         }  

21.     }  

4- GET_RESULT-Get the displayed picture after layout
1-Construct the parameter object

Insert picture description here

Corresponding to requestJson code:

1.  /* 

2.      title: 文案标题 

3.      description:文案内容 

4.      copyRight:图片版权归属的个人/公司名称  

5.      anchor:“详情”或“查看更多”  

6.      info: info1-info9的排版可以选择其中一个  

7.   */  

8.    

9.  private void createRequestJson(String title, String description, String copyRight, String anchor, String info) {  

10.     try {  

11.         JSONObject taskJson = new JSONObject();  

12.         taskJson.put("title", title);  

13.         taskJson.put("imageUrl", "imageUrl");  

14.         taskJson.put("description", description);  

15.         taskJson.put("copyRight", copyRight);  

16.         taskJson.put("isNeedMask", false);  

17.         taskJson.put("anchor", anchor);  

18.         JSONArray jsonArray = new JSONArray();  

19.         if (info != null && info.length() > 0) {  

20.             String[] split = info.split(",");  

21.             for (int i = 0; i < split.length; i++) {  

22.                 jsonArray.put(split[i]);  

23.             }  

24.         } else {  

25.             jsonArray.put("info8");  

26.         }  

27.         taskJson.put("styleList", jsonArray);  

28.         requestJson.put("requestId", "");  

29.         requestJson.put("taskJson", taskJson);  

30.         requestJson.put("authJson", authJson);  

31.   

32.         Log.d(TAG, "createRequestJson: "+requestJson);  

33.     } catch (JSONException e) {  

34.         LogsUtil.e(TAG, e.getMessage());  

35.     }  

36. }  

2- Show some code

The graphic intelligent typesetting service needs to be connected to the HMS Core cloud to obtain the display style. If not connected to the Internet, the info3 style will be returned by default

1.  private void layoutAdd(String title, String info, String description, String copyRight, String anchor) {  

2.      if (imageBitmap == null) {  

3.          return;  

4.      }  

5.      final Bitmap reBitmap = this.imageBitmap;  

6.      new Thread(new Runnable() {  

7.          @Override  

8.          public void run() {  

9.              try {  

10.                 token = Utility.getToken(context, client_id, client_secret);  

11.                 authJson.put("token", token);  

12.                 createRequestJson(title, description, copyRight, anchor, info);  

13.                 final ImageLayoutInfo imageLayoutInfo = imageVisionLayoutAPI.analyzeImageLayout(requestJson,  reBitmap);  

14.                 runOnUiThread(new Runnable() {  

15.                     @Override  

16.                     public void run() {  

17.                         iv.setImageBitmap(null);  

18.                         Bitmap resizebitmap = Bitmap.createScaledBitmap(Utility.cutSmartLayoutImage(reBitmap), width, height, false);  

19.                         img_btn.setBackground(new BitmapDrawable(getResources(), resizebitmap));  

20.                         setView(imageLayoutInfo);  

21.                         viewSaveToImage(show_image_view);  

22.                     }  

23.                 });  

24.             } catch (JSONException e) {  

25.                 LogsUtil.e(TAG, "JSONException" + e.getMessage());  

26.             }  

27.         }  

28.     }).start();  

29.   

30. }  

5- SOTP_SERVICE stop service
When the graphic intelligent typesetting effect is no longer needed, call this interface to stop the service, when stopCode is 0, the execution is successful.

1.  private void stopFilter() {  

2.          if (null != imageVisionLayoutAPI) {  

3.              int stopCode = imageVisionLayoutAPI.stop();  

4.              tv2.setText("stopCode:" + stopCode);  

5.              iv.setImageBitmap(null);  

6.              imageBitmap = null;  

7.              stopCodeState = stopCode;  

8.              tv.setText("");  

9.              imageVisionLayoutAPI = null;  

10.         } else {  

11.             tv2.setText("The service has not been enabled.");  

12.             stopCodeState = 0;  

13.         }  

14.     }  

4- effect display

Open the App and click the INIT_SERVICE button below to initialize the service; after success, click the IMAGE button to select a picture taken locally; then click GET_RESULT to get the beautiful picture after smart graphic layout

Insert picture description here

Insert picture description here

Insert picture description here

Insert picture description here

5- source code

To participate in developer discussions, please go to the Reddit community:https://www.reddit.com/r/HMSCore/

To download the demo and sample code, please go to Github:https://github.com/HMS-Core

To solve integration problems, please go to Stack Overflow:https://stackoverflow.com/questions/tagged/huawei-mobile-services?tab=Newest


Original link:https://developer.huawei.com/consumer/cn/forum/topic/0202441824310590439?fid=18

Author: Pepper

Guess you like

Origin blog.51cto.com/14772288/2608897