-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathApp.js
104 lines (93 loc) · 2.48 KB
/
App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import * as ImagePicker from 'expo-image-picker';
import React from 'react';
import { Button, Image, StyleSheet, Text, View } from 'react-native';
const API_KEY = 'ADD_YOUR_KEY_HERE';
const API_URL = `https://vision.googleapis.com/v1/images:annotate?key=${API_KEY}`;
async function callGoogleVisionAsync(image) {
const body = {
requests: [
{
image: {
content: image,
},
features: [
{
type: 'LABEL_DETECTION',
maxResults: 1,
},
],
},
],
};
const response = await fetch(API_URL, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
const result = await response.json();
console.log('callGoogleVisionAsync -> result', result);
return result.responses[0].labelAnnotations[0].description;
}
export default function App() {
const [image, setImage] = React.useState(null);
const [status, setStatus] = React.useState(null);
const [permissions, setPermissions] = React.useState(false);
const askPermissionsAsync = async () => {
let permissionResult = await ImagePicker.requestCameraPermissionsAsync();
if (permissionResult.granted === false) {
alert('Permission to access camera roll is required!');
return;
} else {
setPermissions(true);
}
};
const takePictureAsync = async () => {
const { cancelled, uri, base64 } = await ImagePicker.launchCameraAsync({
base64: true,
});
if (!cancelled) {
setImage(uri);
setStatus('Loading...');
try {
const result = await callGoogleVisionAsync(base64);
setStatus(result);
} catch (error) {
setStatus(`Error: ${error.message}`);
}
} else {
setImage(null);
setStatus(null);
}
};
return (
<View style={styles.container}>
{permissions === false ? (
<Button onPress={askPermissionsAsync} title="Ask permissions" />
) : (
<>
{image && <Image style={styles.image} source={{ uri: image }} />}
{status && <Text style={styles.text}>{status}</Text>}
<Button onPress={takePictureAsync} title="Take a Picture" />
</>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
alignItems: 'center',
justifyContent: 'center',
},
image: {
width: 300,
height: 300,
},
text: {
margin: 5,
},
});