How to implement the random generation and display of the picture, and do not save the picture to the database or hard disk! Author: tavor Issue Date: 2004-7-5 22:44:00
The principle of random generation of pictures is to randomly read records from the database, and then construct the corresponding pictures, then write it to Response.OutputStream with binary. The principles from the database are as follows: set rowcount 1 select * from [Your] Order by newid () If the ID in your table is continuous, you can also use the NEXT () method of the C # Random class. Generate a random ID to obtain the corresponding record, as follows: "Select * from [YourTable] where [pkid] =" (new random ()). Next (1,1000); The corresponding record has been read from the database, and now you should use the read record as a parameter to generate a corresponding picture, because here is just a demonstration, the passive parameters are just a string, of course, can also do more practical For example, the style of setting pictures, etc. The following method returns a Bitmap object: public bitmap getImage (string s) {bitmap b = new bitmap (1, 1); int Width, Height; Font Afont = New Font ("Times New Roman", 16, System.drawing .GraphicsUnit.point; graphics graphics = graphics.fromImage (b); width = (int) graphics.measureString (s, af) .width; height = (int) graphics.measureString (s, afst) .height; b = new Bitmap (b, new Size (width, height)); graphics = Graphics.FromImage (b); graphics.Clear (Color.Black); graphics.TextRenderingHint = TextRenderingHint.AntiAlias; graphics.DrawString (s, aFont, new SolidBrush (Color.yellow), 0, 0); graphics.flush (); return (b);} Now get a Bitmap object, now it is output, we can add the output code in the corresponding event, below The example is placed in the Page_Load method, the code is as follows: response.contenttype = "image / gif" b.save (response.outputstream, system.drawing .imaging .imageformat .gif); // memorystream ms = new memoryStream (); // b.save (ms, system.drawing .imaging .imageformat .gif); // ms.position = 0; // Byte [] t = new byte [ms.length]; // ms.read (t, 0, (int) ms.Length); // response.binaryWrite (T); the above code gives two output methods, one is to save Bitmap to the output stream of Response In the middle, another method is to save Bitmap into a stream, then write the database to a byte array, and then write it directly to the output stream with the RESPONSE's binary output method, actually MS The content is written directly to the output flow and implements the output of the picture.