c# - 在 ASP.NET 中设置动态创建图像的内容长度

标签 c# asp.net .net http

我正在寻找一种简单的方法来设置 Http 响应中动态创建的图像的内容长度。

Response.ContentType = "image/jpeg";
Response.Clear();
Response.BufferOutput = true; 
...
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
...
bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
Response.Flush();

尝试设置内容长度

Response.AddHeader("Content-Length", Response.OutputStream.Length()) 

给出意想不到的结果。

此外,我不希望将文件复制到另一个流(例如 MemoryStream)并将其再次复制到输出流。

有什么想法吗?

谢谢。

最佳答案

long bmpByteSize;
using (var ms = new MemoryStream(estimatedLength /* you can instantiate without this parameter at all */))
{
    bmp.Save(ms, ImageFormat.Png);
    bmpByteSize= ms.Length;
}

关于c# - 在 ASP.NET 中设置动态创建图像的内容长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9598197/

相关文章:

C#:double[][] 和 double[,]

javascript - 使用 Ajax 的 URL Action 参数

c# - 使用图形的 Azure 函数我得到 "Could not load file or assembly ' System.Text.Json”

c# - 在同步代码中实现需要 Task 返回类型的接口(interface)

c# - cecil : Instruction. Instruction.OpCode.Code值对应的操作数类型

c# - ASP.net C#。多个页面合而为一

c# - 在 C# 中使用 LINQ 在范围之间分组数据

c# - POST 字符串到 ASP.NET Web Api 应用程序 - 返回 null

c# - 如何将类作为可选参数传递给方法?

c# - 将用户控件拖放到 VS 设计器时发生 TypeLoadException