基于 react-native-create-thumbnail 的 OpenHarmony 适配版,从视频生成缩略图封面
Access rate limit exceeded. Please log in to continue.
Document Template: v0.4.2
react-native-create-thumbnail
This project is based on react-native-create-thumbnail.
This third-party library has been migrated to GitCode and is now available for direct download from npm. The new package name is: @react-native-ohos/react-native-create-thumbnail. The version correspondence details are as follows:
| Name | Version(Npm Address) | Release Information | Supported RN Version | Supported Autolink | Compile API Version | Community Baseline Version | Source code address |
|---|---|---|---|---|---|---|---|
| @react-native-ohos/react-native-create-thumbnail | ~2.2.0 (In development) | GitCode Releases | 0.82.* | Yes | API12+ | 2.0.1 | master |
| @react-native-ohos/react-native-create-thumbnail | ~2.1.0 | GitCode Releases | 0.77.* | No | API12+ | 2.0.1 | br_rnoh0.77 |
| @react-native-ohos/react-native-create-thumbnail | ~2.0.1 | GitCode Releases | 0.72.* | Yes | API12+ | 2.0.0 | br_rnoh0.72 |
| @react-native-oh-tpl/react-native-create-thumbnail | <= 2.0.0-0.0.4@deprecated | GitHub Releases(deprecated) | 0.72.* | No | API12+ | 2.0.0 | sig |
Introduction
React Native video thumbnail generation library.
Implemented with HarmonyOS media capabilities, supporting both local and remote video files, with storage/cache management.
Installation
Go to the project directory and execute the following instruction:
npm
npm install react-native-create-thumbnail@2.0.1
npm install @react-native-ohos/react-native-create-thumbnail
yarn
yarn add react-native-create-thumbnail@2.0.1
yarn add @react-native-ohos/react-native-create-thumbnail
Link
| Version | Supported Autolink | Supported RN Version |
|---|---|---|
| ~2.2.0 | Yes | 0.82.* |
Projects using AutoLink need to be configured according to this document. AutoLink framework guide: https://gitcode.com/CPF-RN/ohos_react_native/blob/main/docs/en/02-development/02-development-guide/autolinking.md
If the version you are using supports Autolink and the project has integrated Autolink, you can skip the ManualLink configuration.
ManualLink: This step provides guidance for manually configuring native dependencies.
Open the harmony directory of the HarmonyOS project in DevEco Studio.
1. Overrides RN SDK
To ensure the project relies on the same version of the RN SDK, add an overrides field in the project's root oh-package.json5 file, specifying the RN SDK version to be used. The replacement version can be a specific version number, a semver range, or a locally available HAR package or source directory.
For more information about this field, see the official documentation.
{
"overrides": {
"@rnoh/react-native-openharmony": "~0.82.18" // ohpm version
// "@rnoh/react-native-openharmony" : "./react_native_openharmony.har" // a locally available HAR package
// "@rnoh/react-native-openharmony" : "./react_native_openharmony" // source code directory
}
}
2. Introducing Native Code
Currently, two methods are available:
- Use the HAR file;
- Directly link to the source code.
Method 1 (recommended): Use the HAR file.
The HAR file is stored in the `harmony` directory in the installation path of the third-party library.
Open entry/oh-package.json5 and add the following dependency:
"dependencies": {
"@react-native-ohos/react-native-create-thumbnail": "file:../../node_modules/@react-native-ohos/react-native-create-thumbnail/harmony/createThumbnail.har"
}
Click the sync button in the upper right corner.
Alternatively, run the following command on the terminal:
cd entry
ohpm install
Method 2: Directly link to the source code.
For details, see [Directly Linking Source Code](https://gitcode.com/CPF-RN/usage-docs/blob/master/en/link-source-code.md).
3. Configuring CMakeLists and Introducing CreateThumbnailPackage
Open entry/src/main/cpp/CMakeLists.txt and add:
project(rnapp)
cmake_minimum_required(VERSION 3.4.1)
set(CMAKE_SKIP_BUILD_RPATH TRUE)
set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
set(NODE_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../node_modules")
+ set(OH_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
set(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../react-native-harmony/harmony/cpp")
set(LOG_VERBOSITY_LEVEL 1)
set(CMAKE_ASM_FLAGS "-Wno-error=unused-command-line-argument -Qunused-arguments")
set(CMAKE_CXX_FLAGS "-fstack-protector-strong -Wl,-z,relro,-z,now,-z,noexecstack -s -fPIE -pie")
set(WITH_HITRACE_SYSTRACE 1) # for other CMakeLists.txt files to use
add_compile_definitions(WITH_HITRACE_SYSTRACE)
add_subdirectory("${RNOH_CPP_DIR}" ./rn)
# RNOH_BEGIN: manual_package_linking_1
add_subdirectory("../../../../sample_package/src/main/cpp" ./sample-package)
+ add_subdirectory("${OH_MODULES}/@react-native-ohos/react-native-create-thumbnail/src/main/cpp" ./create-thumbnail)
# RNOH_END: manual_package_linking_1
file(GLOB GENERATED_CPP_FILES "./generated/*.cpp")
add_library(rnoh_app SHARED
${GENERATED_CPP_FILES}
"./PackageProvider.cpp"
"${RNOH_CPP_DIR}/RNOHAppNapiBridge.cpp"
)
target_link_libraries(rnoh_app PUBLIC rnoh)
# RNOH_BEGIN: manual_package_linking_2
target_link_libraries(rnoh_app PUBLIC rnoh_sample_package)
+ target_link_libraries(rnoh_app PUBLIC rnoh_create_thumbnail)
# RNOH_END: manual_package_linking_2
Open entry/src/main/cpp/PackageProvider.cpp and add:
#include "RNOH/PackageProvider.h"
#include "SamplePackage.h"
+ #include "CreateThumbnailPackage.h"
using namespace rnoh;
std::vector<std::shared_ptr<Package>> PackageProvider::getPackages(Package::Context ctx) {
return {
std::make_shared<SamplePackage>(ctx),
+ std::make_shared<CreateThumbnailPackage>(ctx)
};
}
4. Introducing CreateThumbnailPackage to ArkTS
Open entry/src/main/ets/RNPackagesFactory.ts and add:
...
+ import { CreateThumbnailPackage } from '@react-native-ohos/react-native-create-thumbnail/ts';
export function createRNPackages(ctx: RNPackageContext): RNPackage[] {
return [
+ new CreateThumbnailPackage(ctx)
];
}
Running
Click the sync button in the upper right corner.
Alternatively, run the following command on the terminal:
cd entry
ohpm install
Then build and run the project.
Constraints
Compatibility
The content of this document has been verified based on the following versions:
- RNOH: 0.82.7; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.0.858; ROM: 6.0.0.112 SP12;
Permission Requirements
-
If you generate thumbnails from a network URL, the app needs the Internet permission.
Add the following to
entry/src/main/module.json5:
requestPermissions: [
{
name: "ohos.permission.INTERNET",
},
],
Usage Example
The following code shows a basic usage scenario:
The imported library name remains unchanged.
import React, {useState } from 'react';
import { StyleSheet, Text, Button, ScrollView, View } from 'react-native';
import { createThumbnail } from 'react-native-create-thumbnail';
export default function CreateThumbnailDemo() {
const [text, setText] = useState('');
const CreateThumbnail = async()=> {
try {
let obj = await createThumbnail({
url:'https://media.w3.org/2010/05/sintel/trailer.mp4',
timeStamp: 10000
});
setText(JSON.stringify(obj))
} catch (error) {
console.error('Create thumbnail failed:', error);
setText('Error: ' + error.message);
}
}
return (
<View style={styles.container}>
<View style={styles.titleArea}>
<Text style={styles.title}>Create Thumbnail Demo</Text>
</View>
<View style={styles.inputArea}>
<Text style={styles.baseText}>{text}</Text>
</View>
<ScrollView style={styles.scrollView}>
<View style={{ flexDirection: 'column' }}>
<View style={styles.baseArea}>
<Text style={{flex:1}}>createThumbnail</Text>
<Button title='Run' color='#841584' onPress={CreateThumbnail}></Button>
</View>
</View>
</ScrollView>
</View>
);
}
const styles = StyleSheet.create({
container: {
width: '100%',
height: '100%',
flexDirection: 'column',
alignItems: 'center',
backgroundColor: '#F1F3F5',
},
baseText: {
fontWeight: 'bold',
textAlign:'center',
fontSize:16
},
titleArea:{
width:'90%',
height:'8%',
alignItems:'center',
flexDirection:'row',
},
title: {
width:'90%',
color:'#000000',
textAlign:'left',
fontSize: 30,
},
scrollView: {
width:'90%',
marginHorizontal: 20,
},
inputArea: {
width:'90%',
height:'30%',
borderWidth:2,
borderColor:'#000000',
marginTop:8,
justifyContent:'center',
alignItems:'center',
},
baseArea: {
width:'100%',
height:60,
borderRadius:4,
borderColor:'#000000',
marginTop:8,
backgroundColor:'#FFFFFF',
flexDirection: 'row',
alignItems:'center',
paddingLeft:8,
paddingRight:8
}
});
How to Use
Generate Thumbnail
import { createThumbnail } from 'react-native-create-thumbnail';
// Generate thumbnail from remote video
try {
const thumbnail = await createThumbnail({
url: 'https://example.com/video.mp4',
timeStamp: 10000, // 10th second
format: 'jpeg',
dirSize: 100, // Cache directory max 100MB
});
console.log(thumbnail.path); // Thumbnail path
console.log(thumbnail.width); // Thumbnail width
console.log(thumbnail.height); // Thumbnail height
} catch (error) {
console.error('Create thumbnail failed:', error);
}
Use cache to avoid duplicate generation
try {
const thumbnail = await createThumbnail({
url: 'https://example.com/video.mp4',
timeStamp: 5000,
cacheName: 'my-thumbnail-cache', // Specify cache name
});
} catch (error) {
console.error('Create thumbnail failed:', error);
}
Add request headers
try {
const thumbnail = await createThumbnail({
url: 'https://example.com/video.mp4',
timeStamp: 10000,
headers: {
Authorization: 'Bearer token123'
}
});
} catch (error) {
console.error('Create thumbnail failed:', error);
}
Available APIs
The **Platform** column indicates the platforms supported by the original third-party library.
If **OpenHarmony Platform Support** is **yes**, the OpenHarmony platform supports this property; **no** means not supported; **partially** means partially supported. Usage is consistent across platforms, and the effect aligns with iOS or Android.
API
| Name | Type | Parameter Type | Return Value | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|---|
| createThumbnail | function | Config | Promise | No | iOS, Android | yes | Generate video thumbnail |
Parameters
| Name | Type | Required | Default | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|
| url | string | yes | — | iOS, Android | yes | Path to video file (local or remote) |
| timeStamp | number | no | 0 | iOS, Android | yes | Thumbnail timestamp (in milliseconds) |
| format | "jpeg" | "png" | no | "jpeg" | iOS, Android | yes | Thumbnail format |
| dirSize | number | no | 100 | iOS, Android | yes | Maximum cache directory size (MB) |
| headers | object | no | — | iOS, Android | yes | Headers to load the video with |
| cacheName | string | no | — | iOS, Android | yes | Cache name for the thumbnail |
| maxWidth | number | no | 512 | iOS, Android | yes | Maximum thumbnail width (pixels) |
| maxHeight | number | no | 512 | iOS, Android | yes | Maximum thumbnail height (pixels) |
| timeToleranceMs | number | no | — | iOS | no | Time tolerance (in milliseconds) |
| onlySyncedFrames | boolean | no | true | Android | yes | Whether to use only sync frames |
Return Value
| Name | Type | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|
| path | string | no | iOS, Android | yes | Path to generated thumbnail |
| size | number | no | iOS, Android | yes | Thumbnail size (in bytes) |
| mime | string | no | iOS, Android | yes | Thumbnail MIME type |
| width | number | no | iOS, Android | yes | Thumbnail width |
| height | number | no | iOS, Android | yes | Thumbnail height |
| timeStamp | number | no | — | yes | Thumbnail timestamp (in milliseconds) |
| onlySyncedFrames | boolean | no | — | yes | Whether to use only sync frames |
| headers | object | no | — | yes | Headers to load the video with |
| dirSize | number | no | — | yes | Maximum cache directory size (MB) |
Known Issues
- timeToleranceMs property is not supported because there is no corresponding property in HarmonyOS issues#1
Other
None
Directory Structure
/rntpc_react-native-create-thumbnail # Project root directory
├── harmony # HarmonyOS adaptation code
│ ├── createThumbnail.har # HAR package
│ └── createThumbnail # Core adaptation code
│ ├── Index.ets # Adaptation code entry
│ ├── ts.ets # TurboModule ArkTS declaration entry
│ └── src/main
│ ├── cpp # C++ adaptation code
│ ├── ets # ArkTS adaptation code (including codegen-generated code)
│ └── module.json5 # Module configuration
├── src # React Native code
│ └── NativeCreateThumbnail.ts # TurboModule Spec definition
├── example # Example project
├── index.js # Entry file
├── index.d.ts # Type definitions
├── README.md # Chinese installation and usage guide
├── README_en.md # English installation and usage guide
└── package.json # Package configuration
How to Contribute
If you find any issues during usage, feel free to submit an Issue. Pull requests are also welcome: PR.
License
This project is licensed under The MIT License (MIT).