[英]Display blob image in react native (Expo)
我在我的 React Native 項目中有以下獲取函數以從 MS Graph 返回 blob 圖像,返回有效但我似乎無法將 blob 顯示為圖像。
//Blob Picture
fetch('https://graph.microsoft.com/v1.0/me/photo/$value', {
headers: { 'Authorization': "Bearer " + accessToken },
})
.then((response) => {
// console.log(response);
this.setState({ BlobImage: response});
})
.catch((error) => {
console.error(error);
});
然后我希望像這樣顯示圖像:
<Image source={{uri: BlobImage}} style={{ height: 200, width: null, flex: 1 }}/>
雖然已經有一個答案並且標記為已解決,但我在這里添加我的解決方案。
我試過 react-native-fetch-blob 但沒有成功。
最初我將 responseType 設置為 'arraybuffer'
const photo = await graph.get('/me/photo/$value', {
responseType: 'arraybuffer'
});
現在響應在 photo.data 中有一個數組緩沖區
const state = {
photo: photo.data
};
在我的屏幕上,我顯示了使用 base64-arraybuffer 包的圖像。
import Base64ArrayBuffer from 'base64-arraybuffer';
...
const photoURI = Base64ArrayBuffer.encode(state.photo);
...
<Image style={styles.profilePhoto} source={{ uri: `data:image/jpg;base64,${photoURI}` }} />
一種方法是將您的 blob 轉換為 base64 並將其用作 uri,如此處所述 但我寧願使用rn-fetch-blob並使用路徑,因為它更直接。 檢查這個例子:
RNFetchBlob
.config({
fileCache : true,
// by adding this option, the temp files will have a file extension
appendExt : 'png'
})
.fetch('GET', 'http://www.example.com/file/example.zip', {
//some headers ..
})
.then((res) => {
// the temp file path with file extension `png`
console.log('The file saved to ', res.path())
// Beware that when using a file path as Image source on Android,
// you must prepend "file://"" before the file path
imageView = <Image source={{ uri : Platform.OS === 'android' ? 'file://' + res.path() : '' + res.path() }}/>
})
在浪費了很多時間之后,這與 React Native > 0.60 和使用 react-native-image-picker 或 expo-image-picker 和 axios 的 Expo 配合得很好。
const {uri} = file;
const uriParts = uri.split('.');
const fileType = 'image/' + uriParts[uriParts.length - 1];
const data = new FormData();
data.append('image', {type: fileType, uri: uri, name: 'image'});
data.append('first_name', 'John Doe')
const req = await axios.post(url, data, {headers: {'Content-Type': 'multipart/form-data'} });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.