如何通过网络发送图片api 2?
How to send image via web api 2?
我有一个 android 客户端和 asp.net 服务器,我正在使用网络 api 2。
我想 return 从服务器到客户端的图像 作为响应的一部分 ,我的意思是如果我的响应对象是:
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
是服务器解决方案中包含图像的文件夹中的图像。
我该怎么做?
(我不知道怎么定义图片对象所以定义成字符串)
要将实际图像作为字符串获取,您当然需要对其进行编码,您可以尝试对其进行 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)));
我有一个 android 客户端和 asp.net 服务器,我正在使用网络 api 2。 我想 return 从服务器到客户端的图像 作为响应的一部分 ,我的意思是如果我的响应对象是:
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
是服务器解决方案中包含图像的文件夹中的图像。
我该怎么做?
(我不知道怎么定义图片对象所以定义成字符串)
要将实际图像作为字符串获取,您当然需要对其进行编码,您可以尝试对其进行 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)));