如何在点网核心 API 中接受和返回图像



我有一个接受字符串并返回二维码(作为图像(的dotnet core api。我可以在浏览器上看到图像。 我有另一个使用 api 的项目,但我不知道如何获取图像

//This the code that accepts string and retuns image as qr code
[Route("generate")]
[HttpGet]
public IActionResult Process(string context = "play")
{
var content = context;
var width = 200;
var height = 200;
var barcodeWriterPixelData = new ZXing.BarcodeWriterPixelData
{
Format = ZXing.BarcodeFormat.QR_CODE,
Options = new QrCodeEncodingOptions
{
Height = height,
Width = width,
Margin = 0
}
};
var memoryStream = new MemoryStream();
var pixelData = barcodeWriterPixelData.Write(content);
using (var bitmap = new Bitmap(pixelData.Width, pixelData.Height,
System.Drawing.Imaging.PixelFormat.Format24bppRgb))
{
var bitmapData = bitmap.LockBits(
new Rectangle(0, 0, pixelData.Width, pixelData.Height),
System.Drawing.Imaging.ImageLockMode.WriteOnly,
System.Drawing.Imaging.PixelFormat.Format32bppRgb
);
try
{
System.Runtime.InteropServices.Marshal.Copy
(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length);
}
finally
{
bitmap.UnlockBits(bitmapData);
}
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
memoryStream.Seek(0, SeekOrigin.Begin);


return File(memoryStream, "image/png");
}
}
//This is the code that consumes the api but i don't know how to get the image from it
public class HomeController : Controller
{
public QR_API _myapi = new QR_API();
public async Task<ActionResult<JsonResult>> Index()
{
HttpClient client = _myapi.Initial();
HttpResponseMessage res =  await client.GetAsync("generate");
if (res.IsSuccessStatusCode)
{
return Json(res);
}
return Json("Not Working");
}

如您所见,我可以在 api 中获取图像,如何从 http rsponse 消息中检索它

你可以做的一件事是从HttpResponseMessage的内容中读取你的图像作为byteArray。

var 图像 = 响应。Content.ReadAsByteArrayAsync((.结果;

然后将其作为 json 中的 byte[] 属性返回给您的 UI 端

public byte[] barCodeImage { get; set; }

更详细地说:

添加一个响应 dto 类,该类将具有图像属性和其他属性基础,您需要像这样

public class ResponseDTO
{
public int statuscode { get; set; }
public string errormessage { get; set; }
public string someproperty { get; set; }
public byte[] barCodeImage { get; set; }//this one is ur image porperty
}

然后你的

public async Task<ActionResult<ResponseDTO>> Index()
{
var resp = new ResponseDTO() { statuscode = 200 };//creating response object
try
{
HttpClient client = _myapi.Initial();
HttpResponseMessage res = await client.GetAsync("generate");
if (res.IsSuccessStatusCode)
{
HttpResponseMessage response = await client.GetAsync(builder.Uri);
//read your image from HttpResponseMessage's content as byteArray
var image = response.Content.ReadAsByteArrayAsync().Result;
//Setting ur byte array to property of class which will convert into json later
resp.barCodeImage = image;
resp.someproperty = "some other details you want to send to UI";

}
}
catch (Exception e)
{
//In case you got error
resp.statuscode = 500;
resp.errormessage = e.Message;
}
return resp;
}

相关内容

  • 没有找到相关文章

最新更新