ASP.NET 畫圖與圖像處理-如何直接輸出到頁面


有時候我們生成的圖片並不需要保存到磁盤中,而是直接輸出到頁面,比如驗證碼、實時報表等,如何做呢?請參考如下:

    protected void Page_Load(object sender, EventArgs e)
    {
        System.Drawing.Bitmap img = new System.Drawing.Bitmap(300, 100);
        System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(img);
       
        System.Drawing.Font font = new System.Drawing.Font("宋體", 16); //字體與大小
        System.Drawing.Brush brush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
        graphics.DrawString("www.cftea.com", font, brush, 50, 50); //寫字,最后兩個參數表示位置
       
        //將圖片保存到內存流中
        System.IO.MemoryStream stream = new System.IO.MemoryStream();
        img.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
       
        //在頁面上輸出
        Response.Clear();
        Response.ContentType = "image/gif";
        Response.BinaryWrite(stream.ToArray());  
       
        stream.Close();
        stream.Dispose();
       
        graphics.Dispose();
        img.Dispose();
       
        Response.End();
    }

更簡單的做法

img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
Response.ContentType = "image/gif";
Response.AddHeader("Content-Disposition", "inline;filename=1.gif");

直接保存在 Response.OutputStream 中。最后一句 AddHeader 的目的是讓用戶在圖片上右鍵另存為的時候,在保存文件對話框中指定默認的文件名。

http://www.cftea.com/c/2008/04/UNNV8Z99H60AVT6U.asp


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM