一、关于保存图像和屏幕截图
概述:上午调试一个可以截屏(截取软件界面)并保存到指定文件夹的Demo功能,截图功能比较顺利,在图像保存的时候出了点问题 代码如下:
// 存储 Image
string filePath = Path.Combine(Application.StartupPath,"image1");
Directory.GetParent(filePath).Create();
img.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
二、相关现象:
代码执行后生成:
这明显不是想得到的图像文件,查看其文件类型就是:文件 ,而非设定的jpeg类型图片,但通过画图软件打开确实是图片。
后来查找问题发现,原来是 代码: string filePath = Path.Combine(Application.StartupPath,"image1"); 没有给文件标注文件类型
应该修改为: string filePath = Path.Combine(Application.StartupPath,"image1.jpeg");
这样会生成正常图像类型:
三、问题总结及思考记录
这也让我想到之前的一个问题 记录如下:
记录一:有个文件是不带后缀(.txt)通过 Path.Combine组合出文件名称 不带后缀(.txt) 而后用StreamReader打开文件没有问题,后来有了带后缀(.txt)的文件还用这种方法,就会报错,必须获得其全称。
记录二:通过大小对比,同样尺寸的png图像是jpeg格式图像大小的近 3倍
四、主要功能代码
- 下面是这次Demo的主要功能代码如下:
-
private void btnPrint_Click(object sender, EventArgs e) { int width = this.ClientSize.Width; int height = this.ClientSize.Height; Size size = this.ClientSize; // 获取窗口位置 int x = this.Location.X; int y = this.Location.Y; Bitmap img = new Bitmap(this.Width, this.Height); Graphics g = Graphics.FromImage(img); g.CopyFromScreen(this.Location.X + 1, this.Location.Y + 1, 0, 0, this.Size); //g.CopyFromScreen(new Point(x, y), new Point(0, 0), this.Size); // 存储 Image string filePath = Path.Combine(Application.StartupPath,"image1.jpeg"); Directory.GetParent(filePath).Create(); img.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg); //MemoryStream msNewImage = new MemoryStream(); //img.Save(msNewImage, System.Drawing.Imaging.ImageFormat.Jpeg); //System.IO.File.WriteAllBytes(filePath, msNewImage.ToArray()); //Form1 body = new Form1(); //body.BackgroundImage = img; //body.Show(); }
界面