简体   繁体   中英

Cannot draw image from WebApi call on Canvas

I have a working WebApi that delivers a PNG image to me (tested in Fiddler). However, when I want to draw the image an on HTML Canvas, nothing happens.

Web api code :

public HttpResponseMessage GetInitialMap(int height, int width)
{
    var chart = RmdbHelper.GetInitialChart(height, width);

    MemoryStream memoryStream = new MemoryStream();
    chart.Save(memoryStream, ImageFormat.Png);

    HttpResponseMessage response = new HttpResponseMessage();
    response.Content = new StreamContent(memoryStream);
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
    response.StatusCode = HttpStatusCode.OK;

    return response;

}

This is the javascript and jquery code to call the image and try drawing

var NavChart = function() {
    var ctx,
    chartHeight,
    chartWidth,

    // other stuff

    renderBackgroundMap = function() {
        $.get("../api/NauticalMaps/GetInitialMap?height" + chartHeight + "&width=" + chartWidth)
            .done(function (bgImage) {
                var background = new Image(chartWidth, chartHeight);
                background.src = bgImage;
                ctx.drawImage(background, 0, 0);
            })
            .fail(function (error) {
                showError("...");
            });

    };

    initialize = function(canvasId) {
        var canvas = document.getElementById(canvasId);
        chartHeight = canvas.getAttribute("height");
        chartWidth = canvas.getAttribute("width");

        ctx = canvas.getContext("2d");

        render();
    };

    return {
        initialize: initialize
    };
};

On the HTML page I create a NavChart object and call the initialize function. No problems until then. Fiddler shows me that the call is made and it returns a image.

HTML and call :

<div class="row">
    <canvas id="zeekaart" height="550" width="1150" style="border: 1px solid lightgrey"></canvas>
</div>


<script>
    var nav = new NavChart();
    nav.initialize("zeekaart");  
</script>

It seems that

var background = new Image(chartWidth, chartHeight);
background.src = bgImage;

the .src expects an URL or destination. But plainly using

.done(function (bgImage) {
    ctx.drawImage(bgImage, 0, 0);
})

doesn't work either.

Any ideas? I don't want to write all images away in a temp folder on the server and clear them after a specified time.

A workaround presented by @Kaiido does the job well enough, like this:

var back = new Image();
back.onload = function() {
    ctx.drawImage(back, 0, 0);
}
back.src = "../api/NauticalMaps/GetInitialMap?height=" + chartHeight + "&width=" + chartWidth;

However ... I finally found the solution for my problem. Part of my problem was not returning a JSON object, by returning it as a plain image. When returning purely an image, the code above will do. But, by returning the image as part of a JSON object, you can directly use the image in the browser memory. Here's my solution:

A simple class for storing the data (which will be sent automatically as json) to the browser

public class NavigationMapData
{
    public byte[] MapData { get; set; }

    // ... other data goes in here as well     
}

The api-controller method:

public NavigationMapData Get(string id, double northing, double easting, double northing2, double easting2, int height, int width)
{
    NavigationMapData data = new NavigationMapData();
    // next method just returns a Bitmap object
    var img = RmdbHelper.GetChart(northing, easting, northing2, easting2, height, width);
    // convert the object
    data.MapData = img.ToByteArray(ImageFormat.Jpeg);
    return data;
}

For the completeness, the image extension for converting Image/Bitmap data into a byte[]:

public static class ImageExtensions
{
    public static byte[] ToByteArray(this Image image, ImageFormat format)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            image.Save(ms, format);
            return ms.ToArray();
        }
    }
}

The javascript/jquery code:

$.get(URL_TO_API_PLUS_PARAMS)
    .done(function (navMapData) {

        var img = document.createElement("img");
        // as seen on stackoverflow somewhere
        img.src = 'data:image/jpeg;base64,' + navMapData.MapData;
        ctx.drawImage(img, 0, 0);
    })
    .fail(function (error) {
        // onError actions
    })
    .always(function() {
        // onFinished actions
    });

Now I have more control over my api calls in case a bitmap or my data would not load.

您的Web API正在发送原始图像数据,但“ src”需要一个URL。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM