Android接入Pixelfree美颜SDK技术指南

概述

Pixelfree是一款功能强大的美颜SDK,支持实时美颜、滤镜、贴纸等功能。本文档将详细介绍如何在Android项目中接入Pixelfree SDK,包括带UI和不带UI两种接入方式。

项目结构

bash 复制代码
SMBeautyEngine_andriod/
├── pixelfree_android_demo/
│   ├── app/                    # 主应用模块
│   ├── sdk-aar/               # SDK AAR文件
│   ├── lib_pixelFree_uikit/   # UI组件库
│   └── hapiAVRender/          # 渲染模块

环境要求

  • Android Studio 4.0+
  • Android SDK 21+
  • Gradle 7.1.2+

1. 基础配置

1.1 添加依赖

在项目根目录的 build.gradle 中添加:

rust 复制代码
buildscript {
    repositories {
        maven { url 'https://jitpack.io' }
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.1.2'
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10'
    }
}

settings.gradle 中添加模块:

php 复制代码
include ':app'
include ':sdk-aar'
include ':lib_pixelFree_uikit'
include ':hapiAVRender'

在应用模块的 build.gradle 中添加依赖:

java 复制代码
dependencies {
    implementation project(':hapiAVRender')
    implementation project(':sdk-aar')
    implementation project(':lib_pixelFree_uikit')
    
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.5.0'
    implementation 'com.google.android.material:material:1.6.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
}

1.2 权限配置

AndroidManifest.xml 中添加必要权限:

ini 复制代码
<uses-feature android:name="android.hardware.camera.any" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
​
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

1.3 资源文件

将以下文件添加到 app/src/main/assets/ 目录:

  • pixelfreeAuth.lic - 授权文件
  • filter_model.bundle - 美颜模型文件
  • 各种贴纸 .bundle 文件
  • allStickers.json - 贴纸配置文件

2. 不带UI接入方式

2.1 基础初始化

kotlin 复制代码
class MainActivity : AppCompatActivity() {
    
    private val mPixelFree by lazy {
        PixelFree()
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        // 初始化SDK
        initPixelFree()
    }
    
    private fun initPixelFree() {
        // 创建SDK实例
        mPixelFree.create()
        
        // 读取授权文件
        val authData = mPixelFree.readBundleFile(this, "pixelfreeAuth.lic")
        mPixelFree.auth(this.applicationContext, authData, authData.size)
        
        // 加载美颜模型
        val faceFilter = mPixelFree.readBundleFile(this, "filter_model.bundle")
        mPixelFree.createBeautyItemFormBundle(
            faceFilter,
            faceFilter.size,
            PFSrcType.PFSrcTypeFilter
        )
    }
    
    override fun onDestroy() {
        mPixelFree.release()
        super.onDestroy()
    }
}

2.2 图像处理

kotlin 复制代码
private fun processImage(bitmap: Bitmap) {
    if (!mPixelFree.isCreate()) return
    
    // 转换图像格式
    val rgbaData = convertBitmapToRGBA(bitmap)
    
    // 创建输入参数
    val pxInput = PFImageInput().apply {
        wigth = bitmap.width
        height = bitmap.height
        p_data0 = rgbaData
        p_data1 = null
        p_data2 = null
        stride_0 = bitmap.rowBytes
        stride_1 = 0
        stride_2 = 0
        textureID = 0
        format = PFDetectFormat.PFFORMAT_IMAGE_RGBA
        rotationMode = PFRotationMode.PFRotationMode0
    }
    
    // 处理图像
    mPixelFree.processWithBuffer(pxInput)
    
    // 获取处理结果
    mPixelFree.textureIdToBitmap(pxInput.textureID, pxInput.wigth, pxInput.height) { resultBitmap ->
        // 处理结果图像
        runOnUiThread {
            imageView.setImageBitmap(resultBitmap)
        }
    }
}
​
private fun convertBitmapToRGBA(bitmap: Bitmap): ByteArray {
    val bytes = ByteArray(bitmap.width * bitmap.height * 4)
    bitmap.copyPixelsToBuffer(ByteBuffer.wrap(bytes))
    return bytes
}

2.3 美颜参数设置

scss 复制代码
// 设置美白强度
mPixelFree.pixelFreeSetBeautyFiterParam(
    PFBeautyFilterType.PFBeautyFilterTypeFaceM_newWhitenStrength, 
    0.5f
)
​
// 设置磨皮强度
mPixelFree.pixelFreeSetBeautyFiterParam(
    PFBeautyFilterType.PFBeautyFilterTypeFaceBlurStrength, 
    0.7f
)
​
// 设置大眼效果
mPixelFree.pixelFreeSetBeautyFiterParam(
    PFBeautyFilterType.PFBeautyFilterTypeFace_EyeStrength, 
    0.3f
)
​
// 设置瘦脸效果
mPixelFree.pixelFreeSetBeautyFiterParam(
    PFBeautyFilterType.PFBeautyFilterTypeFace_thinning, 
    0.4f
)

2.4 滤镜设置

scss 复制代码
// 设置滤镜
mPixelFree.pixelFreeSetFilterParam("chulian", 0.8f)

// 设置一键美颜
mPixelFree.pixelFreeSetBeautyFiterParam(
    PFBeautyFilterType.PFBeautyFilterTypeOneKey,
    PFBeautyTypeOneKey.PFBeautyTypeOneKeyNatural.ordinal
)

2.5 贴纸设置

scss 复制代码
// 加载贴纸
val stickerData = mPixelFree.readBundleFile(context, "bear_headgear.bundle")
mPixelFree.createBeautyItemFormBundle(
    stickerData,
    stickerData.size,
    PFSrcType.PFSrcTypeSticker
)

// 设置贴纸
mPixelFree.pixelFreeSetBeautyFiterParam(
    PFBeautyFilterType.PFBeautyFilterSticker2DFilter,
    1.0f
)

3. 带UI接入方式

3.1 使用PixeBeautyDialog

kotlin 复制代码
class MainActivity : AppCompatActivity() {
    
    private val mPixelFree by lazy {
        PixelFree()
    }
    
    private val mPixeBeautyDialog by lazy {
        PixeBeautyDialog(mPixelFree)
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        // 初始化SDK
        initPixelFree()
        
        // 显示美颜对话框
        findViewById<Button>(R.id.showBeauty).setOnClickListener {
            mPixeBeautyDialog.show(supportFragmentManager, "")
        }
    }
    
    private fun initPixelFree() {
        mPixelFree.create()
        val authData = mPixelFree.readBundleFile(this, "pixelfreeAuth.lic")
        mPixelFree.auth(this.applicationContext, authData, authData.size)
        val faceFilter = mPixelFree.readBundleFile(this, "filter_model.bundle")
        mPixelFree.createBeautyItemFormBundle(
            faceFilter,
            faceFilter.size,
            PFSrcType.PFSrcTypeFilter
        )
    }
}

3.2 自定义BeautyView

kotlin 复制代码
class CustomBeautyActivity : AppCompatActivity() {
    
    private val mPixelFree by lazy {
        PixelFree()
    }
    
    private lateinit var beautyView: BeautyView
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_custom_beauty)
        
        initPixelFree()
        setupBeautyView()
    }
    
    private fun setupBeautyView() {
        beautyView = findViewById(R.id.beauty_view)
        beautyView.pixelFreeGetter = { mPixelFree }
        
        // 创建美颜项目列表
        val beautyItems = ArrayList<BeautyItem>().apply {
            add(BeautyItem(
                PFBeautyFilterType.PFBeautyFilterTypeFaceM_newWhitenStrength, 
                0.2f, "美白", "meibai"
            ))
            add(BeautyItem(
                PFBeautyFilterType.PFBeautyFilterTypeFaceBlurStrength, 
                0.7f, "磨皮", "mopi"
            ))
            add(BeautyItem(
                PFBeautyFilterType.PFBeautyFilterTypeFace_EyeStrength, 
                0.2f, "大眼", "dayan"
            ))
        }
        
        beautyView.setList(beautyItems)
    }
}

3.3 颜色调节对话框

kotlin 复制代码
private val mColorGradingDialog by lazy {
    ColorGradingDialog(this, mPixelFree) { 
        // 颜色调节回调
    }
}

// 显示颜色调节对话框
findViewById<Button>(R.id.showColorGrading).setOnClickListener {
    mColorGradingDialog.show()
}

4. 实时视频处理

4.1 摄像头集成

kotlin 复制代码
class VideoBeautyActivity : AppCompatActivity() {
    
    private val mPixelFree by lazy {
        PixelFree()
    }
    
    val hapiCapturePreView by lazy { 
        findViewById<HapiCapturePreView>(R.id.preview) 
    }
    
    // 摄像头轨道
    private val cameraTrack by lazy {
        HapiTrackFactory.createCameraXTrack(this, this, 720, 1280).apply {
            frameCall = object : FrameCall<VideoFrame> {
                override fun onFrame(frame: VideoFrame) {
                    // 帧回调
                }
                
                override fun onProcessFrame(frame: VideoFrame): VideoFrame {
                    if (mPixelFree.isCreate()) {
                        val pxInput = PFImageInput().apply {
                            wigth = frame.width
                            height = frame.height
                            p_data0 = frame.data
                            p_data1 = frame.data
                            p_data2 = frame.data
                            stride_0 = frame.rowStride
                            stride_1 = frame.rowStride
                            stride_2 = frame.rowStride
                            format = PFDetectFormat.PFFORMAT_IMAGE_RGBA
                            rotationMode = PFRotationMode.PFRotationMode90
                        }
                        
                        mPixelFree.processWithBuffer(pxInput)
                        frame.textureID = pxInput.textureID
                    }
                    return super.onProcessFrame(frame)
                }
            }
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video_beauty)
        
        initPixelFree()
        setupCamera()
    }
    
    private fun setupCamera() {
        cameraTrack.playerView = hapiCapturePreView
        cameraTrack.start()
        
        hapiCapturePreView.mHapiGLSurfacePreview.mOpenGLRender.glCreateCall = {
            // OpenGL上下文创建后初始化SDK
            initPixelFree()
        }
    }
}

5. 性能优化

5.1 内存管理

kotlin 复制代码
// 及时释放资源
override fun onDestroy() {
    mPixelFree.release()
    super.onDestroy()
}

// 避免频繁创建对象
private val pxInput = PFImageInput()
private val rgbaData = ByteArray(MAX_IMAGE_SIZE * 4)

5.2 线程处理

scss 复制代码
// 在GL线程中处理图像
mPixelFree.glThread.runOnGLThread {
    mPixelFree.processWithBuffer(pxInput)
}

5.3 参数缓存

kotlin 复制代码
// 缓存常用参数
private val beautyParams = mutableMapOf<PFBeautyFilterType, Float>()

private fun setBeautyParam(type: PFBeautyFilterType, value: Float) {
    if (beautyParams[type] != value) {
        mPixelFree.pixelFreeSetBeautyFiterParam(type, value)
        beautyParams[type] = value
    }
}

6. 常见问题

6.1 授权问题

确保 pixelfreeAuth.lic 文件正确放置在 assets 目录中,并且授权有效。

6.2 模型加载失败

检查 filter_model.bundle 文件是否存在且完整。

6.3 内存泄漏

确保在Activity销毁时调用 mPixelFree.release()

7. 总结

本文档详细介绍了Android项目中接入Pixelfree美颜SDK的两种方式:

  1. 不带UI接入:适合需要自定义界面的应用,可以完全控制美颜参数的设置和界面设计。
  2. 带UI接入:使用SDK提供的UI组件,快速实现美颜功能,适合快速开发。

无论选择哪种方式,都需要正确配置项目依赖、权限和资源文件,并遵循SDK的生命周期管理规范。通过合理的性能优化,可以在保证美颜效果的同时提供流畅的用户体验。

相关推荐
斯~内克3 分钟前
基于Vue.js和PDF-Lib的条形码生成与批量打印方案
前端·vue.js·pdf
阴阳怪气乌托邦4 分钟前
别再啃OA代码了!低代码"搭积木"式搞数智化,我直接少写500行
前端·低代码
beelan8 分钟前
v-on的思考
前端
山河木马11 分钟前
前端学习C++之:.h(.hpp)与.cpp文件
前端·javascript·c++
用户92724725021911 分钟前
PHP + CSS + JS + JSON 数据采集与展示系统,支持伪静态
前端
努力只为躺平15 分钟前
一文搞懂 Promise 并发控制:批量执行 vs 最大并发数,实用场景全解析!
前端·javascript
李大玄18 分钟前
Google浏览器拓展工具 "GU"->google Utils
前端·javascript·github
爱编程的喵18 分钟前
从DOM0到事件委托:揭秘JavaScript事件机制的性能密码
前端·javascript·dom
蓝倾23 分钟前
京东批量获取商品SKU操作指南
前端·后端·api
JSLove30 分钟前
常见 npm 报错问题
前端·npm