示例#1
0
        static void DoConvert_DataMatrix(string datafile)
        {
            if (!File.Exists(datafile))
            {
                return;
            }
            XmlDocument doc = new XmlDocument();

            doc.Load(datafile);
            XmlNode root = doc.DocumentElement;

            for (int i = 0; i < root.ChildNodes.Count; i++)
            {
                XmlNode item     = root.ChildNodes[i];
                string  content  = item.Attributes[@"内容"].Value;
                int     height   = int.Parse(item.Attributes[@"高"].Value);
                int     width    = int.Parse(item.Attributes[@"宽"].Value);
                string  filename = item.Attributes[@"内容"].Value;
                string  savefile = item.Attributes[@"文件名"].Value;

                DmtxImageEncoder Die = new DmtxImageEncoder();
                DataMatrix.net.DmtxImageEncoderOptions option = new DmtxImageEncoderOptions();
                option.SizeIdx    = DmtxSymbolSize.DmtxSymbolSquareAuto; //形状
                option.MarginSize = 0;                                   //边距
                option.ModuleSize = 4;                                   //点阵大小

                Bitmap b = Die.EncodeImage(content, option);
                b.Save(savefile, System.Drawing.Imaging.ImageFormat.Bmp);
            }
        }
示例#2
0
        private static void TestGS1EnDecoder()
        {
            string                  fileName1 = "gs1DataMatrix1.png";
            string                  fileName2 = "gs1DataMatrix2.gif";
            string                  gs1Code1  = "10AC3454G3";
            string                  gs1Code2  = "010761234567890017100503";
            DmtxImageEncoder        encoder   = new DmtxImageEncoder();
            DmtxImageEncoderOptions options   = new DmtxImageEncoderOptions();

            options.ModuleSize = 8;
            options.MarginSize = 30;
            options.BackColor  = Color.White;
            options.ForeColor  = Color.Black;
            options.Scheme     = DmtxScheme.DmtxSchemeAsciiGS1;
            Bitmap encodedBitmap1 = encoder.EncodeImage(gs1Code1, options);

            encodedBitmap1.Save(fileName1, ImageFormat.Png);
            Bitmap encodedBitmap2 = encoder.EncodeImage(gs1Code2, options);

            encodedBitmap2.Save(fileName2, ImageFormat.Gif);
            DmtxImageDecoder decoder       = new DmtxImageDecoder();
            List <string>    decodedCodes1 = decoder.DecodeImage(encodedBitmap1, 1, new TimeSpan(0, 0, 5));
            List <string>    decodedCodes2 = decoder.DecodeImage(encodedBitmap2, 1, new TimeSpan(0, 0, 5));

            if (decodedCodes1 != null && decodedCodes1.Count == 1)
            {
                Console.WriteLine("Encoded code 1: {0}, decoded code 1: {1}, codes are equal: {2}", gs1Code1, decodedCodes1[0], gs1Code1.Equals(decodedCodes1[0]));
            }
            if (decodedCodes2 != null && decodedCodes2.Count == 1)
            {
                Console.WriteLine("Encoded code 2: {0}, decoded code 2: {1}, codes are equal: {2}", gs1Code2, decodedCodes2[0], gs1Code2.Equals(decodedCodes2[0]));
            }
            Console.Read();
        }
示例#3
0
        public static Bitmap GenerateGS1DataMatrix(string code, int moduleSize)
        {
            DmtxImageEncoder        encoder = new DmtxImageEncoder();
            DmtxImageEncoderOptions options = new DmtxImageEncoderOptions();

            options.ModuleSize = moduleSize;
            options.MarginSize = 0;
            options.BackColor  = Color.White;
            options.ForeColor  = Color.Black;
            options.Scheme     = DmtxScheme.DmtxSchemeAsciiGS1;
            return(encoder.EncodeImage(code, options));
            //return GenerateGS1DataMatrix(code.Select(x => (byte)x).ToArray(), moduleSize);
        }
示例#4
0
        public Bitmap make(string sValue, int iBitSize, int iBorSize)
        {
            sValue = sValue.Replace("[ENTER]", System.Environment.NewLine);
            DmtxImageEncoder        encoder = new DmtxImageEncoder();
            DmtxImageEncoderOptions options = new DmtxImageEncoderOptions();

            options.ModuleSize = iBitSize;
            options.MarginSize = iBorSize;
            options.BackColor  = System.Drawing.Color.White;
            options.ForeColor  = System.Drawing.Color.Black;
            Bitmap oB = encoder.EncodeImage(sValue, options);

            return(oB);
        }
示例#5
0
文件: Form1.cs 项目: ssor/csharpDemos
        private void button3_Click(object sender, EventArgs e)
        {
            DmtxImageEncoder        encoder = new DmtxImageEncoder();
            DmtxImageEncoderOptions options = new DmtxImageEncoderOptions();

            options.ModuleSize = 8;
            options.MarginSize = 4;
            options.BackColor  = Color.White;
            options.ForeColor  = Color.Black;
            Bitmap encodedBitmap = encoder.EncodeImage("1231234567890-lkjhgfds");

            pictureBox1.Image = encodedBitmap;
            return;
        }
示例#6
0
        public string GetMatrixSymbologies(string barcode)
        {
            DmtxImageEncoder encoder = new DmtxImageEncoder();
            Bitmap           bmp     = encoder.EncodeImage(barcode);

            byte[] bitmapData;

            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                bmp.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
                bitmapData = memoryStream.ToArray();
            }

            return(Convert.ToBase64String(bitmapData));
        }
        /// <summary>
        /// Redraws the whole barcode
        /// </summary>
        public override void RedrawAll()
        {
            Children.Clear();

            if (Value != null)
            {
                DmtxImageEncoder encoder = new DmtxImageEncoder();
                var bmpImage = ImageToBitmapImage(encoder.EncodeImage(Value.ToString()));

                var BarcodeImage = new Image();
                BarcodeImage.Stretch = Stretch.UniformToFill;
                BarcodeImage.Source = bmpImage;
                BarcodeImage.Width = this.Width;
                BarcodeImage.Height = this.Height;
                Children.Add(BarcodeImage);
            }                
        }
        /// <summary>
        /// Redraws the whole barcode
        /// </summary>
        public override void RedrawAll()
        {
            Children.Clear();

            if (Value != null)
            {
                DmtxImageEncoder encoder = new DmtxImageEncoder();
                var bmpImage             = ImageToBitmapImage(encoder.EncodeImage(Value.ToString()));

                var BarcodeImage = new Image();
                BarcodeImage.Stretch = Stretch.UniformToFill;
                BarcodeImage.Source  = bmpImage;
                BarcodeImage.Width   = this.Width;
                BarcodeImage.Height  = this.Height;
                Children.Add(BarcodeImage);
            }
        }
示例#9
0
        static void Main(string[] args)
        {
            //string[] args = new string[4];
            //args[0] = @"C:\BarcodeImages\test.jpg";
            //args[1] = "QR";
            //args[2] = "ASA";
            //args[3] = "   123";

            try
            {
                //param 0 = File directory
                //param 1 = DMC or QR info
                //param 2 = BarcodeText

                string StrBarcode = "";
                StrBarcode = StrBarcode + args[2];
                for (int i = 3; i < args.Length; i++)
                {
                    StrBarcode = StrBarcode + " " + args[i];
                }

                if (args[1] == "DMC")
                {
                    DmtxImageEncoder encoder = new DmtxImageEncoder();
                    Bitmap           bmp     = encoder.EncodeImage(StrBarcode, 100);
                    bmp.Save(args[0], System.Drawing.Imaging.ImageFormat.Jpeg);
                }

                if (args[1] == "QR")
                {
                    QRCodeGenerator QREn   = new QRCodeGenerator();
                    var             QRData = QREn.CreateQrCode(StrBarcode, QRCoder.QRCodeGenerator.ECCLevel.H);
                    var             QRCode = new QRCode(QRData);
                    var             Img    = QRCode.GetGraphic(20);
                    Img.Save(args[0], System.Drawing.Imaging.ImageFormat.Jpeg);
                }

                //Test
                //string deneme = "ss";
            }
            catch (Exception)
            {
                throw;
            }
        }
示例#10
0
        private static void TestRawEncoder(string text)
        {
            DmtxImageEncoder encoder = new DmtxImageEncoder();

            bool[,] rawData = encoder.EncodeRawData(text);
            Console.WriteLine("================");
            Console.WriteLine();
            for (int rowIdx = 0; rowIdx < rawData.GetLength(1); rowIdx++)
            {
                for (int colIdx = 0; colIdx < rawData.GetLength(0); colIdx++)
                {
                    Console.Write(rawData[colIdx, rowIdx] ? "X" : " ");
                }
                Console.WriteLine();
            }
            Console.WriteLine();
            Console.WriteLine("================");
        }
示例#11
0
        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);
            }
        }
示例#12
0
        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!");
                }
            }
        }
示例#13
0
        private void btnEncode_Click(object sender, EventArgs e)
        {
            DmtxImageEncoder encoder = new DmtxImageEncoder();

            try
            {
                Bitmap img = encoder.EncodeImage(textBoxEnc.Text);

                picBox.Image  = img;
                picBox.Width  = img.Width;
                picBox.Height = img.Height;
                picBox.Left   = 139;
                picBox.Top    = 95;
            }
            catch
            {
                textBoxEnc.Text = "0";
            }
        }
示例#14
0
 private void btnGenerate_Click(object sender, RoutedEventArgs e)
 {
     if (Directory.Exists(txtPath.Text))
     {
         int i = 1;
         foreach (string s in dataMatrixDataList)
         {
             string           fullFileName = string.Format("{0}\\DM{1:D4}.png", txtPath.Text, i); //[)><RS>06<GS>P40217372<GS>1T20347[0000]<RS><EOT>
             DmtxImageEncoder encoder      = new DmtxImageEncoder();
             Bitmap           bmp          = encoder.EncodeImage(s);
             bmp.Save(fullFileName, System.Drawing.Imaging.ImageFormat.Png);
             i++;
             txtResults.AppendText(StringConverting.DisplayString(s));
         }
     }
     else
     {
         MessageBox.Show("Wybrana ścieżka nie istnieje!!!", "Zła ścieżka", MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
示例#15
0
        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();
        }
示例#16
0
        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");
                }
            }
        }
示例#17
0
        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;
            }
        }
示例#18
0
        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();
        }
示例#19
0
        /// <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);
        }
示例#20
0
        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);
            }
        }