C#图像处理(3):在图像上加条形码
引入Aspose.BarCode用来生成条形码,方法如下:
1 /// <summary> 2 /// 生成条码 3 /// </summary> 4 /// <param name="CodeString">生成条码的字符串</param> 5 /// <param name="Path">条码保存的路径</param> 6 /// <returns>条码保存的路径</returns> 7 public bool CreateBarCode(string CodeString, string Path) 8 { 9 try 10 { 11 Aspose.BarCode.BarCodeBuilder builder = new Aspose.BarCode.BarCodeBuilder(CodeString, Symbology.GS1Code128); 12 //string filenameurl = Application.StartupPath + @"\xxx.gif"; 13 builder.BorderVisible = false; 14 builder.BarHeight = 10f; 15 builder.BorderWidth = 30f; 16 builder.BorderDashStyle = Aspose.BarCode.BorderDashStyle.Solid; 17 builder.CodeLocation = CodeLocation.Below; 18 MarginsF Margin = new MarginsF(1, 1, 0, 0); 19 builder.Margins = Margin; 20 if (!System.IO.File.Exists(Path)) 21 { 22 builder.Save(Path); 23 } 24 else 25 { 26 System.IO.File.Delete(Path); 27 builder.Save(Path); 28 } 29 builder.Dispose(); 30 } 31 catch (Exception ex) 32 { 33 return false; 34 } 35 return true; ; 36 }
将条形码加入到图片的指定位置:
1 /// <summary> 2 /// 图片上方加条码,条码将会被180度反转 3 /// </summary> 4 /// <param name="Img">待处理图片</param> 5 /// <param name="ImgBarCode">写入的条码</param> 6 /// <param name="UpMargin">180度反转后条码顶部距离上边缘距离</param> 7 /// <param name="RightMargin">条码最左边距离右边缘距离</param> 8 /// <returns></returns> 9 public Bitmap BarCodeUp(Image Img, Image ImgBarCode, int UpMargin, int RightMargin) 10 { 11 //获取图片宽高 12 int Width = Img.Width; 13 int Height = Img.Height; 14 //获取图片水平和垂直的分辨率 15 float dpiX = Img.HorizontalResolution; 16 float dpiY = Img.VerticalResolution; 17 //创建一个位图文件 18 Bitmap BitmapResult = new Bitmap(Width, Height, PixelFormat.Format24bppRgb); 19 //设置位图文件的水平和垂直分辨率 与Img一致 20 BitmapResult.SetResolution(dpiX, dpiY); 21 //在位图文件上填充一个矩形框 22 Graphics Grp = Graphics.FromImage(BitmapResult); 23 System.Drawing.Rectangle Rec = new System.Drawing.Rectangle(0, 0, Width, Height); 24 //向矩形框内填充Img 25 Grp.DrawImage(Img, 0, 0, Rec, GraphicsUnit.Pixel); 26 27 28 //平移Graphics对象 29 Grp.TranslateTransform(Width - RightMargin, UpMargin); 30 //设置Graphics对象的输出角度 31 Grp.RotateTransform(180); 32 //设置条码填充颜色 33 //Brush brush = Brushes.Black; 34 //旋转显示条码 35 //Grp.DrawString(WriteString, new Font(FontType, FontSize), brush, 0, 0); 36 Grp.DrawImage(ImgBarCode, 0, 0); 37 //恢复全局变换矩阵 38 Grp.ResetTransform(); 39 Grp.Dispose(); 40 GC.Collect(); 41 return BitmapResult; 42 }