Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Buscar imágenes de galería con React Native

Tiempo de lectura: 2 minutos

Hoy os voy a enseñar cómo podemos obtener imágenes de la galería del dispositivo utilizando React Native.

Primero tenemos que instalar la siguiente librería:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install react-native-image-picker --save
npm install react-native-image-picker --save
npm install react-native-image-picker --save

Lo primero que haremos es añadir los permisos, para ello vamos a la carpeta nativa Android y buscamos nuestro AndroidManifest.xml

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  <uses-permission android:name="android.permission.CAMERA"/>
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

En el caso de iOS vamos a info.plist y añadimos:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<key>NSPhotoLibraryUsageDescription</key>
<string>Allow $(PRODUCT_NAME) to access your photo library</string>
<key>NSCameraUsageDescription</key>
<string>Allow $(PRODUCT_NAME) to access your camera</string>
<key>NSPhotoLibraryUsageDescription</key> <string>Allow $(PRODUCT_NAME) to access your photo library</string> <key>NSCameraUsageDescription</key> <string>Allow $(PRODUCT_NAME) to access your camera</string>
<key>NSPhotoLibraryUsageDescription</key>
	<string>Allow $(PRODUCT_NAME) to access your photo library</string>
	
	<key>NSCameraUsageDescription</key>
	<string>Allow $(PRODUCT_NAME) to access your camera</string>

Y ejecutamos este comando:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
RCT_NEW_ARCH_ENABLED=1 npx pod-install ios
RCT_NEW_ARCH_ENABLED=1 npx pod-install ios
 RCT_NEW_ARCH_ENABLED=1 npx pod-install ios

Ahora creamos un componente nuevo, lo llamaremos ImagePicker.js y añadimos lo siguiente:

  • Importamos la librería que vamos a utilizar:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import * as ImagePicker from "react-native-image-picker"
import * as ImagePicker from "react-native-image-picker"
import * as ImagePicker from "react-native-image-picker"

Y creamos las siguientes funciones:

  • Obtener imagen de Gelería:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
export function getImageLibrary(returnFunction) {
var objetoImagenRetornar = {};
let options = {
storageOptions: {
skipBackup: true,
path: 'images',
},
includeBase64: true
};
ImagePicker.launchImageLibrary(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
returnFunction(-2);
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
returnFunction(-1);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
alert(response.customButton);
} else {
const source = { uri: response.uri };
console.log('response', JSON.stringify(response));
objetoImagenRetornar = {
data: response,
fileData: response.assets[0].base64,
base64Data: 'data:image/jpeg;base64,' + response.assets[0].base64,
fileUri: response.assets[0].uri
};
returnFunction(objetoImagenRetornar );
}
});
}
export function getImageLibrary(returnFunction) { var objetoImagenRetornar = {}; let options = { storageOptions: { skipBackup: true, path: 'images', }, includeBase64: true }; ImagePicker.launchImageLibrary(options, (response) => { console.log('Response = ', response); if (response.didCancel) { console.log('User cancelled image picker'); returnFunction(-2); } else if (response.error) { console.log('ImagePicker Error: ', response.error); returnFunction(-1); } else if (response.customButton) { console.log('User tapped custom button: ', response.customButton); alert(response.customButton); } else { const source = { uri: response.uri }; console.log('response', JSON.stringify(response)); objetoImagenRetornar = { data: response, fileData: response.assets[0].base64, base64Data: 'data:image/jpeg;base64,' + response.assets[0].base64, fileUri: response.assets[0].uri }; returnFunction(objetoImagenRetornar ); } }); }
export function getImageLibrary(returnFunction) {
    var objetoImagenRetornar = {};
    let options = {
        storageOptions: {
            skipBackup: true,
            path: 'images',
        },
       includeBase64: true
    };
    ImagePicker.launchImageLibrary(options, (response) => {
        console.log('Response = ', response);

        if (response.didCancel) {
            console.log('User cancelled image picker');
            returnFunction(-2);
        } else if (response.error) {
            console.log('ImagePicker Error: ', response.error);
            returnFunction(-1);
        } else if (response.customButton) {
            console.log('User tapped custom button: ', response.customButton);
            alert(response.customButton);
        } else {
            const source = { uri: response.uri };
            console.log('response', JSON.stringify(response));
            objetoImagenRetornar = {
                data: response,
                fileData: response.assets[0].base64,
                base64Data: 'data:image/jpeg;base64,' + response.assets[0].base64,
                fileUri: response.assets[0].uri
            };
             returnFunction(objetoImagenRetornar );
        }
    });
}
  • Obtener imagen de cámara:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
export function getLaunchCamera() {
var objetoImagenRetornar = {};
let options = {
storageOptions: {
skipBackup: true,
path: 'images',
},
includeBase64: true
};
ImagePicker.launchCamera(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
returnFunction(-2);
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
returnFunction(-1);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
alert(response.customButton);
} else {
const source = { uri: response.uri };
console.log('response', JSON.stringify(response));
objetoImagenRetornar = {
data: response,
fileData: response.assets[0].base64,
base64Data: 'data:image/jpeg;base64,' + response.assets[0].base64,
fileUri: response.assets[0].uri
};
returnFunction(objetoImagenRetornar);
}
});
}
export function getLaunchCamera() { var objetoImagenRetornar = {}; let options = { storageOptions: { skipBackup: true, path: 'images', }, includeBase64: true }; ImagePicker.launchCamera(options, (response) => { console.log('Response = ', response); if (response.didCancel) { console.log('User cancelled image picker'); returnFunction(-2); } else if (response.error) { console.log('ImagePicker Error: ', response.error); returnFunction(-1); } else if (response.customButton) { console.log('User tapped custom button: ', response.customButton); alert(response.customButton); } else { const source = { uri: response.uri }; console.log('response', JSON.stringify(response)); objetoImagenRetornar = { data: response, fileData: response.assets[0].base64, base64Data: 'data:image/jpeg;base64,' + response.assets[0].base64, fileUri: response.assets[0].uri }; returnFunction(objetoImagenRetornar); } }); }
export function getLaunchCamera() {
    var objetoImagenRetornar = {};
  
        let options = {
            storageOptions: {
                skipBackup: true,
                path: 'images',
            },
        includeBase64: true
        };
        ImagePicker.launchCamera(options, (response) => {
            console.log('Response = ', response);

            if (response.didCancel) {
                console.log('User cancelled image picker');
                returnFunction(-2);
            } else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
            returnFunction(-1);
            } else if (response.customButton) {
                console.log('User tapped custom button: ', response.customButton);
                alert(response.customButton);
            } else {
                const source = { uri: response.uri };
                console.log('response', JSON.stringify(response));
                objetoImagenRetornar = {
                  data: response,
                  fileData: response.assets[0].base64,
                  base64Data: 'data:image/jpeg;base64,' + response.assets[0].base64,
                  fileUri: response.assets[0].uri
               };
                returnFunction(objetoImagenRetornar);
            }
        });
}

Y para invocar a las funciones solo tendremos que importar nuestro archivo ImagePicker.js dónde querramos utilizarlo:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import { getLaunchCamera, getImageLibrary } from "../../ImagenesGaleria/ImagesPicker";
import { getLaunchCamera, getImageLibrary } from "../../ImagenesGaleria/ImagesPicker";
import {  getLaunchCamera, getImageLibrary } from "../../ImagenesGaleria/ImagesPicker";

Y llamar a la función con un onPress:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
onPress={() => {
getImageManage();
}}
...
function getImageManage(){
getImageLibrary(returnFunction)
function returnFunction(objReturn){
console.log(JSON.stringify(objReturn));
}
}
onPress={() => { getImageManage(); }} ... function getImageManage(){ getImageLibrary(returnFunction) function returnFunction(objReturn){ console.log(JSON.stringify(objReturn)); } }
onPress={() => { 

getImageManage();

 }}



...

function getImageManage(){
getImageLibrary(returnFunction)

function returnFunction(objReturn){
console.log(JSON.stringify(objReturn));
}
}

Recuerda qué para utilizar esta librería nativa, tendrás que generar un build nativo: https://devcodelight.com/como-crear-un-build-development-usando-expo-eas-con-react-native/

0

Deja un comentario