tijian_tieying/winform/photo/Photo_Form2.cs

504 lines
21 KiB
C#
Raw Permalink Normal View History

2025-02-20 12:01:17 +08:00
using AForge.Controls;
using AForge.Video.DirectShow;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
namespace photo
{
public partial class Photo_Form2 : Form
{
//250 350
private FilterInfoCollection videoDevices;//所有摄像设备
private VideoCaptureDevice videoDevice;//摄像设备
private VideoCapabilities[] videoCapabilities;//摄像头分辨率
public string img64 = "";
public int iActualHeight = 0;//视频流窗口高度
public int iActualWidth = 0;//视频流窗口宽度
//PaintEventArgs e11;
public Photo_Form2()
{
this.StartPosition = FormStartPosition.CenterScreen;//居中显示
InitializeComponent();
Get_Shebei();//得到机器所有接入的摄像设备
Conn_Camera();//连接摄像头
}
public void Get_Shebei()
{
//寻找设备的摄像头,检索分辨率
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (videoDevices.Count != 0)//读取到摄像设备
{
foreach (FilterInfo device in videoDevices)
{
cboVideo.Items.Add(device.Name);//把摄像设备添加到摄像列表中
}
}
else
{
cboVideo.Items.Add("没有找到摄像头");
}
cboVideo.SelectedIndex = 0; //默认选择第一个
if (videoDevices.Count != 0) //读取到摄像设备
{
//获取摄像头
videoDevice = new VideoCaptureDevice(videoDevices[cboVideo.SelectedIndex].MonikerString);
GetDeviceResolution(videoDevice); //获得摄像头的分辨率
}
}
//点击确定按钮
private void btn_queding_Click(object sender, EventArgs e)
{
DisConnect();//断开连接
EnableControlStatus(true);
this.Close();//关闭窗体
}
//点击拍照按钮
private void btn_paizhao_Click(object sender, EventArgs e)
{
try
{
if (videoSourcePlayer1 == null)
{
return;
}
else
{
while (true)
{
//i++;
//创建图像对象
Bitmap img = videoSourcePlayer1.GetCurrentVideoFrame();//拍照
Bitmap imgbitmap = new Bitmap(img);
//Image resizedImage = resizeImage(imgbitmap, new Size(640, 360));//250 350
Image resizedImage = resizeImage(imgbitmap, new Size(iActualWidth, iActualHeight));
//pictureBox2.Image = img;
//保存
//string path = "C:\\PhotoList\\DengJi";
//if (!Directory.Exists(path))
//{
// Directory.CreateDirectory(path);
//}
//path += "\\" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".jpg";
//img.Save(path, ImageFormat.Jpeg);
////计算图片多大
//int Img_Height = videoCapabilities[0].FrameSize.Height;
//int Img_Width = videoCapabilities[0].FrameSize.Width;
//Image originImage = Image.FromFile(path);
//创建矩形对象表示原图上裁剪的矩形区域,这里相当于划定原图上坐标为(10, 10)处50x50大小的矩形区域为裁剪区域
//Rectangle cropRegion = new Rectangle(255, 30, 400, 500);
//Rectangle cropRegion = new Rectangle(250, 30, 180, 300);
int iY = Convert.ToInt32(iActualHeight / 1.4);
int iX = (iActualWidth - iY) / 2;
Rectangle cropRegion = new Rectangle(iX, 0, iY, iActualHeight);
//创建空白画布,大小为裁剪区域大小
Bitmap result = new Bitmap(cropRegion.Width, cropRegion.Height);
//创建Graphics对象并指定要在result目标图片画布上绘制图像
Graphics graphics = Graphics.FromImage(result);
//使用Graphics对象把原图指定区域图像裁剪下来并填充进刚刚创建的空白画布
graphics.DrawImage(resizedImage, new Rectangle(0, 0, cropRegion.Width, cropRegion.Height), cropRegion, GraphicsUnit.Pixel);
//这个时候裁剪区域图片就被填充进result对象中去了可以对其进行保存
//string path12 = "C:\\PhotoList\\DengJi\\" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".jpg";
//result.Save(path12, ImageFormat.Png);
pictureBox1.Image = result;
//返回前端
MemoryStream ms = new MemoryStream();
result.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] photo = ms.GetBuffer();
ms.Close();
//FileStream fs = new FileStream(path12, FileMode.Open, FileAccess.Read);
//byte[] photo = new byte[fs.Length];
//fs.Read(photo, 0, photo.Length);
//fs.Close();
img64 = Convert.ToBase64String(photo);
img64 = "data:image/jpeg;base64," + img64;
break;
#region MyRegion
////原图片文件
//Image fromImage = Image.FromFile(fromImagePath);
////创建新图位图
//Bitmap bitmap = new Bitmap(width, height);
////创建作图区域
//Graphics graphic = Graphics.FromImage(bitmap);
////截取原图相应区域写入作图区
//graphic.DrawImage(fromImage, 0, 0, new Rectangle(offsetX, offsetY, width, height), GraphicsUnit.Pixel);
////从作图区生成新图
//Image saveImage = Image.FromHbitmap(bitmap.GetHbitmap());
////保存图片
//saveImage.Save(toImagePath, ImageFormat.Png);
////释放资源
//saveImage.Dispose();
//graphic.Dispose();
//bitmap.Dispose();
#endregion
}
}
}
catch (Exception)
{
throw;
}
}
public void Conn_Camera()
{
if (videoDevice != null)//如果摄像头不为空
{
videoDevice.VideoResolution = videoCapabilities[comboBox2.SelectedIndex];//摄像头分辨率
videoSourcePlayer1.Size = new System.Drawing.Size(iActualWidth, iActualHeight);//保证画线时大小统一
videoSourcePlayer1.VideoSource = videoDevice;//把摄像头赋给控件
videoSourcePlayer1.Start();//开启摄像头
EnableControlStatus(false);
}
}
//关闭并释放
private void DisConnect()
{
if (videoSourcePlayer1.VideoSource != null)
{
videoSourcePlayer1.SignalToStop();
videoSourcePlayer1.WaitForStop();
videoSourcePlayer1.VideoSource = null;
}
}
//控件的显示切换
private void EnableControlStatus(bool status)
{
//cboVideo.Enabled = status;
//pictureBox1.Enabled = status;
//videoSourcePlayer1.Enabled = status;
//videoSourcePlayer1.Enabled = !status;
//btnCut.Enabled = !status;
}
//获得摄像头的分辨率
private void GetDeviceResolution(VideoCaptureDevice videoCaptureDevice)
{
comboBox2.Items.Clear();//清空列表
videoCapabilities = videoCaptureDevice.VideoCapabilities;//设备的摄像头分辨率数组
foreach (VideoCapabilities capabilty in videoCapabilities)
{
//把这个设备的所有分辨率添加到列表
comboBox2.Items.Add($"{capabilty.FrameSize.Width} x {capabilty.FrameSize.Height}");
}
comboBox2.SelectedIndex = 0;//默认选择第一个
SetVideoSourcePlayer1Size(videoCapabilities[0].FrameSize.Width, videoCapabilities[0].FrameSize.Height);
}
//设置视频流窗口大小
private void SetVideoSourcePlayer1Size(int iWidth, int iHeight)
{
while (iWidth > 500)
{
iWidth = iWidth / 2;
iHeight = iHeight / 2;
}
videoSourcePlayer1.Width = iWidth;
videoSourcePlayer1.Height = iHeight;
iActualWidth = iWidth;
iActualHeight = iHeight;
pictureBox1.Height = iActualHeight;
pictureBox1.Width = Convert.ToInt32(iActualHeight / 1.4);//1寸照片
}
public static Image resizeImage(Image imgToResize, Size size)
{
return (Image)(new Bitmap(imgToResize, size));
}
public static void image(string Path1)
{
System.Drawing.Image img = System.Drawing.Image.FromFile(Path1);
Bitmap bt = new Bitmap(img);
//获取图片位置颜色
Color cl = bt.GetPixel(10, 10);
int Width = img.Width;
int Height = img.Height;
int marginx = Height / 2;
float dpiX = img.HorizontalResolution;
float dpiY = img.VerticalResolution;
//设置新图的大小
Bitmap bitmap = new Bitmap(Width, Width, PixelFormat.Format24bppRgb);
//设置位图文件的水平和垂直分辨率与Img一致
bitmap.SetResolution(dpiX, dpiY);
//在位图文件上填充一个新图
Graphics graphics = Graphics.FromImage(bitmap);
System.Drawing.Rectangle Rec = new System.Drawing.Rectangle(0, 0, Width, Width);
//定义颜色
SolidBrush mySolidBrush = new SolidBrush(cl);
//将新图填充为获取原图位置的颜色
graphics.FillRectangle(mySolidBrush, Rec);
//向新图中填充Img
graphics.DrawImage(img, 0, marginx, Rec, GraphicsUnit.Pixel);
graphics.Dispose();
GC.Collect();
bitmap.Save("保存图片路径", System.Drawing.Imaging.ImageFormat.Jpeg);
}
private void videoSourcePlayer1_Paint(object sender, PaintEventArgs e)
{
////画矩形
Graphics g1 = e.Graphics;
Pen p2 = new Pen(Color.White, 2);
p2.DashStyle = DashStyle.Dot;
//g1.DrawRectangle(p2, 96, 0, 128, 180);
//g1.DrawRectangle(p2, 124, 0, 178, 250);
int iY = Convert.ToInt32(iActualHeight / 1.4);
int iX = (iActualWidth - iY) / 2;
g1.DrawRectangle(p2, iX, 0, iY, iActualHeight);
/* Graphics g1 = e.Graphics;
//使绘图质量最高,即消除锯齿
g1.SmoothingMode = SmoothingMode.AntiAlias;
g1.InterpolationMode = InterpolationMode.HighQualityBicubic;
g1.CompositingQuality = CompositingQuality.HighQuality;
Pen p = new Pen(Color.Blue, 1);//定义笔的颜色为蓝色大小为2
Brush fillBrush = new SolidBrush(Color.White);
////画直线
//g1.DrawLine(p, 200, 10, 300, 10);//在画板上画直线,起始坐标为(10,10),终点坐标为(100,100)
////画虚线
Pen px = new Pen(Color.White, 2);//定义笔的颜色为蓝色大小为2
px.DashStyle = DashStyle.Dot;//定义虚线的样式为点
//g1.DrawLine(px, 200, 20, 300, 20);
////自定义虚线
//Pen pd = new Pen(Color.Black, 5);//定义笔的颜色为蓝色大小为2
//pd.DashPattern = new float[] { 2, 1 };//设置短划线和空白部分的数组
//g1.DrawLine(pd, 200, 30, 300, 30);
////画箭头,只对不封闭曲线有用
//pd.DashStyle = DashStyle.Solid;//恢复实线
//pd.EndCap = LineCap.ArrowAnchor;//定义线尾的样式为箭头
//g1.DrawLine(pd, 200, 50, 300, 50);
//画圆
g1.DrawEllipse(px, 140, 40, 140, 140);//与椭圆相贴的矩形的坐标,椭圆的长轴,椭圆的短轴*/
//单色填充圆
//g1.FillEllipse(fillBrush, 100, 40, 140, 140);
////画矩形
//Pen p2 = new Pen(Color.Yellow, 4);
//g1.DrawRectangle(p2, 0, 310, 100, 100);
////用渐变色填充
//Rectangle rect = new Rectangle(300, 60, 50, 50);//定义矩形,参数为起点横纵坐标以及其长和宽
//rect.Location = new Point(330, 20);
//LinearGradientBrush b3 = new LinearGradientBrush(rect, Color.Yellow, Color.Black, LinearGradientMode.Horizontal);
//g1.FillRectangle(b3, rect);
////用图片填充
////TextureBrush b2 = new TextureBrush(Image.FromFile(@"e:\picture\1.jpg"));
////rect.Location = new Point(10, 70);//更改这个矩形的起点坐标
////rect.Width = 200;//更改这个矩形的宽来
////rect.Height = 200;//更改这个矩形的高
////g1.FillRectangle(b2, rect);
////绘制字符串
//g1.DrawString("绘制文字", new Font("微软雅黑", 10), fillBrush, new PointF(130, 10));
////画多边形
//Point[] pg = { new Point(0, 76),
// new Point(80, 76),
// new Point(106, 0),
// new Point(130, 76),
// new Point(210, 76),
// new Point(146, 124),
// new Point(170, 200),
// new Point(106, 152),
// new Point(40, 200),
// new Point(66, 124),
//};
//g1.DrawPolygon(p, pg);
////画三维饼状图
//int width = 200;
//int height = 100;
//int x = 440;
//int y = 20;
//Rectangle r = new Rectangle(x, y, width, height);
//Pen p3 = new Pen(Color.Gray);
//for (int i = y; i < 3 * y; i++)
//{
// Rectangle tempR = new Rectangle(x, i, width, height);
// g1.DrawEllipse(p3, tempR);
//}
//Brush b = new SolidBrush(Color.Gainsboro);
//g1.FillPie(b, r, 0, 360);//笔刷,基础矩形,扫过的角
//b = new SolidBrush(Color.Blue);
//g1.FillPie(b, r, 60, 150);
//b = new SolidBrush(Color.Yellow);
//g1.FillPie(b, r, 210, 150);//从210°开始掠过150度
//Bitmap image = new Bitmap(500, 500);
//Graphics g = Graphics.FromImage(image);
//g.DrawEllipse(p, 200, 90, 100, 100);//与椭圆相贴的矩形的坐标,椭圆的长轴,椭圆的短轴
////单色填充圆
//g.FillEllipse(fillBrush, 200, 90, 100, 100);
////image.Save(@"c:\1.jpg");
#region
//pictureBox1.Image = (Image)image;
//pictureBox1.Image.Save(@"c:\1.jpg");
//pictureBox1.Show();
#endregion
//g1.Dispose();//释放由Graphics使用的资源
//p.Dispose();
}
#region
//protected override void OnPaint(PaintEventArgs e)
//{
// base.OnPaint(e);
// int width = this.Width;
// int height = this.Height;
// int radius = width < height ? width : height;//以最短的边最为圆的直径
// Graphics graphics = this.CreateGraphics();
// //graphics.Clear( Color .FromArgb (255,240,240,240) );
// Rectangle rectangle = new Rectangle(0, 0, radius, radius);
// graphics.SmoothingMode = SmoothingMode.AntiAlias;//消除锯齿
// Brush brush = new SolidBrush(Color.Blue);//指定画刷的颜色
// graphics.FillEllipse(brush, new Rectangle(0, 0, radius, radius));//填充一个圆
// Pen pen = new Pen(Color.Black, 2);//指定画笔的颜色和线宽
// graphics.DrawEllipse(pen, rectangle);//绘制圆的边界
// string text = this.Text;
// brush = new SolidBrush(Color.Black);//指定画刷画文本的颜色
// Font font = this.Font;
// StringFormat sf = new StringFormat();
// sf.Alignment = StringAlignment.Center;//字符水平对齐方式
// sf.LineAlignment = StringAlignment.Center;//字符垂直对齐方式
// graphics.DrawString(text, font, brush, new RectangleF(0, 0, radius, radius), sf);
// #region 使控件的单击事件只在圆内触发而不是在矩形控件范围内触发消除在圆外和控件内的区域响应单机事件的bug
// System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
// path.AddEllipse(0, 0, radius, radius);
// this.Region = new Region(path);
// #endregion
// //font.Dispose();//当控件的size改变时如果调用了 font.Dispose()那么font.Height会报异常因为没有重新实例化font类导致DrawString会报参数无效所以也可以不调用font.dispose这样就可以不用捕获异常了
// brush.Dispose();
// pen.Dispose();
// graphics.Dispose();
//}
#endregion
//点击关闭按钮时触发此函数。
//This event happened when the user closing the main form.
private void MainForm_Closing(object sender, CancelEventArgs e)
{
DisConnect();//断开连接
}
private void Photo_Form2_Load(object sender, EventArgs e)
{
//regist the form closing event.
//注册窗体关闭事件。
this.FormClosing += new FormClosingEventHandler(MainForm_Closing);
}
//------2023-10-19 xulu 添加上传图片功能-------
private Thread invokeThread;
private OpenFileDialog openFileDialog1;
private DialogResult result;
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "图片文件(*.jpg,*.png)|*.jpg;*.png";
invokeThread = new Thread(new ThreadStart(InvokeMethod));
invokeThread.SetApartmentState(ApartmentState.STA);
invokeThread.Start();
invokeThread.Join();
if (result == DialogResult.OK)
{
if (openFileDialog1.FileName != "")
{
string file = openFileDialog1.FileName;//文件夹路径
string path = file.Substring(file.LastIndexOf("\\") + 1); //格式化处理,提取文件名
//File.Copy(file, Application.StartupPath + "\\cai\\" + lujin, false); //复制到的目录切记要加文件名!!!
//PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; //使图像拉伸或收缩以适合PictureBox
this.pictureBox1.ImageLocation = file;
//返回前端
Bitmap bmp = new Bitmap(file);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
ms.Close();
string base64string = Convert.ToBase64String(arr);
img64 = "data:image/jpeg;base64," + base64string;
}
}
}
private void InvokeMethod()
{
result = openFileDialog1.ShowDialog();
}
//-----------------------------------------------------
}
}