TEBeautyKit 導入
Features
To facilitate customers' quick integration of the beauty effect and simplify the development of UI panels, we provide the beauty effect UI component: TEBeautyKit. It includes further encapsulation of the SDK and customizable UI panels, as shown in the figure below. If you prefer not to use this UI, see Integrating Core SDK (Android).
Demo Project: TEBeautyDemo
Clone the demo project from GitHub, follow the instructions in the TEBeautyDemo/README document to run TEBeautyDemo, and then refer to this document for detailed steps on integrating the SDK with UI.
Integrate TEBeautyKit
Note:
This library only supports Tencent Effect SDK V3.5.0 and later versions.
Step 1: Add dependency library
Step 2: Add TEBeautyKit dependency
1. Copy the TEBeautyKit module from the demo project into your project, and modify the SDK package type and version number in
tebeautykit/build.gradle to match the SDK package type and version number in Step 1.implementation 'com.tencent.mediacloud:TencentEffect_S1-04:SDK version number'
2. Then add the dependency on the TEBeautyKit module in the relevant module of your app:
implementation project(':tebeautykit')
Add the TEBeautyKit library dependency to your app's dependencies. The latest version can be queried via [Maven Central].
Versioning Convention: The first three digits of TEBeautyKit's version number must match those of TencentEffect, while the fourth digit should always use the latest available version.
Example: If TencentEffect's version is 3.9.0.8, then TEBeautyKit should select version 3.9.0.x (where x represents the most recent value).
dependencies{...implementation 'com.tencent.mediacloud:TEBeautyKit:SDK version number'}
Since TEBeautyKit also depends on components like Gson and OkHttp, you need to add the following dependencies:
dependencies{implementation 'com.google.code.gson:gson:2.8.2'implementation 'com.squareup.okhttp3:okhttp:3.9.0'implementation 'com.github.bumptech.glide:glide:4.12.0'implementation 'androidx.appcompat:appcompat:1.0.0'implementation 'androidx.constraintlayout:constraintlayout:2.1.3'implementation 'androidx.recyclerview:recyclerview:1.2.1'}
1. Download TEBeautyKit (The downloaded file will be a zip file. Extract it to get the AAR file.)
2. Copy the
tebeautykit-xxxx.aar file to the app project's libs directory.3. Open the app module's
build.gradle and add the dependency reference:dependencies{...implementation fileTree(dir: 'libs', include: ['*.jar','*.aar'])}
Since TEBeautyKit also depends on components like Gson and OkHttp, you need to add the following dependencies:
dependencies{implementation 'com.google.code.gson:gson:2.8.2'implementation 'com.squareup.okhttp3:okhttp:3.9.0'implementation 'com.github.bumptech.glide:glide:4.12.0'implementation 'androidx.appcompat:appcompat:1.0.0'implementation 'androidx.constraintlayout:constraintlayout:2.1.3'implementation 'androidx.recyclerview:recyclerview:1.2.1'}
Step 3: Add the Panel JSON File
Obtain the panel configuration file from the demo project's
demo/src/main/assets/beauty_panel, or click here to download and unzip it,Place it in the assets directory of your project.
How to Use TEBeautyKit
We strongly recommend that you refer to the
TEMenuActivity.java and TECameraBaseActivity.java of the demo project's to understand how to integrate TEBeautyKit.Step 1: Authenticate
1. Apply for authorization to obtain the license URL and license key. Please refer to the License Guide.
2. Set the URL and key in the initialization code of the related business module to trigger license download to avoid downloading temporarily before use. For example, in our demo project, the download is triggered in the onCreate method of the application. However, we do not recommend triggering it here in your project because network permission might not be available or there could be a high rate of network failure at this time. Please choose a more appropriate time to trigger the license download.
// If you only want to trigger the download or update the license without caring about the authentication result, input null for the fourth parameter.//TEApplication.javaTEBeautyKit.setTELicense(context, LicenseConstant.mXMagicLicenceUrl, LicenseConstant.mXMagicKey, null);
3. Perform authentication before actually using the beauty feature (e.g., before launching the camera):
//TEMenuActivity.javaTEBeautyKit.setTELicense(context, LicenseConstant.mXMagicLicenceUrl, LicenseConstant.mXMagicKey, new TELicenseCheckListener() {@Overridepublic void onLicenseCheckFinish(int errorCode, String msg) {// Note: This callback may not be on the calling thread.if (errorCode == TELicenseCheck.ERROR_OK) {// Authentication succeeded.} else {// Authentication failed.}}});
Authentication error code description:
Error Code | Description |
0 | Success |
-1 | Invalid input parameters, such as empty URL or KEY |
-3 | Download failure. Please check your network settings. |
-4 | TE authorization information read locally is empty, possibly due to I/O failure. |
-5 | Content of the VCUBE TEMP license file is empty, possibly due to I/O failure. |
-6 | JSON fields in the v_cube.license file are incorrect. Please contact the Tencent Cloud team to deal with it. |
-7 | Signature verification failed. Please contact the Tencent Cloud team to deal with it. |
-8 | Decryption failed. Please contact the Tencent Cloud team to deal with it. |
-9 | JSON fields in the TELicense field are incorrect. Please contact the Tencent Cloud team to deal with it. |
-10 | The TE authorization information parsed from the network is empty. Please contact the Tencent Cloud team to deal with it. |
-11 | Failed to write TE authorization information to a local file, possibly due to I/O failure |
-12 | Download failed, and parsing local assets also failed. |
-13 | Authentication failed. Please check if the .so file is in the package or if the .so path is set correctly. |
3004/3005 | Invalid authorization. Please contact the Tencent Cloud team to deal with it. |
3015 | Bundle ID/Package Name mismatch. Check if the Bundle ID/Package Name used by your app is consistent with the applied one, and ensure you are using the correct license file. |
3018 | The license file has expired. You need to apply for a renewal from Tencent Cloud. |
Others | Please contact the Tencent Cloud team to deal with it. |
Step 2: Set the path
//TEMenuActivity.javaString resPath = new File(getFilesDir(), AppConfig.getInstance().getBeautyFileDirName()).getAbsolutePath();TEBeautyKit.setResPath(resPath);
Step 3: Copy resources
The resource files mentioned here consist of two parts:
The SDK model files, located in the
assets directory of the SDK's AAR package.Filter and dynamic effect resource files, located in the
assets directory of the demo project, named lut and MotionRes respectively.Before using the beauty effect, you need to copy the above resources to the resPath set in Step 2. If the SDK version is not updated, you only need to copy it once. After a successful copy, you can record it in the SharedPreference of the app, so that you do not need to copy it again next time. For details, refer to the
copyRes method of TEMenuActivity.java in the demo project.//TEMenuActivity.javaprivate void copyRes() { if (!isNeedCopyRes()) { return; } new Thread(() -> { TEBeautyKit.copyRes(getApplicationContext()); }).start(); }
Step 4: Initialize TEBeautyKit and add the view to the page
//TECameraBaseActivity.javaTEBeautyKit.create(this.getApplicationContext(), beautyKit -> {mBeautyKit = beautyKit;initBeautyView(beautyKit);});public void initBeautyView(TEBeautyKit beautyKit) {TEUIConfig.getInstance().setPanelViewResAndEffectPlanName("beauty_panel/index.json", EffectPlan.S1_07);// TEUIConfig.getInstance().setDisPlayNameKey("en");mTEPanelView = new TEPanelView(this);mTEPanelView.setTEPanelViewCallback(this);mTEPanelView.setupWithTEBeautyKit(beautyKit);mTEPanelView.showView(this);this.mPanelLayout.addView(mTEPanelView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));}
Depending on your subscription plan, fill in the corresponding feature JSON accordingly. For instance, if your plan does not include segmentation, there is no need to add
segmentation.json. Similarly, if your package does not support 3D stickers, you should omit motion_3d.json.Step 5: Use beauty effect
We assume you have already implemented the camera application, can start the camera normally, and can call back the camera's SurfaceTexture texture information to Activity for beauty effect processing, as shown below:
//TECameraBaseActivity.java@Overridepublic int onCustomProcessTexture(int textureId, int textureWidth, int textureHeight) {// The beauty effect SDK processes the textureId here, adds beauty effects and special effects for it, and returns the processed new textureID.}
If you have not yet implemented the camera application, you can refer to
TECameraBaseActivity.java in the demo project and use the GLCameraXView component to add it to your Activity's layout for quick camera preview:<com.tencent.demo.camera.camerax.GLCameraXViewandroid:id="@+id/te_camera_layout_camerax_view"android:layout_width="match_parent"android:layout_height="match_parent"app:back_camera="false"app:surface_view="false"app:transparent="true" />
The beauty effect SDK processes each frame of data and returns the corresponding processing results. For detailed information on the process method, see the API Documentation.
//TECameraBaseActivity.java@Override public int onCustomProcessTexture(int textureId, int textureWidth, int textureHeight) { return mBeautyKit.process(textureId, textureWidth, textureHeight); }
Step 6: Manage the lifecycle
Lifecycle method onResume: It is recommended to call it in the
Activity's onResume() method. When called, it will resume the sound in the effects.mBeautyKit.onResume();
Lifecycle method onPause: It is recommended to call it in the Activity's
onPause() method. When called, it will pause the sound in the effects.mBeautyKit.onPause();
Beauty effect release SDK: It is called when the OpenGL environment is being terminated. It needs to be called in the GL thread, and cannot be called in the main thread (Activity's onDestroy); otherwise, it may cause resource leaks and result in a white or black screen after multiple entries and exits.
@Override public void onGLContextDestroy() { mBeautyKit.onDestroy(); }
Step 7: Export and import beauty effect parameters
Export the current beauty effect parameters and save them in SharedPreference:
String json = mBeautyKit.exportInUseSDKParam(); if (json != null) { getSharedPreferences("demo_settings", Context.MODE_PRIVATE).edit().putString("current_beauty_params", json).commit(); }
Next time when initializing TEBeautyKit, import this string to modify the default beauty effect:
Appendix
Panel JSON File Elucidation
The configuration consists of two categories of files, each serving a distinct and independent purpose.
beauty_panel/├── index.json ← Defines which tabs are included in the panel├── panel_json/ ← Defines the feature items within each tab│ ├── beauty_template.json│ ├── beauty.json│ ├── beauty_image.json│ ├── shape.json → beauty_base_shape.json / beauty_general_shape.json / beauty_shape.json│ ├── beauty_body.json│ ├── lut.json│ ├── beauty_makeup.json│ └── motions.json└── panel_icon/ ← All icon resources required by the panel
For detailed instructions, please download the panel resources and refer to the README.md documentation.
TEBeautyKit Method Descriptions
// Asynchronously creates a TEBeautyKit instance@Deprecatedpublic static void create(@NonNull Context context, @NonNull OnInitListener initListener)// isEnableHighPerformance: Whether to enable high-performance mode.// When high-performance mode is enabled, beauty processing consumes fewer system CPU/GPU resources,// which helps reduce device overheating and lag, making it more suitable for long-term use on low-end devices.// Note: When high-performance mode is enabled, the following beauty features will be unavailable:// 1. Eyes: Eye Width, Eye Height, Eye Bags Removal// 2. Eyebrows: Angle, Distance, Height, Length, Thickness, Eyebrow Peak// 3. Mouth: Smile Lips// 4. Face: Face Slimming (Natural, Goddess, Handsome), Chin Reduction, Wrinkle Removal, Nasolabial Fold Removal.// It is recommended to use "Face Shape" to achieve a comprehensive eye-enlarging and face-slimming effect.@Deprecatedpublic static void create(@NonNull Context context, boolean isEnableHighPerformance, @NonNull OnInitListener initListener)public static void create(@NonNull Context context, EffectMode effectMode, @NonNull OnInitListener initListener)private TEBeautyKit(Context context, EffectMode effectMode, @NonNull OnInitListener initListener)// Constructor of TEBeautyKit, used to synchronously create a TEBeautyKit instance@Deprecatedpublic TEBeautyKit(Context context)@Deprecatedpublic TEBeautyKit(Context context, boolean isEnableHighPerformance)public TEBeautyKit(Context context, EffectMode effectMode)/*** @param context Application context* @param isEnableHighPerformance Whether to enable high-performance mode*/public TEBeautyKit(Context context, boolean isEnableHighPerformance)/*** Sets the mute state.** @param isMute true to mute*/public void setMute(boolean isMute)/*** If applying beauty effects to an image, this method must be called to set the data source type.* The available types are camera data source and image data source:* Camera data source: XmagicApi.PROCESS_TYPE_CAMERA_STREAM* Image data source: XmagicApi.PROCESS_TYPE_PICTURE_DATA** @param type The default is video stream type.*/public void setBeautyStreamType(int type)/*** Enables or disables a specific feature.** @param featureName See XmagicConstant.FeatureName for available values* @param enable true to enable, false to disable*/public void setFeatureEnableDisable(String featureName, boolean enable)/*** Applies beauty processing to an image.** @param bitmap* @param needReset* @return*/public Bitmap process(Bitmap bitmap, boolean needReset)/*** Processes each frame of video/camera data.** @param textureId Texture ID. The texture type must be GL_TEXTURE_2D, and the pixel format must be RGBA.* @param width Texture width* @param height Texture height* @return The processed texture ID*/public int process(int textureId, int width, int height)/*** Updates beauty properties.** @param paramList*/public void setEffectList(List<TEUIProperty.TESDKParam> paramList)/*** Updates a beauty property.** @param teParam*/public void setEffect(TEUIProperty.TESDKParam teParam)/*** Enables or disables enhanced mode.** @param enableEnhancedMode true to enable enhanced mode, false to disable it* @return true if the state has changed, false otherwise*/public boolean enableEnhancedMode(boolean enableEnhancedMode)/*** Retrieves the currently active beauty property list as a string.* The exported string can be saved locally by the client, and applied later* by calling the setLastParamList method after creating a new TEPanelView instance.** @return*/public String exportInUseSDKParam()/*** Resumes sound playback in stickers.* Resumes the gyroscope sensor.*/public void onResume()/*** Pauses sound playback in stickers.* Pauses the gyroscope sensor.*/public void onPause()/*** Destroys the beauty engine.* Note: This method must be called on the GL thread.*/public void onDestroy()/*** Sets an event listener to listen for device orientation events, used for the adapter.** @param listener The event listener callback*/public void setEventListener(EventListener listener)/*** Sets the AI data listener callback.** @param aiDataListener*/public void setAIDataListener(XmagicApi.XmagicAIDataListener aiDataListener)/*** Sets the animation tips callback, used to display tips on the front-end page.** @param tipsListener*/public void setTipsListener(XmagicApi.XmagicTipsListener tipsListener)/*** Captures the current frame from the texture.** @param callback*/public void exportCurrentTexture(XmagicApi.ExportTextureCallback callback)/*** Sets the counterclockwise rotation angle of the texture.* Purpose: Used internally by the SDK to rotate the texture so that the face is upright,* allowing the SDK to correctly detect the face.* By default, the SDK uses the sensor to determine the rotation angle.** @param orientation Valid values are 0, 90, 180, and 270 only*/public void setImageOrientation(TEImageOrientation orientation)/*** Checks whether the current device supports the given material.** @param motionResPath The path of the material file* @return*/public boolean isDeviceSupport(String motionResPath)/*** Gets the current state of the beauty effect.** @return EffectState*/public EffectState getEffectState()/*** Sets whether beauty effects are enabled.** @param effectState ENABLED to turn on, DISABLED to turn off*/public void setEffectState(EffectState effectState)/*** Sets the strategy implementation for enhanced mode.* If not set, the default implementation will be used.** @param teParamEnhancingStrategy The enhanced mode strategy handler*/public void setParamEnhancingStrategy(TEParamEnhancingStrategy teParamEnhancingStrategy)// Static methods are as follows/*** Sets the storage path for beauty resources.** @param resPath*/public static void setResPath(String resPath)/*** Extracts resource files from the APK's assets to the specified path.* The path must be set beforehand via {@link #setResPath(String)}.* This only needs to be called once after the app is first installed or upgraded.* Copies xmagic resources from assets to a local path.*/public static boolean copyRes(Context context)/*** Performs beauty license authentication.* Note: When calling this method, if no callback is provided, authentication will not be performed* (it will only download license information from the network).* Refer to the demo: you can call this method in Application without a callback,* and then call it again with a callback before using the TEBeautyKit instance to complete authentication.** @param context Application context* @param licenseKey The licenseKey applied for on the platform* @param licenseUrl The licenseUrl applied for on the platform* @param teLicenseCheckListener The authentication callback listener*/public static void setTELicense(Context context, String licenseUrl, String licenseKey, TELicenseCheck.TELicenseCheckListener teLicenseCheckListener)
TEUIConfig explanation
Alter the panel color
Global modification: After accessing the object through
TEUIConfig.getInstance(), you can adjust the panel color by modifying the following fields.Partial Modification: Using the
new TEUIConfig object, adjust the panel color by modifying the following fields, and update the panel style using the TEPanelView.updateUIConfig method./*** The overall background color of the beauty panel (applied to the bottom panel container).*/@ColorIntpublic int panelBackgroundColor = 0xAA000000;/*** The color of dividers inside the panel (e.g., the divider below the top title bar* and the vertical dividers between items).*/@ColorIntpublic int panelDividerColor = 0x19FFFFFF;/*** The text color of a selected item in the secondary panel.*/@ColorIntpublic int panelItemCheckedColor = 0xFFFFFFFF;/*** The text color of a default (unselected) item in the secondary panel.*/@ColorIntpublic int panelItemColor = 0x99FFFFFF;/*** The text color of a default (unselected) tab in the top title bar.*/@ColorIntpublic int textColor = 0x99FFFFFF;/*** The text color of a selected tab in the top title bar.*/@ColorIntpublic int textCheckedColor = 0xFFFFFFFF;/*** The primary color of the SeekBar, applied to:* 1) The selected portion of the progress track* 2) The thumb* 3) The bubble indicator shown while dragging*/@ColorIntpublic int seekBarProgressColor = 0xFFFFFFFF;
JSON file of the configuration panel
TEUIConfig.getInstance().setPanelViewResAndEffectPlanName("beauty_panel/index.json", EffectPlan.S1_07);
Type 1/*** Set the JSON file path for the beauty panel* @param beauty The JSON file path for beauty attributes, set to null if not available* @param beautyBody The JSON file path for body sculpting attributes, set to null if not available* @param lut The JSON file path for filter attributes, set to null if not available* @param motion The JSON file path for motion sticker attributes, set to null if not available* @param makeup The JSON file path for full makeup style attributes, set to null if not available* @param segmentation The JSON file path for segmentation attributes, set to null if not available*/public void setTEPanelViewRes(String beauty, String beautyBody, String lut, String motion, String makeup, String segmentation)Type 2List<TEPanelDataModel> panelDataModels = TEUIConfig.getInstance().getPanelDataList();panelDataModels.clear();//Add the corresponding JSON according to the package featuresTEPanelDataModel template = new TEPanelDataModel("beauty_panel/beauty_template.json", TEUIProperty.UICategory.BEAUTY_TEMPLATE);TEPanelDataModel beauty1 = new TEPanelDataModel("beauty_panel/beauty.json", TEUIProperty.UICategory.BEAUTY);TEPanelDataModel beauty2 = new TEPanelDataModel("beauty_panel/beauty_image.json", TEUIProperty.UICategory.BEAUTY);TEPanelDataModel beauty4 = new TEPanelDataModel("beauty_panel/beauty_shape.json", TEUIProperty.UICategory.BEAUTY);TEPanelDataModel beauty3 = new TEPanelDataModel("beauty_panel/beauty_makeup.json", TEUIProperty.UICategory.BEAUTY);TEPanelDataModel lut = new TEPanelDataModel("beauty_panel/lut.json", TEUIProperty.UICategory.LUT);TEPanelDataModel lightMakeup = new TEPanelDataModel("beauty_panel/light_makeup.json",TEUIProperty.UICategory.LIGHT_MAKEUP);TEPanelDataModel makeup = new TEPanelDataModel("beauty_panel/makeup.json", TEUIProperty.UICategory.MAKEUP);TEPanelDataModel motion = new TEPanelDataModel("beauty_panel/motion_2d.json", TEUIProperty.UICategory.MOTION);TEPanelDataModel motion2 = new TEPanelDataModel("beauty_panel/motion_3d.json", TEUIProperty.UICategory.MOTION);TEPanelDataModel motion_gesture = new TEPanelDataModel("beauty_panel/motion_gesture.json",TEUIProperty.UICategory.MOTION);TEPanelDataModel seg = new TEPanelDataModel("beauty_panel/segmentation.json", TEUIProperty.UICategory.SEGMENTATION);panelDataModels.add(template);panelDataModels.add(beauty1);panelDataModels.add(beauty2);panelDataModels.add(beauty4);panelDataModels.add(beauty3);panelDataModels.add(lut);panelDataModels.add(lightMakeup);panelDataModels.add(makeup);panelDataModels.add(motion);panelDataModels.add(motion2);panelDataModels.add(motion_gesture);panelDataModels.add(seg);
Multilingual Configuration
The language settings of the panel consist of two parts:
System Text and Panel Item Names.1.System Text
System text is located in the
res/values/strings.xml file. Supported languages by default: Simplified Chinese, English.
To add additional languages:
Create a corresponding resource folder (e.g.,
values-ja, values-ko) under your project's `res` directory. Create a `strings.xml` file within that folder.
Translate the text content of TEBeautyKit.
2.Panel Item Names
1. Add the corresponding language text under the `name` node in the panel JSON file.
2. In the code, set the key for the language to be displayed. For example, to display English:
TEUIConfig.getInstance().setDisPlayNameKey("en") Panel item names are defined in the JSON configuration file and controlled by the following two fields:
Field | Default Language |
displayName | Simplified Chinese |
displayNameEn | English |
Switch between Chinese and English:
// Display Chinese (using the displayName field)TEUIConfig.getInstance().setUseDisplayName(true);// Display English (using the displayNameEn field)TEUIConfig.getInstance().setUseDisplayName(false);
Adding Additional Languages:
Duplicate the original JSON file and create corresponding language versions (e.g., panel_zh_hant.json).
Translate the value of the displayName field into the target language.
Detect the current system language in the code and load the corresponding JSON file.
Invoke TEUIConfig.getInstance().setUseDisplayName(true).
Description of TEPanelView
/** * This is utilized for setting the previously used beauty effect data, with the intent to revert the beauty panel back to its prior state. * Note: This method needs to be used prior to the {@link #showView(TEPanelViewCallback tePanelViewCallback)}} method. * * @param lastParamList The beauty data, which is accessible through the {@link TEBeautyKit#exportInUseSDKParam()} ()}} method, and then stored, to be passed as a string when starting the beauty feature the next time. */ void setLastParamList(String lastParamList); /** * Present the beauty panel * @param tePanelViewCallback The interface callback for panel events */ void showView(TEPanelViewCallback tePanelViewCallback); /** * Synchronizes with TEBeautyKit object, which the beauty panel calls directly to set attributes when a user selects an item. * @param beautyKit The TEBeautyKit object */ void setupWithTEBeautyKit(TEBeautyKit beautyKit);/** * Select Self-Definition split or green screen item from the Settings, because the green screen or Self-Definition split button jumps to the gallery after clicking, * Only after the user has selected a picture or video, the corresponding item can be selected. If the user cancels the operation during this process, the corresponding item cannot be selected * * @param uiProperty */ void validatePanelViewItem(TEUIProperty uiProperty);/** * Configuring the UI of the current panel * @param uiConfig */ void updateUIConfig(TEUIConfig uiConfig);
