servarevitas3
servarevitas3

Reputation: 483

How do I generate an Image in a ASP.NET ASMX web service and load it via AJAX?

I am currently using a function inside an ASP.Net ASMX web service to generate a System.Drawing.Image. I would like to have this image (after converting to a png or something) passed to the browser as the reply to an AJAX call. (using jQuery's $.ajax). I've been Googling but can't seem to find out how, although I'm pretty sure it's possible. Do I convert it to a Data URI somehow first, or what?

Upvotes: 2

Views: 2285

Answers (1)

Kamyar
Kamyar

Reputation: 18797

I don't think you can do that. In order to return the image, you should have a method which returns bytearray which I don't think is of any use in javascript.
My workaround is to save the image in a certain location and return the address of the image to clientside.

Update: based on the comments, you can encode the image's data to Base64 string and handle the DATA URI on your ajax callback.
You can use JSON to represent the base64Encoded data, and on the ajax calklback, you can write something like:

$("#myImage").attr("src", "data:image/png;base64,RETURNED_DATA_FROM_ASMX");    

Here's a sample code to convert your image to base64 in c#:

public string ImageToBase64(Image image, 
  System.Drawing.Imaging.ImageFormat format)
{
  using (MemoryStream ms = new MemoryStream())
  {
    // Convert Image to byte[]
    image.Save(ms, format);
    byte[] imageBytes = ms.ToArray();

    // Convert byte[] to Base64 String
    string base64String = Convert.ToBase64String(imageBytes);
    return base64String;
  }
}

To find out how to format a DATA URI, you can visit http://en.wikipedia.org/wiki/Data_URI_scheme#Format.

Upvotes: 2

Related Questions