ImagePicker.tsx 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /* eslint-disable no-underscore-dangle */
  2. import * as React from 'react';
  3. import { Platform, View } from 'react-native';
  4. import { Button, Icon, Image, Div } from 'react-native-magnus';
  5. import * as ImagePicker from 'expo-image-picker';
  6. import useModel from 'flooks';
  7. import request from '../utils/RequestUtils';
  8. import { toastShow, toastHide } from '../utils/SystemUtils';
  9. const _pickImage = (aspect) => {
  10. return ImagePicker.requestCameraRollPermissionsAsync()
  11. .then((res) => {
  12. if (!res.granted) {
  13. return Promise.reject('notAllod');
  14. } else {
  15. return ImagePicker.launchImageLibraryAsync({
  16. mediaTypes: ImagePicker.MediaTypeOptions.Images,
  17. allowsEditing: true,
  18. aspect: aspect || [1, 1],
  19. quality: 0.6,
  20. base64: true,
  21. });
  22. }
  23. })
  24. .then((res) => {
  25. if (!res.cancelled) {
  26. if (Platform.OS === 'web') {
  27. toastShow();
  28. return Promise.resolve(res.uri);
  29. }
  30. return Promise.resolve(res.base64);
  31. } else {
  32. return Promise.reject('cancel');
  33. }
  34. })
  35. .then((img) => {
  36. return request.post(`/upload/base64`, {
  37. data: { base64: img },
  38. requestType: 'form',
  39. });
  40. });
  41. };
  42. export default function ImagePickerCom(props) {
  43. const { aspect, img, setImg, cancelEvent, h, w } = props;
  44. return (
  45. <Div mr="sm" mb="sm">
  46. <Button
  47. bg="yellow200"
  48. h={h || 67}
  49. w={w || 67}
  50. rounded="xs"
  51. onPress={() => {
  52. _pickImage(aspect || [1, 1])
  53. .then((newImg) => {
  54. if (setImg) {
  55. setImg(newImg);
  56. }
  57. })
  58. .catch((e) => {
  59. console.log(e);
  60. })
  61. .finally(() => {
  62. toastHide();
  63. });
  64. }}
  65. >
  66. {!img && <Icon name="plus" color="white" fontSize="4xl" />}
  67. {!!img && (
  68. <Image
  69. h={67}
  70. w={67}
  71. rounded="xs"
  72. source={{
  73. uri: img,
  74. }}
  75. />
  76. )}
  77. </Button>
  78. {cancelEvent && (
  79. <Button
  80. bg="red500"
  81. h={16}
  82. w={16}
  83. rounded="circle"
  84. position="absolute"
  85. right={-5}
  86. top={-5}
  87. onPress={cancelEvent}
  88. >
  89. <Icon name="minus" fontFamily="AntDesign" color="#fff" />
  90. </Button>
  91. )}
  92. </Div>
  93. );
  94. }