Replies: 2 comments 13 replies
-
Without the source image and your code no one can help you. |
Beta Was this translation helpful? Give feedback.
1 reply
-
This is the code. using SixLabors.Fonts;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
namespace Common
{
public class ValidateCodeHelper
{
public static string CreateValidateString()
{
string chkCode = string.Empty;
//验证码的字符集,去掉了一些容易混淆的字符
char[] character = { '2', '3', '4', '5', '6', '8', '9', 'a', '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)];
}
return chkCode;
}
public static byte[] CreateValidateCodeBuffer(string chkCode)
{
int codeW = 90;
int codeH = 30;
int fontSize = 24;
Random rnd = new Random();
//颜色列表,用于验证码、噪线、噪点
Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Brown, Color.DarkBlue };
//字体列表,用于验证码
string[] font = { "Times New Roman", "Verdana", "Arial", "Impact" };
//创建画布
using Image img = new Image<Rgba32>(codeW, codeH);
img.Mutate(ctx =>
{
//白底背景
ctx.Fill(Color.White);
//画验证码
for (int i = 0; i < chkCode.Length; i++)
{
string fnt = font[rnd.Next(font.Length)];
Font ft = SystemFonts.CreateFont(fnt, fontSize);
Color clr = color[rnd.Next(color.Length)];
ctx.DrawText(chkCode[i].ToString(), ft, clr, new PointF(18 * i + 10, rnd.Next(1, 2)));
}
//画干扰线
for (int i = 0; i < 2; i++)
{
int x1 = rnd.Next(codeW);
int y1 = rnd.Next(codeH);
int x2 = rnd.Next(codeW);
int y2 = rnd.Next(codeH);
Color clr = color[rnd.Next(color.Length)];
var p1 = new PointF(x1, y1);
var p2 = new PointF(x2, y2);
var pen = new Pen(clr, 1);
ctx.DrawLines(pen, p1, p2);
}
//画噪点
for (int i = 0; i < 24; i++)
{
int x = rnd.Next(codeW);
int y = rnd.Next(codeH);
Color clr = color[rnd.Next(color.Length)];
var p1 = new PointF(x, y);
var p2 = new PointF(p1.X + 0.5f, p1.Y + 0.5f);
var pen = Pens.Dot(clr, 1);
ctx.DrawLines(pen, p1, p2);
}
//改变大小
//ctx.Resize(img.Width * 4, img.Height * 4);
});
using MemoryStream ms = new MemoryStream();
//JpegEncoder encoder = new JpegEncoder()
//{
// //标准中定义的0到100之间的质量值。默认值为75。
// //通过减少Quality松散的信息,从而减小文件大小。
// Quality = 100
//};
//img.SaveAsJpeg(ms, encoder);
PngEncoder encoder = new PngEncoder()
{
CompressionLevel = PngCompressionLevel.NoCompression,
BitDepth = PngBitDepth.Bit16,
ColorType = PngColorType.RgbWithAlpha
};
img.SaveAsPng(ms, encoder);
return ms.ToArray();
}
}
} |
Beta Was this translation helpful? Give feedback.
12 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Beta Was this translation helpful? Give feedback.
All reactions