【问题标题】:How to send image via web api 2?如何通过 web api 2 发送图像?
【发布时间】:2019-03-13 03:55:51
【问题描述】:

我有一个 android 客户端和 asp.net 服务器,我正在使用 web api 2。 我想将图像从服务器返回到客户端作为响应的一部分,我的意思是如果我的响应对象是:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
}

现在我希望我的对象看起来像:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
    public string Image { get; set; }
}

因此string Image 是来自服务器解决方案中包含图像的文件夹中的图像。

我该怎么做?

(我不知道如何定义图像对象,所以我将其定义为字符串)

【问题讨论】:

标签: image asp.net-web-api2


【解决方案1】:

要将实际图像作为字符串获取,您当然需要对其进行编码,您可以尝试对其进行 base64 编码 - 这将允许您将其作为字符串:

byte[] imageBits = System.IO.File.ReadAllBytes(@"/path/to/image");
string imageBase64 = Convert.ToBase64String(imageBits);

然后要显示它,您可以使用<img src="data:yourBase64StringHere" />,或者将其解码回实际图像:

var img = Image.FromStream(new MemoryStream(Convert.FromBase64String(imageBase64)));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    • 2017-10-02
    • 2017-01-15
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    相关资源
    最近更新 更多