我正在尝试在移动应用中显示项目列表的缩略图。 API返回一个完整大小的图像,我通过XMLHttpRequest检索,然后使用FileReader转换为base64。
http.onreadystatechange = () => {
if (http.readyState !== 4) return;
if (http.status === 200 && http.response) {
const fileReader = new FileReader();
fileReader.readAsDataURL(http.response);
fileReader.onload = () => {
const result = fileReader.result;
resolve(result);
};
} else {
resolve(false);
}
};
http.send(JSON.stringify(params));
如果我使用它的输出作为或源,它工作正常。但是,我想首先缩小图像,因为没有理由将全尺寸图像存储在内存中只是为了显示缩略图,所以在从我的API文件中检索完整图像后,我试图将它传递给ImageManipulator 。
const photo = await inventoryAPI.getPhoto(credentials, this.key);
const shrunk = await ImageManipulator.manipulateAsync(photo, [{ resize: { width: 320 } }], { base64: true });
出于某种原因,ImageManipulator在这一步上抛出了一个错误:File 'data:image/jpeg;base64,[long image data string here]=' isn't readable
我确定还有其他方法来压缩base64图像数据,但我想知道这里的问题是什么,以防我需要对这种方式检索的图像执行任何其他操作。任何帮助,将不胜感激。谢谢!
您可以使用filesystem
中的expo
对base64进行编码。
example.js
import { FileSystem } from 'expo'
...
const signature = await FileSystem.readAsStringAsync(item.signature, { encoding: FileSystem.EncodingTypes.Base64 })
要么
您可以使用ImagePicker
中的expo
对base64进行编码。
example.js
import React, { Component } from 'react';
import { Button, Image, Text, View, StyleSheet } from 'react-native';
import { ImagePicker, Constants } from 'expo';
export default class App extends Component {
state = {
pickerResult: null,
};
_pickImg = async () => {
let pickerResult = await ImagePicker.launchImageLibraryAsync({
base64: true,
allowsEditing: false,
aspect: [4, 3],
});
this.setState({
pickerResult,
});
};
render() {
let { pickerResult } = this.state;
let imageUri = pickerResult ? `data:image/jpg;base64,${pickerResult.base64}` : null;
imageUri && console.log({uri: imageUri.slice(0, 100)});
return (
<View style={styles.container}>
<Button onPress={this._pickImg} title="Open Picker" />
{pickerResult
? <Image
source={{uri: imageUri}}
style={{ width: 200, height: 200 }}
/>
: null}
{pickerResult
? <Text style={styles.paragraph}>
Keys on pickerResult:
{' '}
{JSON.stringify(Object.keys(pickerResult))}
</Text>
: null}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
color: '#34495e',
},
});
它是关于link的Image Picker