private void Button_Click(object sender, RoutedEventArgs e) { try { Code128Content content = new Code128Content(txtInput.Text); this.txtGenBarCode.Text = string.Join(string.Empty, content.Codes); System.Drawing.Image myimg = Code128Rendering.MakeBarcodeImage(txtInput.Text, int.Parse(txtWeight.Text), true); MemoryStream ms = new MemoryStream(); // no using here! BitmapImage will dispose the stream after loading myimg.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); BitmapImage ix = new BitmapImage(); ix.BeginInit(); ix.CacheOption = BitmapCacheOption.OnLoad; ix.StreamSource = ms; ix.EndInit(); this.imgBarCode.Source = ix; } catch (Exception ex) { //MessageBox.Show(this, ex.Message, this.txtInput.Text); } }
public bool GetGenerateBarCodeText(SensorDataModel sensorDataModel, out string generatedText) { generatedText = string.Empty; var barCodeString = BarcodeManager.GenerateBarCodeString(sensorDataModel); if (string.IsNullOrEmpty(barCodeString)) return false; Code128Content content = new Code128Content(barCodeString); generatedText = string.Join(string.Empty, content.Codes); return true; }
/// <summary> /// Make an image of a Code128 barcode for a given string /// </summary> /// <param name="InputData">Message to be encoded</param> /// <param name="BarWeight">Base thickness for bar width (1 or 2 works well)</param> /// <param name="AddQuietZone">Add required horiz margins (use if output is tight)</param> /// <returns>An Image of the Code128 barcode representing the message</returns> public static System.Drawing.Image MakeBarcodeImage( string InputData, int BarWeight, bool AddQuietZone ) { // get the Code128 codes to represent the message Code128Content content = new Code128Content( InputData ); int[] codes = content.Codes; int width, height; width = ( (codes.Length-3) * 11 + 35) * BarWeight; height = Convert.ToInt32( System.Math.Ceiling( Convert.ToSingle(width) * .15F) ); if (AddQuietZone) { width += 2 * cQuietWidth * BarWeight; // on both sides } // get surface to draw on Image myimg = new System.Drawing.Bitmap(width, height); using (Graphics gr = Graphics.FromImage(myimg)) { // set to white so we don't have to fill the spaces with white gr.FillRectangle(System.Drawing.Brushes.White, 0, 0, width, height); // skip quiet zone int cursor = AddQuietZone ? cQuietWidth * BarWeight : 0; for (int codeidx = 0; codeidx < codes.Length; codeidx++) { int code = codes[codeidx]; // take the bars two at a time: a black and a white for (int bar = 0; bar < 8; bar += 2) { int barwidth = cPatterns[code, bar] * BarWeight; int spcwidth = cPatterns[code, bar + 1] * BarWeight; // if width is zero, don't try to draw it if (barwidth > 0) { gr.FillRectangle(System.Drawing.Brushes.Black, cursor, 0, barwidth, height); } // note that we never need to draw the space, since we // initialized the graphics to all white // advance cursor beyond this pair cursor += (barwidth + spcwidth); } } } return myimg; }