Problem scenario:
After reading the WebCast (III) of Yi Zhiming, I used the GDI + plot part and followed the code, and reported an error ":
"System. Runtime. InteropServices. ExternalException: A generic error occurred in GDI + ."
Code behavior:
Bmp. Save (Response. OutputStream, ImageFormat. Png );
Development Environment:
1. WindowsXP, vs2005, vs2008, vs2010beta2;
2. Windows2003, vs2005, vs2008, vs2010beta2
Code profiling:
Requirement: create a web application and run the start page to output an ellipse.
Code placed in Page_Load
Error code:
Code
Bitmap bmp = new Bitmap (200, 60 );
Graphics g = Graphics. FromImage (bmp );
G. Clear (Color. White );
G. DrawEllipse (new Pen (new SolidBrush (Color. Blue), 10, 10,180, 40 );
Response. ClearContent ();
Response. ContentType = "image/png ";
Bmp. Save (Response. OutputStream, ImageFormat. Png );
Change png to gif or jpeg, and the program runs normally.
Correct code 1: (updated code lines: 1, 8, and 9)
Output images with MemStream
Code
1 MemoryStream MemStream = new MemoryStream ();
2 Bitmap bmp = new Bitmap (200, 60 );
3 Graphics g = Graphics. FromImage (bmp );
4g. Clear (Color. White );
5g. DrawEllipse (new Pen (new SolidBrush (Color. Blue), 10, 10,180, 40 );
6 Response. ClearContent ();
7 Response. ContentType = "image/png ";
8 bmp. Save (MemStream, ImageFormat. Png );
9 MemStream. WriteTo (Response. OutputStream );
The Code in line 1 can be changed to Response. BinaryWrite (MemStream. ToArray ());
Code 2:
Specify the image storage location for saving
Code
1 string sIconFileName = Server. MapPath ("test.png ");
2 Bitmap bmp = new Bitmap (200, 60 );
3 Graphics g = Graphics. FromImage (bmp );
4G. Clear (Color. Transparent );
5G. DrawEllipse (new Pen (new SolidBrush (Color. Blue), 10, 10,180, 40 );
6Response. ClearContent ();
7Response. ContentType = "image/png ";
8bmp. Save (sIconFileName, ImageFormat. Png );
Cause analysis:
Png is a special case. Its decoder requires two-way stream. Therefore, we first need to read the stream to the memory stream, and then use the output stream to write the memory stream.
The gif decoder has a built-in parallel mechanism for processing.
Additional reading:
Http://www.west-wind.com/Weblog/posts/6008.aspx
Http://www.evolt.org/article/To_PNG_or_not_to_PNG/22/60134/index.html