これを実現するにはさまざまな方法がありますが、個人的には次のようにします。まず、画像を生成するフォーム送信 (画像の生成に使用しているデータ) を受け取るハンドラーを作成します (ファイルをサーバーに個人的に保存することはしませんが、必要に応じて)、 JSONを使用してこの文字列を返すためにハンドラーを使用して base64 にエンコードします。
public void ProcessRequest (HttpContext context)
{
// generate the image from POST / GET data sent to this handler from your form
Bitmap bmp = GenerateImage(postData);
// now convert your generated image to a base64 string
string base64 = string.Empty;
using (MemoryStream ms = new MemoryStream())
{
bmp.Save(ms, ImageFormat.Png);
base64 = Convert.ToBase64String(ms);
}
// now return this base64 string to the caller
context.Response.ContentType = "application/json";
string json = "{ \"imageBase64\": \"" + base64 + "\" }";
context.Response.Write(json);
}
クライアント側では、jQuery を使用してハンドラーに Ajax 呼び出しを行い、フォーム データを POST/GET し、base64 でエンコードされた画像の文字列を取得して、 html タグのsrc
プロパティを設定します。img
function postAndRetrieveImage() {
$.ajax({
url: "http://server/myhandler.ashx",
data: jsonDataParsedFromForm,
dataType: "json",
type: "POST",
contentType: "application/json",
async: true,
cache: false,
beforeSend: function() {
// overlay your "loading..." image or something while you wait
// for response from the server
},
complete: function() {
// hide your "loading..." image (or whatever it is) as the operation
// has completed
},
success: function(data) {
var response = jQuery.parseJSON(data.d);
// set the src attribute of the IMG tag (prefixed with the usual
// image stuff) with the base64
var image = document.getElementById("myImage");
image.setAttribute("src", "data:image/png;base64," + response.imageBase64);
},
error: function() {
// display error in some way
}
});
}
私が言ったように、これを達成する方法はたくさんあるので、このラフな (テストされていない) 例は、私がこれを行う方法の 1 つです。IMG
タグがあれば、右クリックで画像を保存することもできます。
これが出発点として役立つことを願っています。