How to solve a common error caused by GDI + when ASP. NET outputs a PNG Image

Source: Internet
Author: User

The original text is as follows:
Code:
Copy codeThe Code is as follows:
Response. Clear ();
Response. ContentType = "image/PNG ";
Img. Save (Response. OutputStream, ChartFormat. Png );

An exception occurred, which is a common error of GDI +. However, if the format is
Code:
Copy codeThe Code is as follows:
Response. ContentType = "image/jpeg ";

No error will be reported.
Fortunately, I used to change it
Code:
Copy codeThe Code is as follows:
Response. ContentType = "image/PNG ";
Using (MemoryStream MS = new MemoryStream ())
{
Img. Save (MS, ChartFormat. Png );
Response. OutputStream. Write (ms. GetBuffer (), 0, (int) ms. Length );
}

You can enter a png image.
This is because the stream Response. OutputStream cannot be read back, that is, its CanSeek attribute.
Is false. When a png image is generated, it is not like jpeg. It is not streaming. If it has already been written, it is not necessary to go back.
Write structural data constantly. However, the response stream cannot go back to seek, so it cannot be used directly. Can be changed to one.
Seek's MemoryStream, which is converted into a png image and then output to the response stream.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.