-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathutils.ts
More file actions
74 lines (65 loc) · 2.13 KB
/
Copy pathutils.ts
File metadata and controls
74 lines (65 loc) · 2.13 KB
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
import { Alert } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { ImageManipulator, SaveFormat } from 'expo-image-manipulator';
import type { SkImage } from '@shopify/react-native-skia';
/**
* Converts a Skia image into the raw RGBA/HWC image buffer that
* react-native-executorch vision tasks accept. Throws if the pixel data cannot
* be read.
* @param image - The Skia image to read pixels from.
* @returns The RGBA/HWC image buffer with its `data`, `width`, `height`,
* `format`, and `layout`.
*/
export const skImageToBuffer = (image: SkImage) => {
const pixels = image.readPixels();
if (!pixels) {
throw new Error('Failed to read pixels from image');
}
if (!(pixels instanceof Uint8Array)) {
throw new Error('Expected Uint8Array from readPixels');
}
return {
data: pixels,
width: image.width(),
height: image.height(),
format: 'rgba' as const,
layout: 'hwc' as const,
};
};
export const getImage = async (
useCamera: boolean,
targetWidth = 800
): Promise<string | undefined> => {
const permissionResult = useCamera
? await ImagePicker.requestCameraPermissionsAsync()
: await ImagePicker.requestMediaLibraryPermissionsAsync();
if (!permissionResult.granted) {
Alert.alert(
'Permission Required',
useCamera
? 'Permission to access camera is required!'
: 'Permission to access camera roll is required!'
);
return;
}
const options: ImagePicker.ImagePickerOptions = {
mediaTypes: ['images'],
allowsEditing: false,
quality: 1,
};
const pickerResult = useCamera
? await ImagePicker.launchCameraAsync(options)
: await ImagePicker.launchImageLibraryAsync(options);
if (pickerResult.canceled || !pickerResult.assets[0]) {
return;
}
const asset = pickerResult.assets[0];
let imageRef = await ImageManipulator.manipulate(asset.uri).renderAsync();
if (imageRef.width > targetWidth) {
imageRef = await ImageManipulator.manipulate(asset.uri)
.resize({ width: targetWidth })
.renderAsync();
}
const result = await imageRef.saveAsync({ format: SaveFormat.PNG });
return result.uri;
};