当前位置:   article > 正文

C# net6使用ImageSharp绘图并展示_sixlabors.imagesharp

sixlabors.imagesharp


研究这个的最初目的是,使用net 6做blazor网站,希望在登录界面实现验证码生成功能,因一直找不到字体文件,所以切换项目实验一下。

winform实现

1.新建窗体程序,使用net 6框架

2.使用Nuget安装相关程序包,SixLabors.ImageSharp和SixLabors.ImageSharp.Drawing(这个使用的是预发行版)

3.在项目根目录中放置字体文件(*.ttf,设置文件属性—复制到输出目录—始终复制)

4.在项目根目录中新建文件保存路径

5.主要生成代码

private void button1_Click(object sender, EventArgs e)
		{
			pictureBox1.Image = null;
			int codeW = 100;
			int codeH = 36;
			int fontSize = 32;
			string chkCode = string.Empty;
			SixLabors.ImageSharp.Color[] color = { SixLabors.ImageSharp.Color.Black, SixLabors.ImageSharp.Color.Red, SixLabors.ImageSharp.Color.Blue, SixLabors.ImageSharp.Color.Green, SixLabors.ImageSharp.Color.Orange, SixLabors.ImageSharp.Color.Brown, SixLabors.ImageSharp.Color.DarkBlue };
			//string[] font = { "Times New Roman" };
			//需要将字体放到项目中
			string[] fonts = { "Arial.ttf" };
			char[] character = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
			//生成验证码字符串
			Random rnd = new Random();
			for (int i = 0; i < 4; i++)
			{
				chkCode += character[rnd.Next(character.Length)];
			}
			//写入Session用于验证码校验,可以对校验码进行加密,提高安全性
			//System.Web.HttpContext.Current.Session["verifyCode"] = chkCode;
			try
			{
				//创建画布
				var image = new Image<Rgba32>(codeW, codeH);
				image.Mutate(x => x.BackgroundColor(SixLabors.ImageSharp.Color.White));
				//Bitmap bmp = new Bitmap(codeW, codeH - 3);

				//Graphics g = Graphics.FromImage(bmp);
				//填充背景颜色为白色
				//g.Clear(Color.White);

				//画噪线
				for (int i = 0; i < 3; i++)
				{
					int x1 = rnd.Next(codeW);
					int y1 = rnd.Next(codeH);
					int x2 = rnd.Next(codeW);
					int y2 = rnd.Next(codeH);

					image.Mutate(x => x
			//画实线
			.DrawLines(
									color[rnd.Next(color.Length)], //字体颜色
									1,   //字体大小
									new SixLabors.ImageSharp.PointF[]{
										new Vector2(x1, y1),
										new Vector2(x2, y2)
									} //两点一线坐标
							));

					//Color clr = color[rnd.Next(color.Length)];
					//g.DrawLine(new Pen(clr), x1, y1, x2, y2);
				}
				//画验证码
				//string bPath = $"{Directory.GetCurrentDirectory()}font/";
				//string bPath = "C:\\Windows\\Fonts";
				for (int i = 0; i < chkCode.Length; i++)
				{
					string fnt = fonts[rnd.Next(fonts.Length)];

					//var install_Family = new FontCollection().Add(System.IO.Path.Combine(bPath, fnt));
					var fontTmp = new FontCollection();

					//var bPath = Environment.CurrentDirectory;
					//var install_Family = fontTmp.Add($"font/ARIAL.TTF");
					//var install_Family = fontTmp.Add($"ARIAL.TTF");
					var install_Family = fontTmp.Add($"./font/Arial.ttf");
					//var install_Family = fontTmp.Add($"C:/Windows/Fonts/ARIAL.TTF");
					//var install_Family = fontTmp.Add($"C:/Windows/Fonts/Arial/ARIAL.TTF");
					var font = new SixLabors.Fonts.Font(install_Family, fontSize);
					image.Mutate(x => x
						.DrawText(
							chkCode[i].ToString(),   //文字内容
								font,
								color[rnd.Next(color.Length)],
								new Vector2((float)i * 20, (float)0))
						);

					//将文字写到画布上
					//Font ft = new Font(fnt, fontSize);
					//   Color clr = color[rnd.Next(color.Length)];
					//   g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0);
				}

				//画图片的前景噪音点
				for (int i = 0; i < 15; i++)
				{
					int x1 = rnd.Next(codeW);
					int y1 = rnd.Next(codeH);
					int x2 = x1 + 2;
					int y2 = y1 + 2;

					image.Mutate(x => x
			//画实线
			.DrawLines(
									color[rnd.Next(color.Length)], //字体颜色
									2,   //字体大小
									new SixLabors.ImageSharp.PointF[]{
										new Vector2(x1, y1),
										new Vector2(x2, y2)
									} //两点一线坐标
							));
				}

				//SixLabors.ImageSharp.Formats.Png.PngTextData
				//IImageFormat bFormat = new Formats;
				//ImgStr = image.ToBase64String(SixLabors.ImageSharp.Formats.Png.PngFormat.Instance);

				image.SaveAsJpeg($"./img/test.jpg");

				System.Drawing.Image bImg = System.Drawing.Image.FromFile($"./img/test.jpg");

				pictureBox1.Image = bImg;
			}
			catch (Exception ex)
			{
				string aMsg = ex.Message;
			}
		}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119

blazor server实现

1.新建Blazor Server项目

2.使用Nuget安装相关程序包,SixLabors.ImageSharp和SixLabors.ImageSharp.Drawing(这个使用的是预发行版)

3.在wwwroot中放置字体文件

4.修改Index.razor文件,准备实现生成图片,字体按照相对路径可以进行寻找

@page "/"
@using SixLabors.Fonts;
@using SixLabors.ImageSharp.Drawing.Processing;
@using System.Numerics;

<PageTitle>ImageSharp生成图片</PageTitle>

<button @onclick=CreateImg>生成图片</button>
<img src="@ImgStr"/>
<div>@Yzm</div>
@code{
  public string ImgStr;
  public string Yzm;

  public void CreateImg()
  {

    int codeW = 100;
    int codeH = 36;
    int fontSize = 32;
    string chkCode = string.Empty;
    SixLabors.ImageSharp.Color[] color = { SixLabors.ImageSharp.Color.Black, SixLabors.ImageSharp.Color.Red, SixLabors.ImageSharp.Color.Blue, SixLabors.ImageSharp.Color.Green, SixLabors.ImageSharp.Color.Orange, SixLabors.ImageSharp.Color.Brown, SixLabors.ImageSharp.Color.DarkBlue };
    //string[] font = { "Times New Roman" };
    //需要将字体放到项目中
    string[] fonts = { "Arial.ttf" };
    char[] character = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
    //生成验证码字符串
    Random rnd = new Random();
    for (int i = 0; i < 4; i++)
    {
      chkCode += character[rnd.Next(character.Length)];
    }
    //写入Session用于验证码校验,可以对校验码进行加密,提高安全性
    //System.Web.HttpContext.Current.Session["verifyCode"] = chkCode;
    try
    {
      //创建画布
      var image = new Image<Rgba32>(codeW, codeH);
      image.Mutate(x => x.BackgroundColor(SixLabors.ImageSharp.Color.White));
      //Bitmap bmp = new Bitmap(codeW, codeH - 3);

      //Graphics g = Graphics.FromImage(bmp);
      //填充背景颜色为白色
      //g.Clear(Color.White);

      //画噪线
      for (int i = 0; i < 3; i++)
      {
        int x1 = rnd.Next(codeW);
        int y1 = rnd.Next(codeH);
        int x2 = rnd.Next(codeW);
        int y2 = rnd.Next(codeH);

        image.Mutate(x => x
    //画实线
    .DrawLines(
                color[rnd.Next(color.Length)], //字体颜色
                1,   //字体大小
                new SixLabors.ImageSharp.PointF[]{
                    new Vector2(x1, y1),
                    new Vector2(x2, y2)
                } //两点一线坐标
            ));

        //Color clr = color[rnd.Next(color.Length)];
        //g.DrawLine(new Pen(clr), x1, y1, x2, y2);
      }
      //画验证码
      //string bPath = $"{Directory.GetCurrentDirectory()}font/";
      //string bPath = "C:\\Windows\\Fonts";
      for (int i = 0; i < chkCode.Length; i++)
      {
        string fnt = fonts[rnd.Next(fonts.Length)];

        //var install_Family = new FontCollection().Add(System.IO.Path.Combine(bPath, fnt));
        var fontTmp = new FontCollection();

        //var bPath = Environment.CurrentDirectory;
        //var install_Family = fontTmp.Add($"font/ARIAL.TTF");
        //var install_Family = fontTmp.Add($"ARIAL.TTF");
        var install_Family = fontTmp.Add($"./wwwroot/font/Arial.ttf");
        //var install_Family = fontTmp.Add($"C:/Windows/Fonts/ARIAL.TTF");
        //var install_Family = fontTmp.Add($"C:/Windows/Fonts/Arial/ARIAL.TTF");
        var font = new SixLabors.Fonts.Font(install_Family, fontSize);
        image.Mutate(x => x
          .DrawText(
            chkCode[i].ToString(),   //文字内容
              font,
              color[rnd.Next(color.Length)],
              new Vector2((float)i * 20, (float)0))
          );

        //将文字写到画布上
        //Font ft = new Font(fnt, fontSize);
        //   Color clr = color[rnd.Next(color.Length)];
        //   g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0);
      }

      //画图片的前景噪音点
      for (int i = 0; i < 15; i++)
      {
        int x1 = rnd.Next(codeW);
        int y1 = rnd.Next(codeH);
        int x2 = x1 + 2;
        int y2 = y1 + 2;

        image.Mutate(x => x
    //画实线
    .DrawLines(
                color[rnd.Next(color.Length)], //字体颜色
                2,   //字体大小
                new SixLabors.ImageSharp.PointF[]{
                    new Vector2(x1, y1),
                    new Vector2(x2, y2)
                } //两点一线坐标
            ));
      }

      //SixLabors.ImageSharp.Formats.Png.PngTextData
      //IImageFormat bFormat = new Formats;
      //ImgStr = image.ToBase64String(SixLabors.ImageSharp.Formats.Png.PngFormat.Instance);

      //保存成文件
      //image.SaveAsJpeg($"./wwwroot/img/test.jpg");

      //保存成base64字符串
      using var memoryStream = new MemoryStream();
      image.Save(memoryStream, SixLabors.ImageSharp.Formats.Png.PngFormat.Instance);
      var base64String = Convert.ToBase64String(memoryStream.ToArray());
      ImgStr = $"data:image/jpeg;base64,{base64String}";
      Yzm = chkCode;

    }
    catch (Exception ex)
    {
      string aMsg = ex.Message;
    }
	}

}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142

5.可以正常保存,生成相关图片

blazor webAssembly 实现

1.新建项目

2.使用Nuget安装相关程序包,SixLabors.ImageSharp和SixLabors.ImageSharp.Drawing(这个使用的是预发行版)

3.在wwwroot中放置字体文件

4.修改Index.razor文件,准备实现生成图片,同样的代码,使用上面的那种方式,总是找不到路径,不太理解其运行机制。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/125125
推荐阅读
  

闽ICP备14008679号