![](/img/trans.png)
[英]How shall I convert application/octet-stream into image to be displayed in base64 or any jpeg format?
[英]How can I display a jpeg stream as an image?
我有一個帶身份驗證的 API,因此我不能只使用像<img src="https://some-link.com/image.jpeg" />
這樣的普通<img>
標簽。
因為我必須進行身份驗證,所以我使用 axios 調用 API:
const instance = axios.create({
headers: {
'Accept': 'image/jpeg',
'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxx'
}
})
function find() {
return instance.get('https://server.com/instances/955a3576/preview');
}
我現在將我的圖像作為 jpeg 流獲取,看起來像這樣(我只粘貼了整個響應數據的一小部分):
����\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000\u0001\u0000\u0001\u0000\u0000��\u0000C\u0000\u0003\u0002\u0002\u0003\u0002\u0002\u0003\u0003\u0003\u0003\u0004\u0003\u0003\u0004\u0005\b\u0005\u0005\u0004\u0004\u0005\n\u0007\u0007\u0006\b\f\n\f\f\u000b\n\u000b\u000b\r\u000e\u0012\u0010\r\u000e\u0011\u000e\u000b\u000b\u0010\u0016\u0010\u0011\u0013\u0014\u0015\u0015\u0015\f\u000f\u0017\u0018\u0016\u0014\u0018\u0012\u0014\u0015\u00
如何在我的網站上將這種響應顯示為圖像? 我正在使用 ReactJS,也許 React 有一個組件可以做到這一點(不幸的是我找不到)?
謝謝你的幫助。
更新:感謝 dune184 對 Blob 的建議。 這似乎很有希望。
我創建了一個具有以下功能的 Blob:
this.setState({myImage: new Blob([res.data], { type: 'image/jfif' })});
現在我試圖顯示這樣的圖像:
<img src={this.state.myImage ? URL.createObjectURL(this.state.myImage) : null}></img>
但圖像不顯示。 任何建議我做錯了什么?
謝謝你的建議。 我現在可以按照 dune184 的建議使用 Blob 解決我的問題。
我從 axios 切換到 fetch,它可以很容易地創建和返回一個 Blob 對象:
function find(id) {
var url = 'https://server.com/instances/'+ id +'/preview';
return fetch(url, {
method: 'GET',
headers: {
'Accept': 'image/jpeg',
'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxxx'
}
}).then(res => res.blob());
}
調用 API 時,我使用 Blob 對象更新我的狀態......
ApiService.find("955a3576").then(res => {
this.setState({myImage: res});
})
...現在可以使用URL.createObjectURL
顯示圖像
<img src={this.state.myImage ? URL.createObjectURL(this.state.myImage) : null}></img>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.