I'm creating some barcode generator, and I want to save generated barcode to database, but I have a problem when I want to get bytes from PictureBox Image. It says that Image property is null. That's hapening because barcode is drawn on the PictureBox(not in Image property). I think that I could solve it by converting graphic to bitmap, but I don't know how?. Here's the code:

Graphics graphics = barcodePictureBox.CreateGraphics();

            graphics.FillRectangle(new SolidBrush(SystemColors.Control),
                new Rectangle(0, 0, barcodePictureBox.Width, barcodePictureBox.Height));

            EAN13 = new Ean13();
            EAN13.CountryCode = "680"; // Yugoslavia
            EAN13.ManufacturerCode = "69048";
            EAN13.ProductCode = RandomNumberGenerator.Generate();
            if (ceksuma.Length > 0)
                EAN13.ChecksumDigit = checksum;

            EAN13.Scale = (float)Convert.ToDecimal("1.0");
            EAN13.DrawEan13Barcode(graphics, new Point(0, 0));
            checksum = EAN13.ChecksumDigit;
            graphics.Dispose();

Drawing to a control's Graphics object like this is only temporary.
When the control is next refreshed the image will disappear.
You need to create an image object and draw to that then assign this to the picture box.
Try modifying your code as below. You should them be able to get the image to save.

// create an image object
            Image img = new System.Drawing.Bitmap(barcodePictureBox.Width, barcodePictureBox.Height);
            // get the graphics object to draw on the image.
            Graphics graphics = Graphics.FromImage(img);
            // set the image background colour
            graphics.FillRectangle(new SolidBrush(SystemColors.Control),
                new Rectangle(0, 0, barcodePictureBox.Width, barcodePictureBox.Height));
            // draw an EAN code on the image
            EAN13 = new Ean13();
            EAN13.CountryCode = "680"; // Yugoslavia
            EAN13.ManufacturerCode = "69048";
            EAN13.ProductCode = RandomNumberGenerator.Generate();
            if (ceksuma.Length > 0)
                EAN13.ChecksumDigit = checksum;

            EAN13.Scale = (float)Convert.ToDecimal("1.0");
            EAN13.DrawEan13Barcode(graphics, new Point(0, 0));
            checksum = EAN13.ChecksumDigit;

            // copy image to picture box control
            barcodePictureBox.Image = img;
            graphics.Dispose();

Thanks. Your code works with some changes in DrawEan13Barcode method.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.