public Bitmap EncodeImageMosaic(string val, int dotSize, int margin) { DmtxImageEncoderOptions options = new DmtxImageEncoderOptions(); options.MarginSize = margin; options.ModuleSize = dotSize; return EncodeImageMosaic(val, options); }
private void button1_Click(object sender, EventArgs e) { try { string str_Experiment = txt_Experiment.Text; string str_Researher = txt_Researcher.Text; string str_TubeNo = txt_TubeNo.Text; string str_RackNo = txt_RackNo.Text; string str_Position = txt_Position.Text; string str_Strain = txt_Strain.Text; string str_DateTime = dtp_Generator.Value.ToString(); string str_Encode_Text = str_TubeNo + "|" + str_RackNo + "|" + str_Position + "|" + str_Strain + "|" + str_DateTime; DmtxImageEncoder encoder = new DmtxImageEncoder(); DmtxImageEncoderOptions options = new DmtxImageEncoderOptions(); options.ModuleSize = 8; options.MarginSize = 4; options.BackColor = Color.White; options.ForeColor = Color.Green; Bitmap encodedBitmap = encoder.EncodeImage(str_Encode_Text); //encodedBitmap.Save(fileName, ImageFormat.Png); SaveFileDialog objSaveFileDialog = new SaveFileDialog(); objSaveFileDialog.Filter = "Image File|*.png"; objSaveFileDialog.Title = "Save Generated Data Matrix"; if (objSaveFileDialog.ShowDialog() == DialogResult.OK) { encodedBitmap.Save(objSaveFileDialog.FileName, ImageFormat.Png); pictureBox_Generator.Image = Image.FromFile(objSaveFileDialog.FileName); lbl_DocumentName.Text = objSaveFileDialog.FileName; } } catch (Exception ObjExp) { MessageBox.Show(ObjExp.Message); } }
private static void TestMatrixEnDecoder() { string fileName = "encodedImg.png"; DmtxImageEncoder encoder = new DmtxImageEncoder(); DmtxImageEncoderOptions options = new DmtxImageEncoderOptions(); options.ModuleSize = 8; options.MarginSize = 4; options.BackColor = Color.White; options.ForeColor = Color.Green; Bitmap encodedBitmap = encoder.EncodeImage(testVal); encodedBitmap.Save(fileName, ImageFormat.Png); DmtxImageDecoder decoder = new DmtxImageDecoder(); List <string> codes = decoder.DecodeImage((Bitmap)Bitmap.FromFile(fileName), 1, new TimeSpan(0, 0, 3)); foreach (string code in codes) { Console.WriteLine("Decoded:\n" + code); } string s = encoder.EncodeSvgImage("DataMatrix.net rocks!!one!eleven!!111!eins!!!!", 7, 7, Color.FromArgb(100, 255, 0, 0), Color.Turquoise); TextWriter tw = new StreamWriter("encodedImg.svg"); tw.Write(s); tw.Flush(); tw.Close(); TestRawEncoder("HELLO WORLD"); new DmtxImageEncoder().EncodeImage("HELLO WORLD").Save("helloWorld.png"); for (int i = 1; i < 10; i++) { var encodedData = Guid.NewGuid().ToString(); Bitmap source = encoder.EncodeImage(encodedData); var decodedData = decoder.DecodeImage(source); if (decodedData.Count != 1 || decodedData[0] != encodedData) { throw new Exception("Encoding or decoding failed!"); } } }
private static void TestMosaicEnDecoder() { string fileName = "encodedMosaicImg.png"; DmtxImageEncoder encoder = new DmtxImageEncoder(); DmtxImageEncoderOptions options = new DmtxImageEncoderOptions(); options.ModuleSize = 8; options.MarginSize = 4; Bitmap encodedBitmap = encoder.EncodeImageMosaic(testVal); encodedBitmap.Save(fileName, ImageFormat.Png); DmtxImageDecoder decoder = new DmtxImageDecoder(); List <string> codes = decoder.DecodeImageMosaic((Bitmap)Bitmap.FromFile(fileName), 1, new TimeSpan(0, 0, 3)); foreach (string code in codes) { Console.WriteLine("Decoded:\n" + code); } Console.Read(); }
private void GenerateBarcode(string inputData) { if (this.Rdo_Linear.IsChecked.GetValueOrDefault()) { try { TYPE type = (TYPE)Enum.Parse(typeof(TYPE), this.Cbo_L_E_Type.SelectedItem.ToString()); if (type == TYPE.UNSPECIFIED) { return; } _linearEncoder = new Barcode(); this.TextBox1.Text = _linearEncoder.Country_Assigning_Manufacturer_Code; if (!String.IsNullOrEmpty(this.Txt_label.Text)) { _linearEncoder.AlternateLabel = this.Txt_label.Text; } _linearEncoder.BackColor = System.Drawing.Color.White; _linearEncoder.ForeColor = System.Drawing.Color.Black; _linearEncoder.IncludeLabel = this.CheckBox1.IsChecked.GetValueOrDefault(); //_linearEncoder.LabelPosition = EnumUtility.Convert<LabelPositions>(this.Cbo_L_LPosition.SelectedItem.ToString()); _linearEncoder.RotateFlipType = (RotateFlipType)Enum.Parse(typeof(RotateFlipType), this.Cbo_L_Rotate.SelectedItem.ToString()); _linearEncoder.EncodedType = (TYPE)Enum.Parse(typeof(TYPE), this.Cbo_L_E_Type.SelectedItem.ToString()); //_linearEncoder.Alignment = EnumUtility.Convert<AlignmentPositions>(this.Cbo_L_Alignment.SelectedItem.ToString()); Image image = _linearEncoder.Encode(type, inputData); _bitmap = new Bitmap(image); this.Image.Width = _bitmap.Width; this.Image.Height = _bitmap.Height; this.Image.Source = ConvertImage(_bitmap); this.ChildWindow2.Show(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } } if (this.Rdo_QR.IsChecked.GetValueOrDefault()) { try { var qrEncoder = new QRCodeEncoder(); qrEncoder.QRCodeBackgroundColor = System.Drawing.Color.White; qrEncoder.QRCodeForegroundColor = System.Drawing.Color.Black; qrEncoder.QRCodeScale = Convert.ToInt32(Cbo_QR_Scale.SelectedItem); qrEncoder.QRCodeVersion = Convert.ToInt32(Cbo_QR_Version.SelectedItem); qrEncoder.QRCodeEncodeMode = (QRCodeEncoder.ENCODE_MODE)Enum.Parse(typeof(QRCodeEncoder.ENCODE_MODE), this.Cbo_QR_Mode.SelectedItem.ToString()); qrEncoder.QRCodeErrorCorrect = (QRCodeEncoder.ERROR_CORRECTION)Enum.Parse(typeof(QRCodeEncoder.ERROR_CORRECTION), this.Cbo_QR_ErrorC.SelectedItem.ToString()); var image = qrEncoder.Encode(inputData); _bitmap = new Bitmap(image); this.Image.Width = _bitmap.Width; this.Image.Height = _bitmap.Height; this.Image.Source = ConvertImage(_bitmap); this.ChildWindow2.Show(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } } if (this.Rdo_DataM.IsChecked.GetValueOrDefault()) { try { var dataEncoder = new DmtxImageEncoder(); var dataEncoderOptions = new DmtxImageEncoderOptions(); dataEncoderOptions.SizeIdx = (DmtxSymbolSize)Enum.Parse(typeof(DmtxSymbolSize), this.Cbo_D_Size.SelectedItem.ToString()); dataEncoderOptions.Scheme = (DmtxScheme)Enum.Parse(typeof(DmtxScheme), this.Cbo_D_Scheme.SelectedItem.ToString()); dataEncoderOptions.ModuleSize = Convert.ToInt32(Cbo_D_Module.SelectedItem); dataEncoderOptions.MarginSize = Convert.ToInt32(this.Cbo_D_Margin.SelectedItem); dataEncoderOptions.ForeColor = System.Drawing.Color.Black; dataEncoderOptions.BackColor = System.Drawing.Color.White; Image image = dataEncoder.EncodeImage(inputData, dataEncoderOptions); _bitmap = new Bitmap(image); this.Image.Width = _bitmap.Width; this.Image.Height = _bitmap.Height; this.Image.Source = ConvertImage(_bitmap); this.ChildWindow2.Show(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } } }
static void writeDataMatrix(Options options) { // can only use text or file, not both if ((string.IsNullOrWhiteSpace(options.inFile) && string.IsNullOrWhiteSpace(options.text)) || (!string.IsNullOrWhiteSpace(options.inFile) && !string.IsNullOrWhiteSpace(options.text))) { errorPrompt("You must specify either the in-file or text switch when writing a datamatrix image however you cannot use both switches"); } // do we have an out-file in a supported image format? if (!(options.outFile.Trim().ToLower().EndsWith(".png") || options.outFile.Trim().ToLower().EndsWith(".bmp") || options.outFile.Trim().ToLower().EndsWith(".gif") || options.outFile.Trim().ToLower().EndsWith(".jpg") || options.outFile.Trim().ToLower().EndsWith(".jpeg") || options.outFile.Trim().ToLower().EndsWith(".tiff"))) { errorPrompt("Out-file was not in a supported format"); } // what is to be encoded into the datamatrix string data = null; if (!string.IsNullOrWhiteSpace(options.inFile)) { if (!File.Exists(options.inFile)) { errorPrompt("The in-file '{0}' does not exist", options.inFile); } FileInfo fi = new FileInfo(options.inFile); if (fi.Length > 1000) { Console.WriteLine("You are trying to encode a large file this may take some time... continue? (y/[n])"); char ret = Console.ReadKey(true).KeyChar; if (Char.ToLower(ret) != 'y') Environment.Exit(0); } try { StreamReader reader = new StreamReader(options.inFile); data = reader.ReadToEnd(); reader.Close(); } catch (Exception ex) { errorPrompt("When reading file '{0}' an exception occurred:\n{1}", options.inFile, ex.Message); } } else if (!string.IsNullOrWhiteSpace(options.text)) data = options.text; if (string.IsNullOrWhiteSpace(data)) { errorPrompt("No data to encode, aborting..."); } DmtxImageEncoderOptions opts = new DmtxImageEncoderOptions(); opts.ForeColor = Color.Black; opts.BackColor = Color.White; opts.ModuleSize = 8; opts.MarginSize = 60; opts.Scheme = DmtxScheme.DmtxSchemeAsciiGS1; Console.WriteLine("Encoding data..."); DmtxImageEncoder enc = new DmtxImageEncoder(); Bitmap encodedBitmap = enc.EncodeImage(data, opts); try { // set the image format according to outFile's file extension; default to png string imageFormat = options.outFile.Substring(options.outFile.LastIndexOf('.') + 1, options.outFile.Length - options.outFile.LastIndexOf('.') - 1); switch (imageFormat) { case "gif": encodedBitmap.Save(options.outFile, ImageFormat.Gif); break; case "bmp": encodedBitmap.Save(options.outFile, ImageFormat.Bmp); break; case "jpg": case "jpeg": encodedBitmap.Save(options.outFile, ImageFormat.Jpeg); break; case "tiff": encodedBitmap.Save(options.outFile, ImageFormat.Tiff); break; case "png": encodedBitmap.Save(options.outFile, ImageFormat.Png); break; default: // this case should not happen due to prior options.outfile.endswith() checks // we want the file extension to be correct if an unsupported image format // is given by the user options.outFile = options.outFile + ".png"; encodedBitmap.Save(options.outFile, ImageFormat.Png); break; } } catch (Exception ex) { Console.WriteLine("When saving the datamatrix image an exception occurred:\n{0}", ex.Message); } }
public string EncodeSvgImage(string val, DmtxImageEncoderOptions options) { DmtxEncode encode = new DmtxEncode(); encode.ModuleSize = options.ModuleSize; encode.MarginSize = options.MarginSize; encode.SizeIdxRequest = options.SizeIdx; encode.Scheme = options.Scheme; byte[] valAsByteArray = Encoding.ASCII.GetBytes(val); encode.EncodeDataMatrix(options.ForeColor, options.BackColor, valAsByteArray); return EncodeSvgFile(encode, "", options.ModuleSize, options.MarginSize, options.ForeColor, options.BackColor); }
public string EncodeSvgImage(string val, int dotSize, int margin, Color foreColor, Color backColor) { DmtxImageEncoderOptions options = new DmtxImageEncoderOptions(); options.ModuleSize = dotSize; options.MarginSize = margin; options.ForeColor = foreColor; options.BackColor = backColor; return EncodeSvgImage(val, options); }
public Bitmap EncodeImageMosaic(string val, DmtxImageEncoderOptions options) { return EncodeImage(val, options, true); }
public Bitmap EncodeImage(string val, DmtxImageEncoderOptions options) { return EncodeImage(val, options, false); }
private Bitmap EncodeImage(string val, DmtxImageEncoderOptions options, bool isMosaic) { DmtxEncode encode = new DmtxEncode(); encode.ModuleSize = options.ModuleSize; encode.MarginSize = options.MarginSize; encode.Scheme = options.Scheme; encode.SizeIdxRequest = options.SizeIdx; byte[] valAsByteArray = Encoding.ASCII.GetBytes(val); if (isMosaic) { encode.EncodeDataMosaic(valAsByteArray); } else { encode.EncodeDataMatrix(options.ForeColor, options.BackColor, valAsByteArray); } return CopyDataToBitmap(encode.Image.Pxl, encode.Image.Width, encode.Image.Height); }
private void genBtn_Click(object sender, EventArgs e) { if (working) { cancelBtn_Click(sender, e); return; } //检查输入框 if (!File.Exists(inputFileEdit.Text)) { MessageBox.Show("输入文件错误", "错误"); return; } if (!Directory.Exists(outputDirEdit.Text)) { MessageBox.Show("目标目录错误", "错误"); return; } DmtxImageEncoderOptions opt = new DmtxImageEncoderOptions(); switch (int.Parse(matrixSizeCB.Text)) { case 0: opt.SizeIdx = DmtxSymbolSize.DmtxSymbolSquareAuto; break; case 16: opt.SizeIdx = DmtxSymbolSize.DmtxSymbol16x16; break; case 18: opt.SizeIdx = DmtxSymbolSize.DmtxSymbol18x18; break; case 20: opt.SizeIdx = DmtxSymbolSize.DmtxSymbol20x20; break; case 22: opt.SizeIdx = DmtxSymbolSize.DmtxSymbol22x22; break; case 24: opt.SizeIdx = DmtxSymbolSize.DmtxSymbol24x24; break; case 26: opt.SizeIdx = DmtxSymbolSize.DmtxSymbol26x26; break; case 32: opt.SizeIdx = DmtxSymbolSize.DmtxSymbol16x16; break; default: MessageBox.Show("程序可能被改坏了", "错误"); return; break; } int pointSize = int.Parse(pointSizeCB.Text) * 2; string outputDir = outputDirEdit.Text; string[] inputDatas = null; try { inputDatas = File.ReadAllLines(inputFileEdit.Text); } catch { MessageBox.Show("读取输入文件错误", "错误"); return; } progressBar1.Maximum = inputDatas.Length; progressBar1.Value = 0; exitEvent = new EventWaitHandle(false, EventResetMode.ManualReset); Action work = new Action(() => { Action updateProgAction = new Action(() => progressBar1.Value = progressBar1.Value + 1); DmtxImageEncoder encoder = new DmtxImageEncoder(); int dataLen = inputDatas.Length; for (int index = 0; index < dataLen; ++index) { string text = inputDatas[index]; if (exitEvent.WaitOne(0)) { break; } Invoke(updateProgAction); string destFile = Path.Combine(outputDir, (index + 1).ToString()) + ".png"; File.Delete(destFile); bool[,] r = encoder.EncodeRawData(text, opt); if (r == null) { object shouldCont = false; Invoke(new Action(() => { if (MessageBox.Show("所选尺寸不足,无法处理第" + (index + 1).ToString() + "行数据。是否继续?", "错误", MessageBoxButtons.YesNo) == DialogResult.Yes) { shouldCont = true; } })); if (((bool)shouldCont) == false) { break; } else { continue; } } int wc = r.GetLength(0); int hc = r.GetLength(1); int padding = 0; pointSize += padding; Bitmap bmp = new Bitmap(850, 850); Graphics g = Graphics.FromImage(bmp); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.FillRectangle(Brushes.White, Rectangle.FromLTRB(0, 0, 850, 850)); for (int j = 0; j < hc; ++j) { for (int i = 0; i < wc; ++i) { if (r[i, j]) { Rectangle rect = Rectangle.FromLTRB(i * 45 + padding, j * 45 + padding, (i + 1) * 45 - 1, (j + 1) * 45 - 1); g.DrawEllipse(Pens.Black, rect); g.FillEllipse(Brushes.Black, rect); //g.DrawRectangle(Pens.Black, rect); //g.FillRectangle(Brushes.Black, rect); } } } g.Flush(); g.Dispose(); bmp.Save(destFile, System.Drawing.Imaging.ImageFormat.Png); } Invoke(new Action(() => { working = false; genBtn.Text = "生成"; })); }); ThreadStart ts = new ThreadStart(work); Thread workThread = new Thread(ts); workThread.SetApartmentState(ApartmentState.STA); working = true; genBtn.Text = "取消"; workThread.Start(); }
static void Main(string[] args) { if (args.Length == 0 || (args.Length == 1 && IsHelp(args[0]))) { ShowHelp(); return; } SortedDictionary <string, string> argumentList = null; try { argumentList = ParseArguments(args); } catch (Exception) { Console.WriteLine("Error parsing arguments, aborting"); } DmtxImageEncoderOptions encoderOptions = null; try { encoderOptions = GetEncoderOptions(argumentList); } catch (Exception) { Console.WriteLine("Invalid arguments, aborting"); } string input = ""; try { input = GetInputString(argumentList); } catch (Exception) { Console.WriteLine("Invalid input, aborting"); return; } if (!argumentList.ContainsKey("-o")) { Console.WriteLine("No output file specified, aborting"); return; } string outputFileName = argumentList["-o"]; if (!outputFileName.ToLower().EndsWith(".jpg") && !outputFileName.ToLower().EndsWith(".gif") && !outputFileName.ToLower().EndsWith(".png") && !outputFileName.ToLower().EndsWith(".bmp") && !outputFileName.ToLower().EndsWith(".svg")) { Console.WriteLine("File type not supported!"); return; } DmtxImageEncoder encoder = new DmtxImageEncoder(); if (outputFileName.ToLower().EndsWith(".svg")) { string output = encoder.EncodeSvgImage(input, encoderOptions); try { TextWriter tw = new StreamWriter(outputFileName); tw.Write(output); tw.Close(); Console.WriteLine("Output created successfully!"); return; } catch (Exception ex) { Console.WriteLine("Error writing to output file: " + ex.Message); return; } } Image outputImage = null; if (argumentList.ContainsKey("-t") && argumentList["-t"] == "Mosaic") { encoderOptions.BackColor = Color.White; encoderOptions.ForeColor = Color.Black; outputImage = encoder.EncodeImageMosaic(input, encoderOptions); } else if (!argumentList.ContainsKey("-t") || (argumentList.ContainsKey("-t") && argumentList["-t"] == "Matrix")) { outputImage = encoder.EncodeImage(input, encoderOptions); } else { Console.WriteLine("Invalid output type, only 'Matrix' and 'Mosaic' are supported!"); return; } try { outputImage.Save(outputFileName); Console.WriteLine("Output created successfully!"); } catch (Exception ex) { Console.WriteLine("Error writing to output file: " + ex.Message); return; } }
/// <summary> /// Erzeugt einen Barcodeshape an der Position der Zelle <paramref name="range"/> mit dem Inhalt /// der Zelle und passt die Größe an die Zelle an <paramref name="fitToCell"/> /// </summary> /// <param name="range">Die Zelle an der dieser Shape gebunden wird und an dessen stelle der Shape /// platziert wird</param> /// <param name="xlPlacement">Soll das Bild an "frei" beweglich sein oder an die "Zellposition" oder an "Zellposition und Größe" gebunden sein.</param> /// <param name="fitToCell">Soll das Shape an die Zellgröße angepasst werden.</param> /// <param name="cellFitToPicture">Soll die Zelle an die Bildgröße angepasst werden.</param> /// <returns></returns> internal static CellShape AddShape(Excel.Range range, Excel.XlPlacement xlPlacement = Excel.XlPlacement.xlMove, bool fitToCell = false, bool cellFitToPicture = false) { //Nur wenn der text nicht leer ist und die Zellen maximal 1 Zelle ist if (range?.Cells.Count == 1) { //Inhalt der Zelle prüfen var value = range.Value?.ToString(); if (!string.IsNullOrEmpty(value)) { try { //Neuen DataMatrix Encoder erstellen var dmtxImageEncoder = new DmtxImageEncoder(); var dmtxImageEncoderOptions = new DmtxImageEncoderOptions { BackColor = System.Drawing.Color.White, ForeColor = System.Drawing.Color.Black }; //Encodierung einleiten var img = dmtxImageEncoder.EncodeImage(value, dmtxImageEncoderOptions); //Irgendwo in Temp eine Datei erzeugen, Name egal var fName = System.IO.Path.GetTempFileName() + ".jpg"; //In diese TempDatei speichern img.Save(fName); //Position der Zelle System.Drawing.Point point = GetPointOfCell(range); //Neue Größe ermitteln System.Drawing.Size size = GetPictureOrCellSize(fName, range, fitToCell); /* * Erstellt ein Bild und speichert es an der Position der Zelle. * Dem Shape wird die Zelle angehangen, die für den Inhalt verantwortlich ist. */ var shape = range.Worksheet.Shapes.AddPicture( fName, Office.MsoTriState.msoFalse, Office.MsoTriState.msoCTrue, point.X, point.Y, size.Width, size.Height); //Wenn die Zelle angepasst werden soll, dann passen wir hier die Zellengröße an if (cellFitToPicture) { //Die Spaltenbreite ist etwas komplizierter, weil hier die Breite //in Einheiten der Schriftbreite verwendet wird. range.ColumnWidth = range.ColumnWidth / range.Width * size.Width; range.RowHeight = size.Height; } //Zellenbindung in Position und Größe //Ist das Bild frei, an die Position oder an Position und Größe gebunden shape.Placement = xlPlacement; //Wir speichern den Namen des Shape in der Form Barcode($A$1), so können wir später //aus jedem Tabellenblatt die Verlinkung des Barcodes zur Ursprungszelle wieder herleiten shape.Name = $"Barcode({range.Address})"; //Das CellShape zurückgeben return(new CellShape { Shape = shape, Address = range.Address, Value = value }); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show( $"An Error on the barcode creation was thrown, see the message below:\n\n{ex.Message}" , "Error on creating barcode image in AddIn OBIforExcel" , System.Windows.Forms.MessageBoxButtons.OK , System.Windows.Forms.MessageBoxIcon.Error); } } } return(null); }