【问题标题】:How Do I Convert Image URI into Byte Expo如何将图像 URI 转换为字节博览会
【发布时间】:2020-05-16 07:13:39
【问题描述】:

我正在使用expo-image-picker 上传图片。但问题是我想通过 WebAPI 以字节的形式将图像发送到服务器。那么如何将图像 URI 转换为字节呢?如果有人有这方面的经验,请分享。

 componentDidMount() {
        this.getPermissionAsync();
    }
    getPermissionAsync = async () => {
        if (Constants.platform.ios) {
            const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
            if (status !== 'granted') {
                alert('Sorry, we need camera roll permissions to make this work!');
            }
        }
    };
    _pickImage = async () => {
        try {
            let result = await ImagePicker.launchImageLibraryAsync({
                allowsEditing: true,
                aspect: [4, 3],
            });
            console.log(result);

            if (!result.cancelled) {
                this.setState({ image: result.uri });
            }
        } catch (e) {
            console.log(e);
        }
    };
render() {
        return (
            <View>
                <Card>
                    <CardItem>
                        <Body>
                            <Button block primary onPress={() => this._pickImage()}>
                                <Text>Add Activity</Text>
                            </Button>
                            {this.state.image && <Image source={{ uri: this.state.image }} style={{ width: 200, height: 200 }} /> }
                        </Body>
                    </CardItem>
                </Card>
            </View>
        );
    }

Expo Snack

【问题讨论】:

标签: javascript reactjs react-native expo


【解决方案1】:

你可以这样做:

import { Buffer } from "buffer";

_pickImage = async () => {
  try {
    let result = await ImagePicker.launchImageLibraryAsync({
      base64: true,
      allowsEditing: true,
      aspect: [4, 3],
    });

    if (!result.cancelled) {
      let imageByte = new Buffer(result.base64, "base64");

      this.setState({ image: result.uri });
    }
  } catch (e) {
      console.log(e);
  }
};

注意:您将需要buffer 包。

【讨论】:

  • 不,它会返回不想要的结果。
猜你喜欢
  • 2019-12-02
  • 1970-01-01
  • 2017-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-13
  • 1970-01-01
  • 2011-11-26
相关资源
最近更新 更多