【解決方法】Asp、net C# ビットマップからイメージをダウンロード


I have a picture on the server is a generous certificate of appreciation when the student searches with a number the student's data is written on the image and without saving it on the server the student protects it on his machine
I got the code to write on the image, but it saves it on the server. Please help me. Instead of saving on the server, the downloader works for the student.
This is the writing code

<pre>Bitmap bitMapImage = new Bitmap(Server.MapPath("img1.jpg"));
            Graphics graphicImage = Graphics.FromImage(bitMapImage);
            graphicImage.DrawString("testing 1 2 3",
            new Font("Arial", 20, FontStyle.Bold),
            SystemBrushes.WindowText, new Point(0, 0));
                    //  I want to replace this by downloading it to the student machine //instead of saving it to the server          bitMapImage.Save(Server.MapPath("~/Images")+"newImage.jpg" , ImageFormat.Jpeg);
            graphicImage.Dispose();

bitMapImage.Dispose();

私が試したこと:

tried

クライアントPCに画像をダウンロード

解決策 1

画像をバイト配列に変換し、BinaryWrite を使用してファイルとしてクライアントに送信します。

C#
Response.AddHeader("Cache-Control", "no-cache, must-revalidate, post-check=0, pre-check=0");
Response.AddHeader("Pragma", "no-cache");
Response.AddHeader("Content-Description", "File Download");
Response.AddHeader("Content-Type", "application/force-download");
Response.AddHeader("Content-Transfer-Encoding", "binary\n");
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
Response.BinaryWrite(data);
Response.End();

解決策 2

1. MemoryStream それに画像を「保存」します。
2. 上記の MemoryStream を 応答

このようになります

C#
Bitmap bitMapImage = new Bitmap(Server.MapPath("img1.jpg"));
Graphics graphicImage = Graphics.FromImage(bitMapImage);
graphicImage.DrawString("testing 1 2 3",
new Font("Arial", 20, FontStyle.Bold),
SystemBrushes.WindowText, new Point(0, 0));
        
// I want to replace this by downloading it to the student machine 
// instead of saving it to the server
// bitMapImage.Save(Server.MapPath("~/Images")+"newImage.jpg" , ImageFormat.Jpeg);

MemoryStream memoryStream = new MemoryStream();
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);

byte[] bytesInStream = memoryStream.ToArray();
memoryStream.Close(); 

Response.Clear();
Response.ContentType = "image/jpeg";
Response.AddHeader("content-disposition", "attachment; newImage.jpg");
Response.BinaryWrite(bytesInStream);

graphicImage.Dispose();
bitMapImage.Dispose();

Response.End();

役立つ情報:
c# – ビットマップをMemoryStreamに保存する[^]
c# – メモリストリームをファイルにダウンロードするには? – スタックオーバーフロー[^]

コメント

タイトルとURLをコピーしました