ImagePicker.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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({
  43. aspect = [1, 1],
  44. img,
  45. setImg,
  46. cancelEvent,
  47. h = 67,
  48. w = 67,
  49. }) {
  50. return (
  51. <Div mr="sm" mb="sm">
  52. <Button
  53. bg="yellow200"
  54. h={h}
  55. w={w}
  56. rounded="xs"
  57. onPress={() => {
  58. _pickImage(aspect || [1, 1])
  59. .then((newImg) => {
  60. if (setImg) {
  61. setImg(newImg);
  62. }
  63. })
  64. .catch((e) => {
  65. console.log(e);
  66. })
  67. .finally(() => {
  68. toastHide();
  69. });
  70. }}
  71. >
  72. {!img && <Icon name="plus" color="white" fontSize="4xl" />}
  73. {!!img && (
  74. <Image
  75. h={h}
  76. w={w}
  77. rounded="xs"
  78. source={{
  79. uri: img,
  80. }}
  81. />
  82. )}
  83. </Button>
  84. {!!cancelEvent && (
  85. <Button
  86. bg="red500"
  87. h={16}
  88. w={16}
  89. rounded="circle"
  90. position="absolute"
  91. right={-5}
  92. top={-5}
  93. onPress={cancelEvent}
  94. >
  95. <Icon name="minus" fontFamily="AntDesign" color="#fff" />
  96. </Button>
  97. )}
  98. </Div>
  99. );
  100. }