|
import React, { useState, useEffect } from 'react'; |
|
import { View, Image, TouchableOpacity, Text } from 'react-native'; |
|
import * as ImagePicker from 'expo-image-picker'; |
|
import { ImageEditor } from 'react-native'; |
|
|
|
const CropImage = () => { |
|
const [croppedImage, setCroppedImage] = useState(null); // State to store the cropped image URI |
|
|
|
useEffect(() => { |
|
getPermission(); |
|
}, []); |
|
|
|
const getPermission = async () => { |
|
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync(); |
|
if (status !== 'granted') { |
|
alert('Permission denied!'); |
|
} |
|
}; |
|
|
|
const handleSelectImage = async () => { |
|
let result = await ImagePicker.launchImageLibraryAsync({ |
|
mediaTypes: ImagePicker.MediaTypeOptions.Images, |
|
}); |
|
|
|
if (!result.cancelled) { |
|
cropImage(result.uri); |
|
} |
|
}; |
|
|
|
const cropImage = (imageUri) => { |
|
const cropData = { |
|
offset: { x: 100, y: 100 }, // x, y coordinates to start cropping |
|
size: { width: 200, height: 200 }, // width, height of the cropped area |
|
displaySize: { width: 200, height: 200 }, // desired width, height of the cropped image |
|
resizeMode: 'contain', // resizing mode |
|
}; |
|
|
|
ImageEditor.cropImage( |
|
imageUri, |
|
cropData, |
|
(croppedURI) => { |
|
// Handle the cropped image URI |
|
console.log('Cropped image URI:', croppedURI); |
|
setCroppedImage({ uri: croppedURI }); |
|
}, |
|
(error) => { |
|
console.error('Error cropping image:', error); |
|
} |
|
); |
|
}; |
|
|
|
return ( |
|
<View> |
|
<TouchableOpacity onPress={handleSelectImage}> |
|
<Text>Select Image</Text> |
|
</TouchableOpacity> |
|
{croppedImage && <Image source={croppedImage} style={{ width: 200, height: 200 }} />} |
|
</View> |
|
); |
|
}; |
|
|
|
export default CropImage; |
|
|