1.获取设置图像像素值
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
//获取图像像素值
Color color = new Color();
if (pictureBox1.Image != null)
{
try
{
color = ((System.Drawing.Bitmap)pictureBox1.Image).GetPixel(e.X, e.Y);
this.label4.Text = "(" + e.X.ToString() + "," + e.Y.ToString() + ")";
this.label3.Text= " (" + color.R.ToString() + "," + color.G.ToString() + "," + color.B.ToString() + ")";
}
catch(Exception ex)
{
MessageBox.Show(ex.Message ,"提示信息");
}
}
this.label3.BackColor = color;
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
//设置图像像素值
try
{
int X = e.X, Y = e.Y, Width = 80, Height = 80;
Bitmap target = new Bitmap(Width, Height);
Bitmap source = (Bitmap)(this.pictureBox1.Image);
for (int i = X; i < X + Width; i++)
{
for (int j = Y; j < Y + Height; j++)
{
Color color = source.GetPixel(i, j);
target.SetPixel(i - X, j - Y, color);
}
}
this.pictureBox2.Image = target;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "信息提示");
}
}
2.获取图像信息(尺寸、大小、类型)
private void button1_Click(object sender, EventArgs e)
{
//打开图像文件
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "图像文件(JPeg, Gif)|*.jpg;*.jpeg;*.gif;| JPeg 图像文件(*.jpg;*.jpeg)|*.jpg;*.jpeg |GIF 图像文件(*.gif)|*.gif";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//得到原始大小的图像
MyBitmap = new Bitmap(openFileDialog.FileName);
}
//MyBitmap.Height = pictureBox1.Height;
//MyBitmap.Width = pictureBox1.Width;
this.pictureBox1.Image = MyBitmap;
//图片尺寸
label1.Text = "尺寸:" + MyBitmap.Size.Width +"×"+MyBitmap .Size .Height;
//图片类型
string Type = openFileDialog.FileName.Substring(openFileDialog.FileName.IndexOf('.')+1);
label2.Text = "类型:" + Type.ToUpper()+"图像";
//图片大小
float length = 0;
if (openFileDialog.FileName != "")
{
System.IO.Stream stream = openFileDialog.OpenFile();
length = (float)stream.Length;
}
label3.Text = "大小:" + Math.Round(length/1024f,2)+"MB";
}
3.实现数据库存取图片
private byte[] b;
Stream stream;
private void btnOpen_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF";
openFileDialog1.DefaultExt = "bmp";
openFileDialog1.ShowDialog();
if (openFileDialog1.FileName != "")
{
stream = openFileDialog1.OpenFile();
int length = (int)stream.Length;
b = new byte[length];
stream.Read(b,0,length);
this.pictureBox1.Image = new Bitmap(stream);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
//将图片以Image类型存储到数据库
try
{
SqlConnection con = new SqlConnection("server=a\\mr;uid=sa;pwd=;database=db_13");
SqlDataAdapter da = new SqlDataAdapter("select * from tb_48", con);
SqlCommandBuilder combuilder = new SqlCommandBuilder(da);
da.UpdateCommand = combuilder.GetUpdateCommand();
DataSet ds = new DataSet();
da.Fill(ds);
DataRow newdr = ds.Tables[0].NewRow();
newdr.BeginEdit();
newdr[1] = openFileDialog1.FileName;
newdr[2] = b;
newdr.EndEdit();
ds.Tables[0].Rows.Add(newdr);
da.Update(ds);
MessageBox.Show("保存成功!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "提示信息");
}
}
private void button1_Click(object sender, EventArgs e)
{
//从数据库读取Image类型的字段
SqlConnection con = new SqlConnection("server=a\\mr;uid=sa;pwd=;database=db_13");
SqlDataAdapter da = new SqlDataAdapter("select * from tb_48 where name='"+comboBox1.Text.ToString ()+"'", con);
SqlCommandBuilder combuilder = new SqlCommandBuilder(da);
da.UpdateCommand = combuilder.GetUpdateCommand();
DataSet ds = new DataSet();
da.Fill(ds);
byte[] bytes = (byte[])ds.Tables[0].Rows[0][2];
MemoryStream m = new MemoryStream(bytes);
try
{
Bitmap bitmap = new Bitmap(m);
this.pictureBox1.Image = bitmap;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "提示信息");
}
}
4.绘制柱形图
//绘制柱形图
private void CreateImage()
{
int height = 400, width = 600;
Bitmap image = new Bitmap(width, height);
//创建Graphics类对象
Graphics g = Graphics.FromImage(image);
try
{
//清空图片背景色
g.Clear(Color.White);
Font font = new Font("Arial", 9, FontStyle.Regular);
Font font1 = new Font("宋体", 20, FontStyle.Bold);
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue , Color.BlueViolet, 1.2f, true);
g.FillRectangle(Brushes.WhiteSmoke, 0, 0, width, height);
// Brush brush1 = new SolidBrush(Color.Blue);
g.DrawString("2007年各月份网站流量统计", font1, brush, new PointF(130, 30));
//画图片的边框线
g.DrawRectangle(new Pen(Color.Blue), 0, 0, image.Width - 1, image.Height - 1);
Pen mypen = new Pen(brush, 1);
//绘制线条
//绘制横向线条
int x = 100;
for (int i = 0; i < 11; i++)
{
g.DrawLine(mypen, x, 80, x, 340);
x = x + 40;
}
Pen mypen1 = new Pen(Color.Blue, 2);
g.DrawLine(mypen1, x - 480, 80, x - 480, 340);
//绘制纵向线条
int y = 106;
for (int i = 0; i < 9; i++)
{
g.DrawLine(mypen, 60, y, 540, y);
y = y + 26;
}
g.DrawLine(mypen1, 60, y, 540, y);
//x轴
String[] n = {" 一月", " 二月", " 三月", " 四月", " 五月", " 六月", " 七月",
" 八月", " 九月", " 十月", "十一月", "十二月"};
x = 62;
for (int i = 0; i < 12; i++)
{
g.DrawString(n[i].ToString(), font, Brushes.Black , x, 348); //设置文字内容及输出位置
x = x + 40;
}
//y轴
String[] m = {"100%", " 90%", " 80%", " 70%", " 60%", " 50%", " 40%", " 30%",
" 20%", " 10%", " 0%"};
y = 85;
for (int i = 0; i < 11; i++)
{
g.DrawString(m[i].ToString(), font, Brushes.Black, 25, y); //设置文字内容及输出位置
y = y + 26;
}
int[] Count = new int[12];
string cmdtxt2 = "";
SqlConnection Con = new SqlConnection(ConfigurationManager.AppSettings["ConSql"]);
Con.Open();
SqlDataAdapter da;
DataSet ds=new DataSet();
for (int i = 0; i < 12; i++)
{
cmdtxt2 = "select COUNT(*) AS count, Month( LoginTime) AS month from tb_53 where Year(LoginTime)=2007 and Month(LoginTime)=" + (i + 1) + "Group By Month(LoginTime)";
da = new SqlDataAdapter(cmdtxt2, Con);
da.Fill(ds,i.ToString ());
if (ds.Tables[i].Rows.Count == 0)
{
Count[i] = 0;
}
else
{
Count[i] = Convert.ToInt32(ds.Tables[i].Rows[0][0].ToString()) * 100 / Total();
}
}
//显示柱状效果
x = 70;
for (int i = 0; i < 12; i++)
{
SolidBrush mybrush = new SolidBrush(Color.Blue);
g.FillRectangle(mybrush, x, 340 - Count[i] * 26 / 10, 20, Count[i] * 26 / 10);
x = x + 40;
}
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Response.ClearContent();
Response.ContentType = "image/Jpeg";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
//访问人数统计
public int Total()
{
SqlConnection Con = new SqlConnection(ConfigurationManager.AppSettings["ConSql"]);
Con.Open();
string cmdtxt1 = "select * from tb_53 where Year(LoginTime)=2007";
SqlDataAdapter dap = new SqlDataAdapter(cmdtxt1, Con);
DataSet ds = new DataSet();
dap.Fill(ds);
int P_Int_total = ds.Tables[0].Rows.Count;//访问人数统计
return P_Int_total;
}
5.绘制饼形图
private void CreateImage()
{
//把连接字串指定为一个常量
SqlConnection Con = new SqlConnection("Server=a\\mr;Database=db_13;Uid=sa;Pwd=");
Con.Open();
string cmdtxt = "select * from tb_54";
//SqlCommand Com = new SqlCommand(cmdtxt, Con);
DataSet ds = new DataSet();
SqlDataAdapter Da = new SqlDataAdapter(cmdtxt, Con);
Da.Fill(ds);
Con.Close();
float Total = 0.0f, Tmp;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
//转换成单精度。也可写成Convert.ToInt32
Tmp = Convert.ToSingle(ds.Tables[0].Rows[i]["Quantity"]);
Total += Tmp;
}
//设置字体,fonttitle为主标题的字体
Font fontlegend = new Font("verdana", 9);
Font fonttitle = new Font("verdana", 10, FontStyle.Bold);
//背景宽
int width = 230;
int bufferspace = 15;
int legendheight = fontlegend.Height * (ds.Tables[0].Rows.Count + 1) + bufferspace;
int titleheight = fonttitle.Height + bufferspace;
int height = width + legendheight + titleheight + bufferspace;//白色背景高
int pieheight = width;
Rectangle pierect = new Rectangle(0, titleheight, width, pieheight);
//加上各种随机色
ArrayList colors = new ArrayList();
Random rnd = new Random();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
colors.Add(new SolidBrush(Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255))));
//创建一个bitmap实例
Bitmap objbitmap = new Bitmap(width, height);
Graphics objgraphics = Graphics.FromImage(objbitmap);
//画一个白色背景
objgraphics.FillRectangle(new SolidBrush(Color.White), 0, 0, width, height);
//画一个亮黄色背景
objgraphics.FillRectangle(new SolidBrush(Color.Beige), pierect);
//以下为画饼图(有几行row画几个)
float currentdegree = 0.0f;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
objgraphics.FillPie((SolidBrush)colors[i], pierect, currentdegree,
Convert.ToSingle(ds.Tables[0].Rows[i]["Quantity"]) / Total * 360);
currentdegree += Convert.ToSingle(ds.Tables[0].Rows[i]["Quantity"]) / Total * 360;
}
//以下为生成主标题
SolidBrush blackbrush = new SolidBrush(Color.Black);
string title = " 各类图书销售比例调查";
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
objgraphics.DrawString(title, fonttitle, blackbrush,
new Rectangle(0, 0, width, titleheight), stringFormat);
//列出各字段与得数目
objgraphics.DrawRectangle(new Pen(Color.Black, 2), 0, height - legendheight, width, legendheight);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
objgraphics.FillRectangle((SolidBrush)colors[i], 5, height - legendheight + fontlegend.Height * i + 5, 10, 10);
objgraphics.DrawString(((String)ds.Tables[0].Rows[i]["BookKind"]) + " —— " + Convert.ToString(Convert.ToSingle(ds.Tables[0].Rows[i]["Quantity"]) * 100 / Total).Substring(0, 5) + "%", fontlegend, blackbrush,
20, height - legendheight + fontlegend.Height * i + 1);
}
//图像总的高度-一行字体的高度,即是最底行的一行字体高度(height - fontlegend.Height )
objgraphics.DrawString("图书销售总数:" + Convert.ToString(Total) + "万本", fontlegend, blackbrush, 5, height - fontlegend.Height);
Response.ContentType = "image/Jpeg";
objbitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
objgraphics.Dispose();
objbitmap.Dispose();
}
6.绘制折线图
private void CreateImage()
{
int height = 440, width = 600;
Bitmap image = new Bitmap(width, height);
Graphics g = Graphics.FromImage(image);
try
{
//清空图片背景色
g.Clear(Color.White);
Font font = new System.Drawing.Font("Arial", 9, FontStyle.Regular);
Font font1 = new System.Drawing.Font("宋体", 20, FontStyle.Regular);
Font font2 = new System.Drawing.Font("Arial", 8, FontStyle.Regular);
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.Blue, 1.2f, true);
g.FillRectangle(Brushes.AliceBlue, 0, 0, width, height);
Brush brush1 = new SolidBrush(Color.Blue);
Brush brush2 = new SolidBrush(Color.SaddleBrown);
g.DrawString("1997年-2006年出生人口的男女比例", font1, brush1, new PointF(100, 30));
//画图片的边框线
g.DrawRectangle(new Pen(Color.Blue), 0, 0, image.Width - 1, image.Height - 1);
Pen mypen = new Pen(brush, 1);
Pen mypen2 = new Pen(Color.Red, 2);
//绘制线条
//绘制纵向线条
int x = 60;
for (int i = 0; i < 10; i++)
{
g.DrawLine(mypen, x, 80, x, 340);
x = x + 50;
}
Pen mypen1 = new Pen(Color.Blue, 2);
g.DrawLine(mypen1, x - 500, 80, x - 500, 340);
//绘制横向线条
int y = 106;
for (int i = 0; i < 9; i++)
{
g.DrawLine(mypen, 60, y, 560, y);
y = y + 26;
}
g.DrawLine(mypen1, 60, y, 560, y);
//x轴
String[] n = {"1997年", "1998年", "1999年", "2000年", "2001年", "2002年",
"2003年", " 2004年", "2005年", "2006年"};
x = 45;
for (int i = 0; i < 10; i++)
{
g.DrawString(n[i].ToString(), font, Brushes.Red, x, 348); //设置文字内容及输出位置
x = x + 50;
}
//y轴
String[] m = {"2200人", " 2000人", " 1800人", "1600人", " 1400人", " 1200人", " 1000人", " 800人",
" 600人"};
y = 106;
for (int i = 0; i < 9; i++)
{
g.DrawString(m[i].ToString(), font, Brushes.Red, 10, y); //设置文字内容及输出位置
y = y + 26;
}
int[] Count1 = new int[10];
int[] Count2 = new int[10];
SqlConnection Con = new SqlConnection(ConfigurationManager.AppSettings["ConSql"]);
Con.Open();
string cmdtxt2 = "SELECT * FROM tb_55 WHERE Year<=2006 and Year>=1997";
SqlDataAdapter da = new SqlDataAdapter(cmdtxt2 ,Con);
DataSet ds = new DataSet();
da.Fill(ds);
for (int j = 0; j < 10; j++)
{
if (ds.Tables[0].Rows.Count == 0)
{
Count1[j] = 0;
}
else
{
Count1[j] = Convert.ToInt32(ds.Tables [0].Rows [j][0].ToString ()) * 13 / 100;
}
}
for (int k = 0; k < 10; k++)
{
if (ds.Tables[0].Rows.Count == 0)
{
Count2[k] = 0;
}
else
{
Count2[k] = Convert.ToInt32(ds.Tables[0].Rows[k][1].ToString()) * 13 / 100;
}
}
//显示折线效果
SolidBrush mybrush = new SolidBrush(Color.Red);
Point[] points1 = new Point[10];
points1[0].X = 60; points1[0].Y = 390 - Count1[0];
points1[1].X = 110; points1[1].Y = 390 - Count1[1];
points1[2].X = 160; points1[2].Y = 390 - Count1[2];
points1[3].X = 210; points1[3].Y = 390 - Count1[3];
points1[4].X = 260; points1[4].Y = 390 - Count1[4];
points1[5].X = 310; points1[5].Y = 390 - Count1[5];
points1[6].X = 360; points1[6].Y = 390 - Count1[6];
points1[7].X = 410; points1[7].Y = 390 - Count1[7];
points1[8].X = 460; points1[8].Y = 390 - Count1[8];
points1[9].X = 510; points1[9].Y = 390 - Count1[9];
g.DrawLines(mypen2, points1); //绘制折线
Pen mypen3 = new Pen(Color.Black, 2);
Point[] points2 = new Point[10];
points2[0].X = 60; points2[0].Y = 390 - Count2[0];
points2[1].X = 110; points2[1].Y = 390 - Count2[1];
points2[2].X = 160; points2[2].Y = 390 - Count2[2];
points2[3].X = 210; points2[3].Y = 390 - Count2[3];
points2[4].X = 260; points2[4].Y = 390 - Count2[4];
points2[5].X = 310; points2[5].Y = 390 - Count2[5];
points2[6].X = 360; points2[6].Y = 390 - Count2[6];
points2[7].X = 410; points2[7].Y = 390 - Count2[7];
points2[8].X = 460; points2[8].Y = 390 - Count2[8];
points2[9].X = 510; points2[9].Y = 390 - Count2[9];
g.DrawLines(mypen3, points2); //绘制折线
//绘制标识
g.DrawRectangle(new Pen(Brushes.Red), 150, 370, 250, 50); //绘制范围框
g.FillRectangle(Brushes.Red, 250, 380, 20, 10); //绘制小矩形
g.DrawString("女孩", font2, Brushes.Red, 270, 380);
g.FillRectangle(Brushes.Black, 250, 400, 20, 10);
g.DrawString("男孩", font2, Brushes.Black, 270, 400);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Response.ClearContent();
Response.ContentType = "image/Jpeg";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
7.随机验证码
一、不重复随机数的生成
1.用一个列表,选出一个删掉一个
核心思想:list存放所有的数,用rnd随机数指定list的下标的数;随机一次,将list里的数删除。
如从M个数里取N个不重复的数,则循环N次即可(maxvalue = M,M-1,....M-N+1).
///
/// 生成最大值范围内无重复值的长度为最大值的随机序列,例:6,则返回0,1,2,3,4,5 的List
///
///
///
public static List
GetRandomList(this int maxValue)
{
if (maxValue == 0)
{
return null;
}
//逻辑描述:生成从0开始到maxValue的tempList
//然后random一次就maxValue--,并将random出来的整数用做索引,加入到returnList并从tempList中移除
maxValue = Math.Abs(maxValue);//防止负数
List
tempList = new List
();
for (int i = 0; i < maxValue; i++)
{
tempList.Add(i);
}
Random rd = new Random();
List
returnList = new List
(); while (maxValue > 0) { int tempInt = 0; if (maxValue > 1)//当maxValue为1时,不再进行随机,因为还剩一个数字,无需随机 { tempInt = rd.Next(maxValue); } returnList.Add(tempList[tempInt]); tempList.RemoveAt(tempInt); maxValue--; } return returnList; } 2.直接判断,重复则继续随机 // 抽奖范围 int range = 100; // 抽奖个数 int lotteryNum = 10; // 中奖号码 List
l = new List
(); Random r = new Random(); while (l.Count != lotteryNum) { int n = r.Next(1, range); if (l.Contains(n)) continue; l.Add(n); } 二、关于随机数 Random r = new Random(l); int n = r.Next(m, n); 参数l:表示种子数,默认为系统时间; 结论:产生的随机数序列由 l,m,n 三个参数共同决定,只要这三个参数完全相同,则产生的随机数序列完全相同! 三、应用:生成随机验证码图片 public partial class Form1 : Form { public Form1() { InitializeComponent(); } char[] pattern = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; //或者写为 //string s = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // char[] Pattern = s.ToCharArray(); ///
/// 产生不重复的随机字符串 /// ///
字符串长度 string CreateStr(int strLenth) { List
list = new List
(); list.AddRange(pattern); strLenth = Math.Min(strLenth, list.Count); //防止溢出 string resultStr = ""; Random rand = new Random(); for(int i=0;i
/// 根据字符串绘制图片 /// ///
目标字符串 private int letterWidth = 100; //单个字体的最大宽度和高度 private int letterHight = 30; private Bitmap CreateImage(string strCode) { int iRandAngle = 35; //字符最大的旋转角度 Bitmap image = new Bitmap(letterWidth, letterHight); //创建图片背景 Graphics g = Graphics.FromImage(image); g.Clear(Color.AliceBlue); //用系统的颜色清除画面并填充背景 Rectangle rect = new Rectangle(0,0,image.Width - 1,image.Height-1); //画一个边框 g.DrawRectangle(new Pen(Color.Black, 0), rect); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; //指定画面呈现模式——消除锯齿 //生成背景噪点 Random rand = new Random(); Pen blackPen = new Pen(Color.LightGray, 0); for(int i = 0;i<150;i++) { int x = rand.Next(image.Width); int y = rand.Next(image.Height); g.DrawRectangle(blackPen, x, y, 1, 1); //汇点 } ///绘制验证码(旋转) //可能用到的颜色和字体(随机) Color[] color = new Color[] { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.Purple }; string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" }; //定义文字格式——居中对齐 StringFormat format = new StringFormat(StringFormatFlags.NoClip); //允许延伸 format.Alignment = StringAlignment.Center; //设置垂直面上的对其方式 format.LineAlignment = StringAlignment.Center; //水平 char[] strChar = strCode.ToCharArray(); //将字符串拆分成字符数组 for(int i =0;i
< code>