Tuesday, December 26, 2017

How do I use PresentationCore in a WebAPI hosted on Azure?

Leave a Comment

I have developed a "simple" testcase:

[HttpPost] [Route("GetImage")] public HttpResponseMessage GetImage() {     try     {         int bmpX = 50;         int bmpY = 50;         DrawingVisual drawingVisual = new DrawingVisual();         var dc = drawingVisual.RenderOpen();         dc.DrawRectangle(Brushes.Green, new Pen(Brushes.Green, 3), new System.Windows.Rect(0, 0, bmpX, bmpY));         dc.DrawLine(new Pen(Brushes.Red, 2.0), new System.Windows.Point(0, 0), new System.Windows.Point(bmpX, bmpY));         dc.DrawLine(new Pen(Brushes.Red, 2.0), new System.Windows.Point(0, bmpY), new System.Windows.Point(bmpX, 0));         dc.Close();         var bmp = new RenderTargetBitmap(bmpX, bmpY, 96, 96, PixelFormats.Pbgra32);         bmp.Render(drawingVisual);         var encoder = new PngBitmapEncoder();         encoder.Frames.Add(BitmapFrame.Create(bmp));         MemoryStream memoryStream = new MemoryStream();         encoder.Save(memoryStream);         HttpResponseMessage httpResponseMessage = new HttpResponseMessage();         httpResponseMessage.Content = new ByteArrayContent(memoryStream.ToArray());         httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");         httpResponseMessage.StatusCode = HttpStatusCode.OK;         return httpResponseMessage;     }     catch (Exception ex)     {         var message = Request.CreateResponse(HttpStatusCode.Created, ex.ToString());         return message;     } } 

This is a function inside my ASP.Net WebAPI project, as part of a Controller (ValuesController as it happens, so adding this to a default project should reproduce the problem easily enough). If I deploy this to Azure and run it locally, then invoke both from Fiddler, the local one works as expected and returns a red X on a green background, but the Azure one returns a blank image.

If I use GDI (System.Drawing.Bitmap) then it works OK, even from Azure. Unfortunately this isn't a solution; I'm porting an already-written application from desktop to an Azure API service and the PresentationCore code is extensive and would take too long to convert to GDI.

Edit: if anyone has a working Azure/Web API/PresentationCore application that I could pick through, that could be very helpful.

0 Answers

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment