随机生成图片验证码

该博客介绍了一段C++代码,用于利用OpenCV库生成带有随机线条、文字和干扰元素的彩色验证码图像。代码中定义了背景、线条、文字和干扰项的绘制函数,并提供了设置颜色和样式的灵活性。生成的图像可以展示并保存为JPEG格式。
摘要由CSDN通过智能技术生成

输出图片效果

代码 main.cpp

#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>

// 创建工程添加包含路径
// 并添加opencv相关链接库!!

using namespace cv;
using namespace std;

#define COUT_H cout << "\n[" __FILE__ ":" << __LINE__ << "]" __FUNCTION__ "()"

#define out_num 10

#define window_height 60
#define window_width 180
#define height_width (window_height + window_width)

#define colour 1 // 1彩色 0黑白

int random(int a, int b)
{
	return a == b ? a : (int)(rand() % (b - a) + a);
}

Scalar randomColor(int l = 0, int r = 255)
{
#if colour
	return Scalar(random(l, r), random(l, r), random(l, r));
#else // 黑白
	int icolor = random(l, r);
	return Scalar(icolor, icolor, icolor);
#endif
}


// 背景
// l r 颜色随机范围0-255
int Drawing_Random_Bg(Mat image, int l = 0, int r = 255)
{
	for (int i = 0; i < image.rows; i++)
	{
		for (int j = 0; j < image.cols; j++)
		{
			image.at<Vec3b>(i, j)[0] = random(l, r);
#if colour
			image.at<Vec3b>(i, j)[1] = random(l, r);
			image.at<Vec3b>(i, j)[2] = random(l, r);
#else
			image.at<Vec3b>(i, j)[1] = image.at<Vec3b>(i, j)[0];
			image.at<Vec3b>(i, j)[2] = image.at<Vec3b>(i, j)[0];

#endif
		}
	}
	return 0;
}

// 画线
int Drawing_Random_Lines(Mat image, int l = 0, int r = 255)
{
	int lineType = 8;

	int lineSizeMin = 1;
	int lineSizeMax = 3;

	// 纵向
	int lineNum = random(5, 8); // 数量
	for (int i = 0; i < lineNum; i++)
	{
		int lineSize = random(lineSizeMin, lineSizeMax); // 粗细

		Point pt1(random(window_width / 10, window_width), 0);
		Point pt2(random(0, window_width * 11 / 10), window_height);
		Scalar scolor = randomColor(l, r);

		line(image, pt1, pt2, scolor, lineSize, lineType);
	}

	// 横向
	lineNum = random(5, 8); // 数量
	for (int i = 0; i < lineNum; i++)
	{
		int lineSize = random(lineSizeMin, lineSizeMax); // 粗细

		Point pt1(0, random(-window_height / 10, window_height * 11 / 10));
		Point pt2(window_width, random(-window_height / 10, window_height * 11 / 10));
		Scalar scolor = randomColor(l, r);

		line(image, pt1, pt2, scolor, lineSize, lineType);
	}
	return 0;
}
string getLetterCode(int len = 4)
{
	//string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	string chars = "0123456789"
		//"abcdefghjklmnpqrstuvwxyz"
		"ABCDEFGHJKLMNPQRSTUVWXYZ";
	string  str = "";

	for (int i = 0; i < len; i++)
	{
		int j = random(0, chars.length());
		str.append(1, chars[j]);
	}
	return str;
}

int Drawing_Random_Text(Mat image, string txt, int type = 0, int l = 0, int r = 255)
{
	int len = txt.length() + 1;

	for (int i = 0; i < txt.length(); i++)
	{
		double x = window_width / len;
		double y = window_height / 10;
		double pos_x = x / 4 + random(x * i, x * i + x / 3);
		double pos_y = random(y * 6, y * 9);

		string tempChar = txt.substr(i, 1);


		int font_face = FONT_HERSHEY_TRIPLEX;
		double font_scale = random(15, 17);

		int thickness = 2;
		int lineType = LINE_AA;
		if (type == 0)
		{
			font_scale /= 10;
		}
		else
		{
			font_scale = 0.6f;
			pos_x = random(window_width / 100, window_width * 80 / 100);
			pos_y = random(y * 3, y * 10);

			int thickness = 1;
			lineType = LINE_8;
		}

		Point origin(pos_x, pos_y);
		Scalar scolor = randomColor(l, r);

		putText(image, tempChar, origin, font_face, font_scale, scolor, thickness, lineType, 0);
	}
	return 0;
}

// 画干扰
int Drawing_Random_disturb(Mat image, int l = 0, int r = 255)
{
	int per = 100;

	// 线
	int lineNum = random(4, 6); // 数量
	for (int i = 0; i < lineNum; i++)
	{
		Point pt1(random(0, window_width * 70 / 100), random(0, window_height * 90 / 100));
		int rdx = random(window_width * 20 / per, window_width * 50 / per);
		int rdy = random(-window_width * 20 / per, window_width * 20 / per);

		int lineSize = random(1, 3);

		Point pt2(pt1.x + rdx, pt1.y + rdy);
		Scalar scolor = randomColor(l, r);

		line(image, pt1, pt2, scolor, lineSize, LINE_8);
	}
	return 0;
}

// 画边框
int Drawing_Random_frame(Mat image, int l = 0, int r = 255)
{
	int siz = height_width * 1 / 100;
	if (siz < 2)
	{
		siz = 2;
	}

	Scalar scolor = randomColor(l, r);

	Point pt1(0, 0);
	Point pt2(window_width - siz / 2, window_height - siz / 2);

	rectangle(image, pt1, pt2, scolor, siz, 8);

	return 0;
}

int main(void)
{
	std::srand(time(0));

	Mat img[out_num];

	for (int i = 0; i < out_num; i++)
	{
		img[i] = Mat::zeros(window_height, window_width, CV_8UC3);

		Drawing_Random_Bg(img[i], 220, 250);	// 背景用淡一点的颜色
		Drawing_Random_Lines(img[i], 180, 250);

		string str = getLetterCode(5);
		Drawing_Random_Text(img[i], str, 0, 10, 150);

		Drawing_Random_disturb(img[i], 10, 150);
		Drawing_Random_frame(img[i], 100, 150);

		Drawing_Random_Text(img[i], getLetterCode(3), 1, 50, 200);

		COUT_H << "str=" << str;

#if 1
		imshow(str, img[i]);
		waitKey(0);
#else
		std::vector<int> vct = { IMWRITE_JPEG_QUALITY , 60 }; // 输出图片质量
		imwrite("..\\..\\output\\" + str + ".jpg", img[i], vct); // 注意创建output文件夹!
#endif
	}

	system("pause");
	return (0);
}

	

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
随机生成6位图片验证码. /// <summary> /// PicHandler1 的摘要说明 /// </summary> public class PicHandler1 : IHttpHandler, IRequiresSessionState { private string mCheckNo = string.Empty; protected ImgBuilder _ImgBuilder = new ImgBuilder(); protected VryImgGen _ImgBuilderNew = new VryImgGen(); private string _text = string.Empty; private string _font = "宋体"; private int _fontSize = 8; private int _padding = 2; public void ProcessRequest(HttpContext context) { mCheckNo = DisCheckNo(); context.Session["CheckCode"] = mCheckNo; this._ImgBuilder.FontSize = this._fontSize; this._ImgBuilder.Padding = this._padding; if (!string.IsNullOrEmpty(this._font)) { this._ImgBuilder.Fonts = new string[] { this._font }; } this._ImgBuilderNew.ChaosWight = 40; this._ImgBuilderNew.FontSize = 25; this._ImgBuilderNew.Padding = 3; System.Drawing.Bitmap image = this._ImgBuilderNew.CreateImage(mCheckNo); System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); context.Response.ClearContent(); context.Response.ContentType = "image/Jpeg"; context.Response.BinaryWrite(ms.ToArray()); context.Session["CheckCode"] = mCheckNo.ToString(); //如果没有实现IRequiresSessionState,则这里会出错,也无法生成图片 context.Response.End(); } //验证码生成 protected string DisCheckNo() { string hash = HashCode.GetNext(); string CheckNo = string.Empty; Random rd = new Random(DateTime.Now.Millisecond); for (int i = 0; i < 6; i++) { CheckNo += hash.Substring(rd.Next(1, hash.Length - 1), 1); } CheckNo = CheckNo.Replace("0", rd.Next(1, 9).ToString()); CheckNo = CheckNo.Replace("o", rd.Next(1, 9).ToString());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值