React-Native multi-image selection supports crop compression

react-native-syan-image-picker

Features

Multi-image selection component encapsulated based on the existing native third-party framework, suitable for React Native App.

Native framework dependency

Features

  • Support both iOS and Android
  • Support single selection, multiple selection
  • Customizable crop area size, support circular crop
  • Compression quality can be set
  • Can set whether to return image base64 encoding
  • Support recording the currently selected picture
  • Support deleting pictures with specified subscripts

Live

Install and use

installation

// Step 1 基于 npm
npm install react-native-syan-image-picker --save

// 或是 yarn
yarn add react-native-syan-image-picker

// Step 2 执行 link
react-native link react-native-syan-image-picker

Other configuration

iOS
1, add the desired native framework bundledocument:
  • TARGETS -> Build Phases -> Copy Bundle Resources Click the “+” button, click the “Add Other” button in the pop-up window, select
node_modules/react-native-syan-image-picker/ios/TZImagePickerController/TZImagePickerController.bundle
2. Add album related permissions:
  • Project Directory->Info.plist->Add
 Privacy - Camera Usage Description 是否允许此App使用你的相机进行拍照?
 Privacy - Photo Library Usage Description 请允许访问相册以选取照片
 Privacy - Photo Library Additions Usage Description 请允许访问相册以选取照片
 Privacy - Location When In Use Usage Description 我们需要通过您的地理位置信息获取您周边的相关数据
3. Chinese adaptation:
  • Add Chinese PROJECT -> Info -> Localizations Click the “+” button, select Chinese(Simplified)
Android
1, AndroidManifest.xmladding permissions:
<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" />
2. To update to PictureSelector, you need to modify the minSdkVersion:
// app/build.gradle

android {
    minSdkVersion =  19 
    .. .
}
3. Dynamically obtain permissions before taking pictures
requestPermission  =  async  ( )  =>  { 
        try  { 
            const  granted  =  await  PermissionsAndroid . request ( 
                PermissionsAndroid . PERMISSIONS . WRITE_EXTERNAL_STORAGE , 
                { 
                    title : 'Apply for read and write mobile phone storage permissions' , 
                    message :
                         'A very awesome application wants to borrow your camera , '  + 
                        ' Then you can make cool soap tablets .' , 
                    buttonNeutral : 'Ask me again later ' , 
                    buttonNegative : 'No' , 
                    buttonPositive :'OK' , 
                } , 
            ) ; 
            if  ( granted  ===  PermissionsAndroid . RESULTS . GRANTED )  { 
                console . Log ( 'Now you have the camera permission' ) ; 
            }  else  { 
                console . Log ( 'Users didn't give it to you' ) ; 
            } 
        }  catch  ( err )  { 
            console . warn ( err ) ; 
        } 
    } ;
4. To use fast-image at the same time, you need to use the glide version

Add glideVersion to specify the same version as fast-image in build.gradle’s buildscript and ext. Add pictureVersion to customize picture_library version

Pay attention to the installation and operation error

  1. Check whether the automatic link is successful
  2. Use Android Studio to see MainApplication.javaif the file is addednew RNSyanImagePickerPackage()
  3. Use Android Studio to open the project to check whether Gradle is synchronized
  4. You can run the ImagePickerExample demo, test Android 7.0, 6.0 and take pictures and select pictures are normal

link failed to add manually

iOS

  1. In XCode, in the project navigator, right click Libraries ➜ Add Files to [your project's name]
  2. Go to node_modules ➜ react-native-syan-image-picker and add RNSyanImagePicker.xcodeproj
  3. In XCode, in the project navigator, select your project. Add libRNSyanImagePicker.a to your project’s Build Phases ➜ Link Binary With Libraries
  4. Run your project (Cmd+R)<

Android

  1. Open up android/app/src/main/java/[...]/MainApplication.java
  • Add import com.reactlibrary.RNSyanImagePickerPackage; to the imports at the top of the file
  • Add new RNSyanImagePickerPackage() to the list returned by the getPackages() method
  1. Append the following lines to android/settings.gradle:
include ':react-native-syan-image-picker'
project(':react-native-syan-image-picker').projectDir = new File(rootProject.projectDir, 	'../node_modules/react-native-syan-image-picker/android')
  1. Insert the following lines inside the dependencies block in android/app/build.gradle:
  compile project(':react-native-syan-image-picker')

Run example

For related Demo, see ImagePickerExample .

Configuration parameter description

When component calls, a support incoming optionsobjects, properties that can be set as follows:

Property name Type Optional Default value Description
imageCount int Yes 6 Maximum number of selected images
isRecordSelected bool Yes false Record the currently selected picture
isCamera bool Yes true Whether to allow users to take pictures inside
isCrop bool Yes false Whether to allow cropping, imageCount is 1 to take effect
CropW int Yes screenW * 0.6 Crop width, the default screen width is 60%
CropH int Yes screenW * 0.6 Cropping height, default screen width 60%
isGif bool Yes false Whether to allow GIF selection, no callback GIF data yet
showCropCircle bool Yes false Whether to show circular cropping area
circleCropRadius float Yes screenW * 0.5 Circular cropping radius, the default screen width is half
showCropFrame bool Yes true Whether to display the cropped area
showCropGrid bool Yes false Whether to hide the crop area grid
quality int Yes 90 Compression quality (Android invalid, fixed Luban compression)
minimumCompressSize int Yes 100 Pictures smaller than 100kb are not compressed (Android)
enableBase64 bool Yes false Whether to return base64 encoding, default does not return
freeStyleCropEnabled bool Yes false Whether the crop box can be dragged (Android)
rotateEnabled bool Yes true Whether the crop can rotate the picture (Android)
scaleEnabled bool Yes true Whether the crop can zoom in or out the picture (Android)
showSelectedIndex bool Yes false Whether to display the serial number

Return result description

At Callbackthe time in the form of calls, the first parameter is returned as error object, and the second is an array of pictures:

Attribute nameTypes ofdescriptionerrorobjectIt is not null when canceling the photo, at this time error.message=='Cancel’photosarraySelected image array

And at Promisethe time in the form of calls, simply return an array of pictures, in catchthe case of cancellation chosen to deal with.

The following are the attributes contained in each image object:

Attribute nameTypes ofdescriptionwidthintPicture widthheightintPicture heighthatestringPicture pathoriginal_uristringOriginal image path, Android onlytypestringFile type, only Android, currently only returns imagesizeintPicture size, in bytes bbase64stringBase64-encoded picture, if enableBase64set false, this property does not return

Method call

Callback

Callback form to be called showImagePickermethod:

import SyanImagePicker from 'react-native-syan-image-picker';

SyanImagePicker . ShowImagePicker ( options ,  ( err ,  selectedPhotos )  =>  { 
  if  ( err )  { 
    // Deselect 
    return ; 
  } 
  // The selection is successful and the picture is rendered 
  // ... 
} )

Promise

Non-use form callback asyncShowImagePickermethod:

import SyanImagePicker from 'react-native-syan-image-picker';

// promise-then 
SYImagePicker . asyncShowImagePicker ( options ) 
  . then ( photos  =>  { 
    // Selection is successful 
  } ) 
  . catch ( err  =>  { 
    // Cancel selection, err.message is "Cancel" 
  } )

// async/await 
handleSelectPhoto  =  async  ( )  =>  { 
  try  { 
    const  photos  =  await  SYImagePicker . asyncShowImagePicker ( options ) ; 
    // selection is successful 
  }  catch  ( err )  { 
    // Cancel the selection, err.message is "Cancel" 
  } 
}

Remove selected picture

After React Native page to remove the selected images to be invoked removePhotoAtIndexmethod to delete a saved array of original pictures, make sure that the next time you enter the picture selection, selected the picture is consistent:

handleDeletePhoto  =  index  =>  { 
  const  {  selectedPhotos : oldPhotos  }  =  this . state ; 
  const  selectedPhotos  =  oldPhotos . filter ( ( photo ,  photoIndex )  =>  photoIndex !== index ) ; 
  // Update the original picture array 
  SYImagePicker . removePhotoAtIndex ( index ) ; 
  // Update the RN page 
  this . SetState ( { selectedPhotos });
}

Remove all selected pictures

STImagePicke.removeAllPhoto()

Call camera

The camera function call method also supports the two forms of Callback and Promise, and the result parameters are also consistent.

 //Callback method 
SyanImagePicker . OpenCamera ( options ,  ( err ,  photos )  =>  { 
  if  ( err )  { 
    // deselect 
    return ; 
  } 
  // the selection is successful, the picture is rendered 
  // ... 
} )

//Promise方式
 SYImagePicker.asyncOpenCamera(options)
 .then(()=>{
   ...
 })
 .catch(()=>{
   ...
 })

Select video

SyanImagePicker . OpenVideoPicker ( options ,  ( err ,  videos )  =>  { 
  if  ( err )  { 
    // Deselect 
    return ; 
  } 
  // The selection is successful and the video is processed 
  //... 
} )

options Optional configuration:

{
  MaxSecond: 60,
  MinSecond: 0,
  recordVideoSecond: 60,
  videoCount: 1
}

Return result:

type value iOS Android
uri string
fileName string
size string
duration number
width number
height number
type string
mime string
coverUri string
favorite string
mediaType string
Android return result:
{
  mime: "video/mp4",
  type: "video",
  height: 1080,
  width: 1920,
  duration: 30.22,
  size: 63876724,
  fileName: "VID_20200409_11492864.mp4",
  uri: "file:///storage/emulated/0/DCIM/Camera/VID_20200409_11492864.mp4",
  coverUri: "file:///storage/emulated/0/Android/data/package_id/cache/thumb-c3c99b6a.jpg"
}

Note: uri contains the protocol “file://”

Delete cache

SYImagePicker.deleteCache();

Version record

  • 0.4.10 Added the showSelectedIndex parameter, whether to display the selected serial number

help

Join the React-Native QQ group 397885169

Download Details:

Author: syanbo

Source Code: https://github.com/syanbo/react-native-syan-image-picker

#react-native #react #mobile-apps

React-Native multi-image selection supports crop compression
5.90 GEEK