借用圖文智能排版製做精美的鎖屏圖片

1-前言

在這裏插入圖片描述

上面這張手機鎖屏後精美的圖文,是否是看起來很美?java

這些鎖屏圖片是手機自帶的。有時候咱們愛好攝影的同窗本身拍了美美的照片,是否是也想加上圖文做爲鎖屏圖片呢?android

咱們HMS Core提供的圖文智能排版能力,就能夠實現這個功能,讓用戶直接在手機上就能體驗本身拍攝的精美圖片經過圖文只能排版製做成精美的雜誌鎖屏圖片。git

2-場景

參考當前經典的圖片文字排版,HMS Core圖文智能排版當前提供了9種文字排版樣式,開發者可使用快速簡單地集成這個能力,提供給攝影愛好者以及圖文編輯者在攝影圖片上添加精緻排版過的文字,圖文並茂的圖片既能夠用來記錄生活中的經典時刻,也能夠用來做爲鎖屏的圖片。github

3-集成關鍵步驟說明和代碼

開發準備

1-配置華爲Maven倉地址web

打開AndroidStudio項目中的build.gradle文件json

在這裏插入圖片描述

在「buildscript > repositories」和「allprojects > repositories」中增長SDK的Maven倉地址:網絡

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

2-添加編譯SDK依賴app

打開應用級的「build.gradle」文件框架

在這裏插入圖片描述

在dependencies中添加圖形引擎的SDK包,使用Full-SDK,以及AR Engine的SDK包maven

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

3-在AndroidManifest.xml中添加權限

打開main中的AndroidManifest.xml文件,在<application 前添加相關的使用權限

<!—訪問網絡和讀寫存儲權限-->

<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" />

開發步驟

1- Layout
以下是須要輸入的內容,用於圖文智能展現的文字:

  1. title: 文案標題,必填字段,不超過7箇中文漢字(總字符數量不超過10個),若是超過字數限制會被強制截斷。

  2. description: 文案內容,不超過44箇中文漢字(總字符數量不超過66個),超過字數限制則進行截斷,用‘…’代替

  3. copyRight: 圖片版權歸屬的我的/公司名稱,建議不超過7箇中文漢字(總字符數量不超過10個),超過字數限制則進行截斷,用‘…’代替。

  4. anchor:「詳情」或「查看更多」,建議4箇中文漢字(總字符數不超過6個)超過字數限制則進行截斷,用‘…’代替。

  5. info: info1-info9的排版能夠選擇其中一個,備註info8爲豎板排版,當前僅支持中文版式,不支持其餘語言版式;info3爲默認兜底版式;若用戶輸入info8且輸入標籤、文本描述有非中文語種,返回用戶info3版式。

在這裏插入圖片描述

按鈕部分功能:

INIT_SERVICE對應服務初始化,

SOTP_SERVICE 中止服務

IMAGE 選擇打開手機上的圖片

GET_RESULT: 獲取展現的排版後圖片

2- INIT_SERVICE-服務初始化
服務初始化,調用setVisionCallBack時須要實現ImageVision.VisionCallBack接口,重寫其中的onSuccess(int successCode)和onFailure(int errorCode)方法。框架初始化成功後會回調onSuccess方法,在onSuccess方法中,須要再初始化圖文智能排版服務。

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. }

其中authJson的格式參考以下連接

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

token爲必選值,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-打開手機本地圖片:

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-獲取展現的排版後圖片
1- 構建參數對象

在這裏插入圖片描述

對應requestJson代碼:

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- 展現部分代碼

圖文智能排版服務須要聯網從HMS Core雲端獲取展現樣式,如不聯網,則默認反回info3樣式

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 中止服務
當再也不須要圖文智能排版效果時,調用該接口中止服務,stopCode爲0時,執行成功。

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-效果展現

打開App點擊下面的INIT_SERVICE按鈕,初始化服務;成功後點擊IMAGE按鈕選擇本地拍攝的圖片;而後點擊GET_RESULT獲取智能圖文排版後的精美圖片

在這裏插入圖片描述

在這裏插入圖片描述

在這裏插入圖片描述

在這裏插入圖片描述

5-源碼

參與開發者討論請到Reddit社區:https://www.reddit.com/r/HMSCore/

下載demo和示例代碼請到Github:https://github.com/HMS-Core

解決集成問題請到Stack Overflow:https://stackoverflow.com/questions/tagged/huawei-mobile-services?tab=Newest


原文連接:https://developer.huawei.com/consumer/cn/forum/topic/0202441824310590439?fid=18

原做者:胡椒

相關文章
相關標籤/搜索