【问题标题】:What's a good way to dynamically generate PNGs in ASP.NET?在 ASP.NET 中动态生成 PNG 的好方法是什么?
【发布时间】:2011-03-05 07:30:57
【问题描述】:

我需要在 ASP.NET 中生成小的 PNG 图像。图像可以包含简单的几何图形和文本。在 ASP.NET 中生成图像是否需要使用 3rd 方库?

【问题讨论】:

    标签: c# asp.net image


    【解决方案1】:

    这样的?

    Bitmap bmp = new Bitmap(300, 300);
    Graphics g = Graphics.FromImage(bmp);
    
    g.Clear(Color.Transparent);
    g.FillRectangle(Brushes.Red, 100, 100, 100, 100);
    
    g.Flush();
    bmp.Save("test.png", System.Drawing.Imaging.ImageFormat.Png);
    

    (来自here

    当然,您必须使用图像的内容,但图形命名空间可能包含您需要的大部分内容。

    【讨论】:

    • 出于某种原因,我从未注意到 Clear 方法。我一直为整个表面手动使用 FillRectangle,所以感谢 kprobst。 :)
    【解决方案2】:

    您只需使用 .NET 框架中的 Bitmap 和其他与图形相关的类即可。

            Bitmap bmpImage = new Bitmap(width, height);
            Graphics gr = Graphics.FromImage(bmpImage);
            //Draw using gr here
    
            //stream to the client
            Response.ContentType = "image/png";
    
            //write to memory stream first, png can only be written to seekable stream
            using(MemoryStream memStream = new MemoryStream())
            {
              bmpImage.Save(memStream, ImageFormat.Png);
              memStream.WriteTo(Response.OutputStream);
            }
            bmpImage.Dispose();
    

    【讨论】:

    • 必须在所有 System.Drawing 对象(图形、位图)周围加上 using 子句。具有讽刺意味的是,MemoryStream 甚至没有做任何处置时间。
    猜你喜欢
    • 2013-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    相关资源
    最近更新 更多