C#图像处理(3):在图像上加条形码

时间:2021-05-15 14:40:52

引入Aspose.BarCode用来生成条形码,方法如下:

         /// <summary>
/// 生成条码
/// </summary>
/// <param name="CodeString">生成条码的字符串</param>
/// <param name="Path">条码保存的路径</param>
/// <returns>条码保存的路径</returns>
public bool CreateBarCode(string CodeString, string Path)
{
try
{
Aspose.BarCode.BarCodeBuilder builder = new Aspose.BarCode.BarCodeBuilder(CodeString, Symbology.GS1Code128);
//string filenameurl = Application.StartupPath + @"\xxx.gif";
builder.BorderVisible = false;
builder.BarHeight = 10f;
builder.BorderWidth = 30f;
builder.BorderDashStyle = Aspose.BarCode.BorderDashStyle.Solid;
builder.CodeLocation = CodeLocation.Below;
MarginsF Margin = new MarginsF(, , , );
builder.Margins = Margin;
if (!System.IO.File.Exists(Path))
{
builder.Save(Path);
}
else
{
System.IO.File.Delete(Path);
builder.Save(Path);
}
builder.Dispose();
}
catch (Exception ex)
{
return false;
}
return true; ;
}

将条形码加入到图片的指定位置:

         /// <summary>
/// 图片上方加条码,条码将会被180度反转
/// </summary>
/// <param name="Img">待处理图片</param>
/// <param name="ImgBarCode">写入的条码</param>
/// <param name="UpMargin">180度反转后条码顶部距离上边缘距离</param>
/// <param name="RightMargin">条码最左边距离右边缘距离</param>
/// <returns></returns>
public Bitmap BarCodeUp(Image Img, Image ImgBarCode, int UpMargin, int RightMargin)
{
//获取图片宽高
int Width = Img.Width;
int Height = Img.Height;
//获取图片水平和垂直的分辨率
float dpiX = Img.HorizontalResolution;
float dpiY = Img.VerticalResolution;
//创建一个位图文件
Bitmap BitmapResult = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
//设置位图文件的水平和垂直分辨率 与Img一致
BitmapResult.SetResolution(dpiX, dpiY);
//在位图文件上填充一个矩形框
Graphics Grp = Graphics.FromImage(BitmapResult);
System.Drawing.Rectangle Rec = new System.Drawing.Rectangle(, , Width, Height);
//向矩形框内填充Img
Grp.DrawImage(Img, , , Rec, GraphicsUnit.Pixel); //平移Graphics对象
Grp.TranslateTransform(Width - RightMargin, UpMargin);
//设置Graphics对象的输出角度
Grp.RotateTransform();
//设置条码填充颜色
//Brush brush = Brushes.Black;
//旋转显示条码
//Grp.DrawString(WriteString, new Font(FontType, FontSize), brush, 0, 0);
Grp.DrawImage(ImgBarCode, , );
//恢复全局变换矩阵
Grp.ResetTransform();
Grp.Dispose();
GC.Collect();
return BitmapResult;
}