rntpc_react-native-create-thumbnail:

Branch11Tags1
FilesLast commitLast update
4 months ago
3 months ago
6 years ago
1 year ago
6 years ago
6 years ago
6 years ago
3 months ago
1 year ago
6 years ago
1 year ago
3 months ago
3 months ago
3 months ago
1 year ago
1 year ago
1 year ago
3 months ago
5 years ago
1 year ago

Document template: v0.4.1

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 Release Information Supported RN Version Supported Autolink Compile API Version Community Baseline Version npm Address
@react-native-ohos/react-native-create-thumbnail ~ 2.2.0 (In development) Gitcode Releases 0.82.* Yes API12+ 2.2.0 Npm Address
@react-native-ohos/react-native-create-thumbnail ~ 2.1.0 Gitcode Releases 0.77.* No API12+ 2.0.1 Npm Address
@react-native-ohos/react-native-create-thumbnail ~ 2.0.1 Gitcode Releases 0.72.* Yes API12+ 2.0.0 Npm Address
@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 Npm Address

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 run:

npm

npm install @react-native-ohos/react-native-create-thumbnail

yarn

yarn add @react-native-ohos/react-native-create-thumbnail
Supported Autolink Supported RN Version
~ 2.2.0 Yes 0.82
~ 2.1.0 No 0.77
~ 2.0.1 Yes 0.72
<= 2.0.0-0.0.4@deprecated No 0.72

Projects using AutoLink need to be configured according to this document. AutoLink framework guide: https://gitcode.com/openharmony-sig/ohos_react_native/blob/master/docs/zh-cn/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.77.73" // 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:

  1. RNOH: 0.82.7; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.0.858; ROM: 6.0.0.112 SP12;
  2. RNOH: 0.72.96; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.0.858; ROM: 6.0.0.112;
  3. RNOH: 0.72.33; SDK: HarmonyOS NEXT B1; IDE: DevEco Studio: 5.0.3.900; ROM: Next.0.0.71;
  4. RNOH: 0.77.73; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.0.858; ROM: 6.0.0.112;

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
  }
});

Usage Guide

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);
}

API Reference

The **Platform** column indicates the platforms supported by the original third-party library.

If **OpenHarmony Support** is **yes**, the OpenHarmony platform supports this API; **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 Support Description
createThumbnail function Config Promise No iOS、Android yes Generate video thumbnail

Parameters

Name Type Required Default Platform OpenHarmony 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
maxWidth2.0.2+ number no 512 iOS、Android yes Maximum thumbnail width (pixels)
maxHeight2.0.2+ number no 512 iOS、Android yes Maximum thumbnail height (pixels)
timeToleranceMs2.0.2+ number no — iOS no Time tolerance (in milliseconds)
onlySyncedFrames2.0.2+ boolean no — Android yes Whether to use only sync frames

Return Value

Name Type Required Platform OpenHarmony 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 iOS、Android yes Thumbnail timestamp (in milliseconds) 🆕
onlySyncedFrames boolean no Android yes Whether to use only sync frames 🆕
headers object no iOS、Android yes Headers to load the video with 🆕
dirSize number no iOS、Android yes Maximum cache directory size (MB) 🆕

Known Issues

Others

None

Directory Structure

/rntp_react-native-create-thumbnail
├── harmony                # adaptation code
│    ├─ createThumbnail.har # HAR package
│    └─ createThumbnail      # Core adaptation code
│          ├─ Index.ets      # Adaptation entry
│          └─ src
│              ├─ main
│              │    ├─ cpp
│              │    │    ├─ CMakeLists.txt
│              │    │    ├─ CreateThumbnail.cpp
│              │    │    ├─ CreateThumbnail.h
│              │    │    └─ CreateThumbnailPackage.h
│              │    └─ ets
│              │         ├─ CreateThumbnailPackage.ets   # Package registration
│              │         ├─ CreateThumbnailTurboModule.ts  # TurboModule implementation
│              │         ├─ download/RequestDownload.ts  # Download module
│              │         └─ util
│              │              ├─ FileUtil.ts
│              │              └─ StringUtil.ts
│              └─ ohosTest   # Test code
├── src
│    ├─ index.js           # Entry file
│    ├─ index.d.ts         # Type definitions
│    └─ NativeCreateThumbnail.ts  # TurboModule Spec
├── example                # Example project
├── README.md              # Chinese installation and usage guide
├── README_en.md           # English installation and usage guide
└─ package.json            # Package configuration

Contributing

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

Introduction

No description

Customize your domain