HTML and CSS Reference
In-Depth Information
Listing 4-23. $.ajax() Method Calling the SaveAsImageFile Web Method
$('#btnSave').click(function () {
var data = canvas.toDataURL();
data = data.replace('data:image/png;base64,', '');
type: 'POST',
url: '/SaveAsServerSideImg.aspx/SaveAsImageFile',
data: '{ "data" : "' + data + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('Image saved on the server!');
Once the Base64-encoded data is received in the web method, it's converted to binary form and saved
as a physical file. Listing 4-24 shows the SaveAsImageFile () web method.
Listing 4-24. Saving the Canvas Drawing as a Physical Image File
public static void SaveAsImageFile(string data)
Guid id = Guid.NewGuid();
string path = HttpContext.Current.Server.MapPath("~/images/" + id.ToString() + ".png");
byte[] binaryData = Convert.FromBase64String(data);
FileStream file = new FileStream(path, FileMode.Create);
BinaryWriter bw = new BinaryWriter(file);
This code generates a random file name using a GUID and the Server.MapPath() method. The
physical file has an extension of .png . To convert Base64-encoded data into binary form, you use the
FromBase64String() method of the Convert class. This method accepts Base64-encoded data and returns a
byte array. The byte array thus returned is written to a physical file using the FileStream and BinaryWriter
Figure 4-23 shows a sample canvas drawing saved as an image file being viewed in Windows Photo
Search WWH ::

Custom Search