Wednesday, April 22, 2015

Code to dynamically generate images.. ECM image generator


        private void button1_Click(object sender, EventArgs e)
        {
            for (int iLoop = 1; iLoop <= 20000; iLoop++)
            {
                string strTxt = "First Name: " + txtFirstName.Text + iLoop.ToString() + "\n\n\n" + "Last Name: " + txtLastName.Text + iLoop.ToString() + "\n\n\n" + "Test Card# " + txtSampleCard.Text + iLoop.ToString() + "\n\n\n" + "BizArea # " + txtBizArea.Text + "\n\n\n" +
                    "This is a sample image generated by ECM tool";

                Image objImage = DrawText(strTxt, Color.Blue, Color.Coral);
                objImage.Save(@"c:\Image\testImage"+iLoop.ToString()+".jpg");
            }
        }

        private Image DrawText(String text, Color textColor, Color backColor)
        {
            //first, create a dummy bitmap just to get a graphics object
            Image img = new Bitmap(1, 1);
            Graphics drawing = Graphics.FromImage(img);
         
            // Set Font property and then add a new Label.
            Font font = new Font("Microsoft Sans Serif", 10.0f);
            this.Font = font;
            this.Size = new Size(300, 200);

            //measure the string to see how big the image needs to be
            SizeF textSize = drawing.MeasureString(text, font);

            //free up the dummy image and old graphics object
            img.Dispose();
            drawing.Dispose();

            //create a new image of the right size
            img = new Bitmap((int)textSize.Width, (int)textSize.Height);

            drawing = Graphics.FromImage(img);

            //paint the background
            drawing.Clear(backColor);

            //create a brush for the text
            Brush textBrush = new SolidBrush(textColor);

            drawing.DrawString(text, font, textBrush, 0, 0);

            drawing.Save();

            textBrush.Dispose();
            drawing.Dispose();

            return img;

        

No comments: