Question

I am wanting to save an image to file which has been stored in a memory stream.

I have saved a asp.net chart to a memory stream.

stream1 = new MemoryStream();
chart_location_3.SaveImage(stream1, ChartImageFormat.Png);

and i am then using the following code to export to a jpg. It triggers the save to prompt and creates the file but the image will not open ("this is not a valid bitmap file, or its format is not currently supported")

System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;

System.Drawing.Image img;

img = System.Drawing.Image.FromStream(stream1);
response.ClearContent();
response.Clear();
Response.ContentType = "image/jpg";
response.AddHeader("Content-Disposition", "attachment; filename= Exported.jpg;");
response.Write(img);
response.Flush();
response.End();
Was it helpful?

Solution

changed the response write to:

response.BinaryWrite(stream1.ToArray());

OTHER TIPS

I used something like this before:

http://www.dotnetperls.com/ashx

It generates image to browser on the fly. Hope it helps.


As per the answer at dotnetperls, it is using response.binarywrite. Change code as below:

System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;

System.Drawing.Image img;

img = System.Drawing.Image.FromStream(stream1);
response.ClearContent();
response.Clear();
Response.ContentType = "image/jpg";
response.AddHeader("Content-Disposition", "attachment; filename= Exported.jpg;");
response.BinaryWrite(img);
response.Flush();
response.End();
    public HttpResponseMessage GetStatChart()
    {
        HttpResponseMessage response = new HttpResponseMessage();

        var chartImage = new Chart(600, 400);
        chartImage.AddTitle("Chart Title");
        chartImage.AddSeries(
                name: "Employee",
                chartType: "Pie",
                axisLabel: "Name",
                xValue: new[] { "Peter", "Andrew", "Julie", "Mary", "Dave" },
                yValues: new[] { "2", "6", "4", "5", "3" });
        byte[] chartBytes = chartImage.GetBytes();

        response.Content = new ByteArrayContent(chartBytes);
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

        return response;



    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top