[英]Meteor React: Render Image from Array Buffer
I try to write a component which renders a picture fetched from a REST-Server. 我尝试编写一个组件,用于呈现从REST服务器获取的图片。 I have to fetch the picture on the server-side because I don't want to expose the REST-Server to the Internet. 我必须在服务器端获取图片,因为我不想将REST服务器暴露给Internet。 Because of this, i can't simply put an "img" tag in the html. 因此,我不能简单地在html中添加“img”标签。 (The REST-Server runs on the same system as the Meteor-Server). (REST-Server在与Meteor-Server相同的系统上运行)。
Lets say, the Meteor-Method "get_picure" fetches the picture from the REST-Server and returns it to the component. 可以说,Meteor-Method“get_picure”从REST-Server获取图片并将其返回给组件。 The returned object is the plain result from a synchronous HTTP.call-request. 返回的对象是来自同步HTTP.call请求的普通结果。
Picture.jsx Picture.jsx
import React, { Component, PropTypes } from 'react';
export default class Picture extends Component {
propTypes: {
picture: PropTypes.string.isReqired,
style: Proptypes.object,
}
constructor(props) {
super(props);
this.state = {
pic: null,
style: this.props.style
}
//invoke the server to fetch the picture
Meteor.call("get_picture", this.props.picture, this.update.bind(this));
}
//callback for Meteor.call
update(error,data) {
if(error || data.statusCode != 200) {
return;
}
//data.content is an "uint8Array" due to the { npmRequestOptions: {encoding: null}} option set in the HTTP-Request
this.setState({pic: data.content});
}
render() {
return (
<span style={this.state.style}>
{ this.state.pic ? this.state.pic : "" }
</span>
)
}
}
All I get, are numbers displayed in the given "span"-tag. 我得到的只是给定“span”-tag中显示的数字。
Is there a way, to display the picture from a state-variable? 有没有办法,从状态变量显示图片?
After a bit of googling, I found an answer. 经过一番谷歌搜索,我找到了答案。 A working solution is to encode the existing uint8array
to base64. 一个有效的解决方案是将现有的uint8array
编码为base64。
export default class Picture extends Component {
...
update(error,data) {
...
//encode to base64
var image = btoa(String.fromCharCode.apply(null, data.content);
this.setState({pic: "data:image/png;base64," + image});
}
...
}
To display this, I set the src
-Attribute from an <img />
-Tag to this.state.pic
. 为了显示这一点,我将src
-Attribute从<img />
this.state.pic
为this.state.pic
。 This causes the fetched image to display in the generated <img />
-Tag. 这会导致获取的图像显示在生成的<img />
-Tag中。
Note : "data:image/png"
represents the content-type from the fetched image and can be replaced with any other image-content-type (for example image/jpeg
). 注意 : "data:image/png"
表示来自获取图像的内容类型,可以替换为任何其他图像内容类型(例如image/jpeg
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.