gpt4 book ai didi

c# - 从 RESTful WCF 服务返回图像

转载 作者:太空狗 更新时间:2023-10-29 21:46:32 25 4
gpt4 key购买 nike

我有这个非常简单的 DTO:

[DataContract]
public class DTO
{
[DataMember]
public byte[] Image {get; set; }
}

这个非常简单的服务:

[ServiceContract]
public interface IFooService
{
[WebGet(
UriTemplate = "",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
List<DTO> GetDTOs();
}

在我的 global.asax 中,我有:

RouteTable.Routes.Add(new ServiceRoute("foo", 
new WebServiceHostFactory(), typeof(FooService)));

现在,当我从浏览器调用它时,我得到了一个 JSON 格式的字节数组。目前很好。现在,如何将该字节数组转换为图像?

或者,是否有更好的方法来解决这个问题?我尝试将 byte[] 更改为 Stream,但是当我从 Firefox 调用该服务时,尽管 HTTP 状态代码为 200,但响应为空。我正在使用 Firebug 和 fiddler 。

我不认为它是相关的,但由于太多的信息永远不会伤害任何不是机器人的人,这里是 web.config:

<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
</configuration>

最终,我想问题是:如何从 WCF RESTful 服务返回位图,以便在浏览器中运行的 JavaScript 可以将其显示在屏幕上?

最佳答案

Good so far. Now, how do I turn that array of bytes into an image?

由于您已使用 javascript 标记了您的问题,我假设这是您使用该服务所使用的,并且您希望在浏览器中显示图像。如果是这种情况,您可以查看 Data URI scheme。这将允许您在给定从服务获得的字节数的情况下显示图像。

下面是一个示例,您可以如何使用 jQuery 使用此类服务​​并显示图像:

$(function () {
$.getJSON('/foo/', function (dtos) {
$.each(dtos, function (index, dto) {
var str = String.fromCharCode.apply(String, dto.Image);
$('<img/>', {
alt: '',
src: 'data:image/png;base64,' + $.base64.encode(str)
}).appendTo('body');
});
});
});

$.base64.encode 函数来自this plugin .

关于c# - 从 RESTful WCF 服务返回图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8340247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com