react-native-image-crop-picker(react-native 圖片選擇)

好記性不如爛筆頭,今天把 react-native-image-crop-picker 總結(jié)下。廢話不多說,開始。

1.執(zhí)行下面命令行:
npm i react-native-image-crop-picker --save

react-native link react-native-image-crop-picker

安卓配置

1.在android/build.gradle添加以下代碼
allprojects {
    repositories {
      mavenLocal()
      jcenter()
      maven { url "$rootDir/../node_modules/react-native/android" }

     //我是要添加的...
      maven { url "https://jitpack.io" }
    }
}

2.在android/app/build.gradle添加以下代碼
android {
    ...

    defaultConfig {
        //我是要添加的....
        vectorDrawables.useSupportLibrary = true
        ...
    }
    ...
}

3.在android/app/src/main/AndroidManifest.xml添加以下代碼
<uses-permission android:name="android.permission.CAMERA"/>

Ios配置

1.在info.plist內(nèi)添加以下內(nèi)容
Privacy - Photo Library Usage Description
Privacy - Camera Usage Description

image
2.在target添加以下內(nèi)容General添加以下內(nèi)容
image

完整代碼借用一下官方的

import React, {Component} from 'react';
import {
  View, Text, StyleSheet, ScrollView, Alert,
  Image, TouchableOpacity, NativeModules, Dimensions
} from 'react-native';

import Video from 'react-native-video';

var ImagePicker = NativeModules.ImageCropPicker;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  button: {
    backgroundColor: 'blue',
    marginBottom: 10
  },
  text: {
    color: 'white',
    fontSize: 20,
    textAlign: 'center'
  }
});

export default class App extends Component {

  constructor() {
    super();
    this.state = {
      image: null,
      images: null
    };
  }

  pickSingleWithCamera(cropping) {
    ImagePicker.openCamera({
      cropping: cropping,
      width: 500,
      height: 500,
      includeExif: true,
    }).then(image => {
      console.log('received image', image);
      this.setState({
        image: {uri: image.path, width: image.width, height: image.height},
        images: null
      });
    }).catch(e => alert(e));
  }

  pickSingleBase64(cropit) {
    ImagePicker.openPicker({
      width: 300,
      height: 300,
      cropping: cropit,
      includeBase64: true,
      includeExif: true,
    }).then(image => {
      console.log('received base64 image');
      this.setState({
        image: {uri: `data:${image.mime};base64,`+ image.data, width: image.width, height: image.height},
        images: null
      });
    }).catch(e => alert(e));
  }

  cleanupImages() {
    ImagePicker.clean().then(() => {
      console.log('removed tmp images from tmp directory');
    }).catch(e => {
      alert(e);
    });
  }

  cleanupSingleImage() {
    let image = this.state.image || (this.state.images && this.state.images.length ? this.state.images[0] : null);
    console.log('will cleanup image', image);

    ImagePicker.cleanSingle(image ? image.uri : null).then(() => {
      console.log(`removed tmp image ${image.uri} from tmp directory`);
    }).catch(e => {
      alert(e);
    })
  }

  cropLast() {
    if (!this.state.image) {
      return Alert.alert('No image', 'Before open cropping only, please select image');
    }

    ImagePicker.openCropper({
      path: this.state.image.uri,
      width: 200,
      height: 200
    }).then(image => {
      console.log('received cropped image', image);
      this.setState({
        image: {uri: image.path, width: image.width, height: image.height, mime: image.mime},
        images: null
      });
    }).catch(e => {
      console.log(e);
      Alert.alert(e.message ? e.message : e);
    });
  }

  pickSingle(cropit, circular=false) {
    ImagePicker.openPicker({
      width: 300,
      height: 300,
      cropping: cropit,
      cropperCircleOverlay: circular,
      compressImageMaxWidth: 640,
      compressImageMaxHeight: 480,
      compressImageQuality: 0.5,
      compressVideoPreset: 'MediumQuality',
      includeExif: true,
    }).then(image => {
      console.log('received image', image);
      this.setState({
        image: {uri: image.path, width: image.width, height: image.height, mime: image.mime},
        images: null
      });
    }).catch(e => {
      console.log(e);
      Alert.alert(e.message ? e.message : e);
    });
  }

  pickMultiple() {
    ImagePicker.openPicker({
      multiple: true,
      waitAnimationEnd: false,
      includeExif: true,
    }).then(images => {
      this.setState({
        image: null,
        images: images.map(i => {
          console.log('received image', i);
          return {uri: i.path, width: i.width, height: i.height, mime: i.mime};
        })
      });
    }).catch(e => alert(e));
  }

  scaledHeight(oldW, oldH, newW) {
    return (oldH / oldW) * newW;
  }

  renderVideo(video) {
    return (<View style={{height: 300, width: 300}}>
      <Video source={{uri: video.uri, type: video.mime}}
         style={{position: 'absolute',
            top: 0,
            left: 0,
            bottom: 0,
            right: 0
          }}
         rate={1}
         paused={false}
         volume={1}
         muted={false}
         resizeMode={'cover'}
         onError={e => console.log(e)}
         onLoad={load => console.log(load)}
         repeat={true} />
     </View>);
  }

  renderImage(image) {
    return <Image style={{width: 300, height: 300, resizeMode: 'contain'}} source={image} />
  }

  renderAsset(image) {
    if (image.mime && image.mime.toLowerCase().indexOf('video/') !== -1) {
      return this.renderVideo(image);
    }

    return this.renderImage(image);
  }

  render() {
    return (<View style={styles.container}>
      <ScrollView>
        {this.state.image ? this.renderAsset(this.state.image) : null}
        {this.state.images ? this.state.images.map(i => <View key={i.uri}>{this.renderAsset(i)}</View>) : null}
      </ScrollView>

      <TouchableOpacity onPress={() => this.pickSingleWithCamera(false)} style={styles.button}>
        <Text style={styles.text}>Select Single With Camera</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={() => this.pickSingleWithCamera(true)} style={styles.button}>
        <Text style={styles.text}>Select Single With Camera With Cropping</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={() => this.pickSingle(false)} style={styles.button}>
        <Text style={styles.text}>Select Single</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={() => this.cropLast()} style={styles.button}>
        <Text style={styles.text}>Crop Last Selected Image</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={() => this.pickSingleBase64(false)} style={styles.button}>
        <Text style={styles.text}>Select Single Returning Base64</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={() => this.pickSingle(true)} style={styles.button}>
        <Text style={styles.text}>Select Single With Cropping</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={() => this.pickSingle(true, true)} style={styles.button}>
        <Text style={styles.text}>Select Single With Circular Cropping</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={this.pickMultiple.bind(this)} style={styles.button}>
        <Text style={styles.text}>Select Multiple</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={this.cleanupImages.bind(this)} style={styles.button}>
        <Text style={styles.text}>Cleanup All Images</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={this.cleanupSingleImage.bind(this)} style={styles.button}>
        <Text style={styles.text}>Cleanup Single Image</Text>
      </TouchableOpacity>
    </View>);
  }
}

屬性:
參數(shù) 類型 描述
cropping bool (default false) 是否打開裁剪
width number 與cropping=true一起使用的,裁剪后的寬度
height number 與cropping=true一起使用的,裁剪后的高度
multiple bool (default false) 啟用或禁用多個(gè)圖像選擇
includeBase64 bool (default false) 啟用或禁用使用圖像返回base64數(shù)據(jù)
cropperActiveWidgetColor (android only) string (default "#424242") 裁剪圖像時(shí),確定工具欄和其他UX元素的顏色。
cropperStatusBarColor (android only) string (default "#424242") 裁剪圖像時(shí),決定狀態(tài)欄StatusBar顏色。
cropperToolbarColor (android only) string (default #424242) 裁剪圖像時(shí),決定狀態(tài)欄Toolbar顏色.
cropperCircleOverlay bool (default false) 裁剪圖像時(shí)候,是否打開圓形裁剪覆蓋(注:我的理解是圓形裁剪框)
maxFiles (ios only) number (default 5) 最多能夠選取的文件數(shù),配合multiple=true
waitAnimationEnd (ios only) bool (default true) Promise will resolve/reject once ViewController completion block is called
compressVideo (ios only) bool (default true) 選擇視頻時(shí),壓縮它并將其轉(zhuǎn)換為mp4
smartAlbums (ios only) array (default ['UserLibrary', 'PhotoStream', 'Panoramas', 'Videos', 'Bursts']) (列出可供選擇的智能相冊)List of smart albums to choose from
useFrontCamera (ios only) bool (default false) 相機(jī)打開時(shí)是否定義文字字體
compressVideoPreset (ios only) string (default MediumQuality) 選擇預(yù)設(shè)一個(gè)視頻壓縮度
compressImageMaxWidth number (default none) 壓縮圖像最大寬度
compressImageMaxHeight number (default none) 壓縮圖像最大高度
compressImageQuality number (default 1) 壓縮圖片的質(zhì)量(從0到1,1是最大質(zhì)量)
loadingLabelText (ios only) string (default "Processing assets...") 圖片加載時(shí)候文字顯示
mediaType string (default any) 選擇一個(gè)媒體類型 photo/video/any/
showsSelectedCount (ios only) bool (default true) 是否顯示選中圖片的數(shù)量
showCropGuidelines (android only) bool (default true) 裁剪過程中是否顯示3x3的網(wǎng)格線
hideBottomControls (android only) bool (default false) 是否展示底部控件
enableRotationGesture (android only) bool (default false) 是否可以通過手勢來旋轉(zhuǎn)圖像。
返回值:
參數(shù) 類型 描述
path string 選中文件的位置
width number 選中文件的寬度
height number 選中文件的高度
mime string 選中圖片的MIME類型(image/jpeg, image/png)
size number 所選圖像大?。ㄒ宰止?jié)為單位)
data base64 (選擇文件以base64表示)Optional base64 selected file representation

問題:1.

image

解決方案:
在android/build.gradle添加以下代碼:

image
 maven { url "https://jitpack.io" }

親測沒有問題,覺得有用的小伙伴點(diǎn)個(gè)小紅心就行??,么么噠。

友情提示:在開發(fā)中有遇到RN相關(guān)的技術(shù)問題,歡迎小伙伴加入交流群(620792950),在群里提問、互相交流學(xué)習(xí)。交流群也定期更新最新的RN學(xué)習(xí)資料給大家,謝謝大家支持

作者:妄自
鏈接:http://www.itdecent.cn/p/71dee6198b56
來源:簡書
簡書著作權(quán)歸作者所有,任何形式的轉(zhuǎn)載都請聯(lián)系作者獲得授權(quán)并注明出處。

本文僅為方便自己學(xué)習(xí)使用,如有轉(zhuǎn)載請注明原作者

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容