C#图像处理学习笔记(屏幕截取,打开保存图像、旋转图像、黑白、马赛克、降低亮度、浮雕)

news2024/11/16 4:42:41
1、创建Form窗体应用程序

         打开VS,创建新项目-语言选择C#-Window窗体应用(.NET Framework)

         如果找不到,检查一下有没有安装.NET 桌面开发模块,如果没有,需要下载,记得勾选相关开发工具

         接上一步,选择windows窗体应用程序之后,点击下一步,修改相关路径和名字之后,点击创建。就可以得到一个如下的form设计界面。

 2、使用到的程序包和控件
        2.1、程序包

                使用到Nuget程序包中的System.Drawing.Common,下载方式如下:

        2.2、控件

                通过视图-工具箱,把工具箱调出来,在工具箱选择需要的控件。

        1)、此功能会运用openFileDialog、saveFileDialog、Button、Picturebox、label控件

        2)、在Form设计界面布置界面,加入图片文件的Picturebox1控件,处理图片后显示图片的Picturebox2控件。 

        3)、一个openFileDialog控件,两个saveFileDialog控件

        4)、接下来布置按钮,Button1:“打开”,Button2:“保存”,Button3:“添加暗角”,Button4:“降低亮度”,Button5:“去色”,Button6:“浮雕”,Button7:“马赛克”,Button8:“扩散”,Button9:“清除图片”,Button10:“保存2”,Button11:“油画效果”,Button12:“柔化”,Button13:“截屏”,Button14:“旋转90”。

        5)、label控件。改名为:运行时间

        提示:右键控件属性,即可改名

界面如下:

 3、代码实现
        3.1、Button1打开按钮
   //打开按钮
   private void button1_Click(object sender, EventArgs e)
   {
       if (openFileDialog1.ShowDialog() == DialogResult.OK)
       {
           //获取打开文件的路径
           string path = openFileDialog1.FileName;
           bitmap = (Bitmap) Bitmap.FromFile(path);
           pictureBox1.Image = bitmap.Clone() as Image;
       }
   }
         3.2、Button2保存按钮
    //保存按钮
    private void button2_Click(object sender, EventArgs e)
    {
        bool isSvae = true;
        if(saveFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string fileName = saveFileDialog1.FileName.ToString();
            if(fileName != "" && fileName != null)
            {
                //获取文件格式
                string fileExtName = fileName.Substring(fileName.LastIndexOf('.') + 1).ToString();
                System.Drawing.Imaging.ImageFormat imgformat = null;
                if(fileExtName != "")
                {
                    //确定文件格式
                    switch (fileExtName)
                    {
                        case "jpg":
                            imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
                            break;
                        case "bmp":
                            imgformat = System.Drawing.Imaging.ImageFormat.Bmp;
                            break;
                        case "gif":
                            imgformat = System.Drawing.Imaging.ImageFormat.Gif;
                            break;
                        default:
                            MessageBox.Show("只能存储为:jpg,bmp, gif 格式");
                            isSvae = false;
                            break;
                    }
                 }

                //默认保存为jpg格式
                if(imgformat == null)
                {
                    imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
                }

                if(isSvae)
                {
                    try
                    {
                        pictureBox2.Image.Save(fileName, imgformat);
                        MessageBox.Show("图片保存成功!");
                    }
                    catch
                    {
                        MessageBox.Show("保存失败! 你还没有截取过图片或者图片已经清空!");
                    }
                }
            }
        }
    }
        3.3、Button3添加暗角按钮
  //添加暗角按钮
  private void button3_Click(object sender, EventArgs e)
  {
      if (bitmap != null)
      {
          newbitmap = bitmap.Clone() as Bitmap;
          
          sw.Reset();
          sw.Restart();

          int width = newbitmap.Width;
          int height = newbitmap.Height;
          float cx = width / 2;
          float cy = height / 2;
          float maxDist = cx * cx + cy * cy;
          float currDist = 0, factor;
          Color pixel;

          for (int i = 0; i < width; i++)
          {
              for (int j = 0; j < height; j++)
              {
                  currDist = ((float)i - cx) * ((float)i - cx) + ((float)j - cy) * ((float)j - cy);
                  factor = currDist / maxDist;

                  pixel = newbitmap.GetPixel(i, j);
                  int red = (int)(pixel.R * (1 - factor));
                  int green = (int)(pixel.G * (1 - factor));
                  int blue = (int)(pixel.B * (1 - factor));
                  newbitmap.SetPixel(i, j, Color.FromArgb(red, green, blue));
              }
          }
          
          sw.Stop();
          label1.Text = "运行时间: " + sw.ElapsedMilliseconds.ToString();
          //显示处理好的图片
          pictureBox2.Image = newbitmap.Clone() as Image;
      }
  }
        3.4、Button4降低亮度按钮 
//降低亮度按钮
private void button4_Click(object sender, EventArgs e)
{
    if(bitmap != null)
    {
        newbitmap = bitmap.Clone() as Bitmap;
        sw.Reset();
        sw.Restart();
        Color pixel;
        int red, green, blue;
        for (int x = 0; x < newbitmap.Width; x++)
        {
            for (int y = 0; y < newbitmap.Height; y++)
            {
                pixel = newbitmap.GetPixel(x, y);
                red = (int)(pixel.R * 0.6);
                green = (int)(pixel.G * 0.6);
                blue = (int)(pixel.B * 0.6);
                newbitmap.SetPixel(x, y, Color.FromArgb(red, green, blue));
            }
        }

        sw.Stop();
        label1.Text = "运行时间: " + sw.ElapsedMilliseconds.ToString();
        pictureBox2.Image = newbitmap.Clone() as Image;
    }
}
       3.5、Button5去色按钮
   //去色按钮
   private void button5_Click(object sender, EventArgs e)
   {
       if(bitmap != null)
       {
           newbitmap = bitmap.Clone() as Bitmap;
           sw.Reset();
           sw.Restart();
           Color pixel;
           int gray;
           for (int x = 0; x < newbitmap.Width; x++)
           {
               for(int y = 0; y< newbitmap.Height; y++)
               {
                   pixel = newbitmap.GetPixel(x, y);
                   gray = (int)(0.3 * pixel.R + 0.59 * pixel.G + 0.11 * pixel.B);
                   newbitmap.SetPixel(x, y, Color.FromArgb(gray, gray, gray));
               }
           }

           sw.Stop();
           label1.Text = "运行时间: " + sw.ElapsedMilliseconds.ToString();
           pictureBox2.Image = newbitmap.Clone() as Image;
       }
   }
        3.6、Button6 浮雕按钮
  //浮雕按钮
  private void button6_Click(object sender, EventArgs e)
  {
      if (bitmap != null)
      {
          newbitmap = bitmap.Clone() as Bitmap;

          sw.Reset();
          sw.Restart();
          Color pixel;
          int red, green, blue;
          
          for (int x = 0; x < newbitmap.Width; x++)
          {
              for (int y = 0;y < newbitmap.Height; y++)
              {
                  pixel = newbitmap.GetPixel(x, y);
                  red = (int)(255 - pixel.R);
                  green = (int)(255 - pixel.G);
                  blue = (int)(255 - pixel.B);
                  newbitmap.SetPixel(x, y, Color.FromArgb(red, green, blue));
              }
          }

          sw.Stop ();
          label1.Text = "运行时间: " + sw.ElapsedMilliseconds.ToString();
          pictureBox2.Image = newbitmap.Clone() as Image;
      }
   }
        3.7、Button7马赛克按钮
  //马赛克按钮
  private void button7_Click(object sender, EventArgs e)
  {
      if (bitmap != null)
      {
          newbitmap = bitmap.Clone() as Bitmap;
          sw.Reset();
          sw.Restart();
          int RIDIO = 50; // 马赛克的尺度,默认为周围的两个像素

          for (int h = 0; h < newbitmap.Height; h += RIDIO)
          {
              for( int w = 0; w < newbitmap.Width; w+= RIDIO)
              {
                  int avgRed = 0, avgGreed = 0, avgBlue = 0;
                  int count = 0;
                  for( int x = w; (x < w + RIDIO && x < newbitmap.Width);  x++)
                  {
                      for ( int y = h; (y < h + RIDIO && y < newbitmap.Height); y++)
                      {
                          Color pixel = newbitmap.GetPixel(x, y);
                          avgRed += pixel.R;
                          avgGreed += pixel.G;
                          avgBlue += pixel.B;
                          count++;
                      }
                  }

                  //取平均值
                  avgRed = avgRed / count;
                  avgBlue = avgBlue / count;
                  avgGreed = avgGreed / count;

                  //设置颜色
                  for( int x = w; ( x < w + RIDIO && x<newbitmap.Width); x++)
                  {
                      for (int y = h; ( y < h + RIDIO && ( y < newbitmap.Height) ); y++)
                       {
                          Color newColor = Color.FromArgb(avgRed, avgGreed, avgBlue);
                          newbitmap.SetPixel(x, y, newColor);
                       }
                  }    
              }
          }

          sw.Stop();
          label1.Text = "运行时间: " + sw.ElapsedMilliseconds.ToString();
          pictureBox2.Image = newbitmap.Clone() as Image;
      }
   }
         3.8、Button8扩散按钮
   //扩散按钮
   private void button8_Click(object sender, EventArgs e)
   {
       if (bitmap != null)
       {
           newbitmap = bitmap.Clone() as Bitmap;
           sw.Reset();
           sw.Restart();
           Color pixel;
           int red, green, blue;

           for (int x = 0; x < newbitmap.Width; x++)
           {
               for (int y = 0; y < newbitmap.Height; y++)
               {
                   Random ran = new Random();
                   int RankKey = ran.Next(-5, 5);
                   if (x + RankKey >= newbitmap.Width || y + RankKey >= newbitmap.Height || x + RankKey < 0 || y + RankKey < 0)
                   {
                       continue;
                   }

                   pixel = newbitmap.GetPixel(x + RankKey, y + RankKey);
                   red = (int)(pixel.R);
                   green = (int)(pixel.G);
                   blue = (int)(pixel.B);
                   newbitmap.SetPixel(x, y, Color.FromArgb(red, green, blue));
               }
           }

           sw.Stop();
           label1.Text = "运行时间: " + sw.ElapsedMilliseconds.ToString();
           pictureBox2.Image = newbitmap.Clone() as Image;
       }
    }
        3.9、Button9清除图片按钮
 //清除图片按钮
 private void button9_Click(object sender, EventArgs e)
 {
     pictureBox1.Image = null;
     pictureBox2.Image = null;
 }
         3.10、保存2按钮
//保存2按钮
private void button10_Click(object sender, EventArgs e)
{
    if(saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        string path = saveFileDialog1.FileName;
        ImageFormat imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
        pictureBox2.Image.Save(path, imgformat);
    }
}
         3.11、Button11油画按钮
  //油画按钮
  private void button11_Click(object sender, EventArgs e)
  {
      if (bitmap != null)
      {
          newbitmap = bitmap.Clone() as Bitmap;
          //取得图片尺寸
          int width = newbitmap.Width;
          int height = newbitmap.Height;

          sw.Reset();
          sw.Restart();
          //产生随机数序列
          Random rnd = new Random();
          //取不同的值决定油画效果的不同程度
          int iModel = 2;
          int i = width - iModel;
          while (i > 1)
          {
              int j = height - iModel;
              while (j > 1)
              {
                  int iPos = rnd.Next(100000) % iModel;
                  //将该点的RGB值设置成附近iModel点之内的任一点
                  Color color = newbitmap.GetPixel(i + iPos, j + iPos);
                  newbitmap.SetPixel(i, j, color);
                  j = j - 1;
              }
              i = i - 1;
          }

          sw.Stop();
          label1.Text = "运行时间: " + sw.ElapsedMilliseconds.ToString();
          pictureBox2.Image = newbitmap.Clone() as Image;
      }
   }
         3.12、Button12柔化按钮
    //柔化按钮
    private void button12_Click(object sender, EventArgs e)
    {
        if (bitmap != null)
        {
            newbitmap = bitmap.Clone() as Bitmap;
            //取得图片尺寸
            int width = newbitmap.Width;
            int height = newbitmap.Height;

            sw.Reset();
            sw.Restart();
            Color piexl;

            //高斯模板
            int[] Gauss = { 1, 2, 1, 2, 4, 2, 1, 2, 1 };
            for(int x = 1; x < width - 1; x++)
            {
                for(int y = 1; y < height - 1; y++)
                {
                    int r = 0, g = 0, b = 0;
                    int index = 0;
                    for(int col = -1; col <= 1; col++)
                    {
                        for (int row = -1; row <= 1; row++)
                        {
                            piexl = newbitmap.GetPixel(x + row, y + col);
                            r += piexl.R * Gauss[index];
                            g += piexl.G * Gauss[index];
                            b += piexl.B * Gauss[index];
                            index++;
                        }
                    }
                    r /= 16;
                    g /= 16;
                    b /= 16;
                    //处理颜色溢出
                    r = r > 255 ? 255 : r;
                    r = r < 0 ? 0 : r;
                    g = g > 255 ? 255 : g;
                    g = g < 0 ? 0 : g;
                    b = b > 255 ? 255 : b;
                    b = b < 0 ? 0 : b;
                    bitmap.SetPixel(x - 1, y -1, Color.FromArgb(r, g, b));
                }
            }

            sw.Stop();
            label1.Text = "运行时间: " + sw.ElapsedMilliseconds.ToString();
            pictureBox2.Image = newbitmap.Clone() as Image;
        }
     }
         3.13、Button13截屏按钮
struct POINT
{
    public Int32 x;
    public Int32 y;
}

struct CURSORINFO
{
    public Int32 cbSize;
    public Int32 flags;
    public IntPtr hCursor;
    public POINT ptScreenPos;
}

 
// 按指定尺寸对图像pic进行非拉伸缩放
 public static Bitmap shrinkTo(Image pic, Size S, Boolean cutting)
 {
     //创建图像
     Bitmap tmp = new Bitmap(S.Width, S.Height);//按指定大小创建图像

     //绘制
     Graphics g = Graphics.FromImage(tmp);//从位图创建Graphics对象
     g.Clear(Color.FromArgb(0, 0, 0)); //清空

     Boolean mode = (float)pic.Width / S.Width > (float)pic.Height / S.Height;  //zoom缩放
     if (cutting) mode = !mode;  //裁剪缩放

     //计算zoom绘制区域
     if (mode)
     {
         S.Height = (int)((float)pic.Height * S.Width / pic.Width);
     }
     else
     {
         S.Width = (int)((float)pic.Width * S.Height / pic.Height);
     }

     Point p = new Point((tmp.Width - S.Width) / 2, (tmp.Height - S.Height) / 2);

     g.DrawImage(pic, new Rectangle(p, S));
     return tmp;//返回构建的新图像
 }

 //根据文件拓展名,获取对应的存储类型
 public static ImageFormat getFormat(string filePath)
 {
     ImageFormat format = ImageFormat.MemoryBmp;
     String Ext = System.IO.Path.GetExtension(filePath).ToLower();

     if (Ext.Equals(".png")) format = ImageFormat.Png;
     else if (Ext.Equals(".jpg") || Ext.Equals(".jpeg")) format = ImageFormat.Jpeg;
     else if (Ext.Equals(".bmp")) format = ImageFormat.Bmp;
     else if (Ext.Equals(".gif")) format = ImageFormat.Gif;
     else if (Ext.Equals(".ico")) format = ImageFormat.Icon;
     else if (Ext.Equals(".emf")) format = ImageFormat.Emf;
     else if (Ext.Equals(".exif")) format = ImageFormat.Exif;
     else if (Ext.Equals(".tiff")) format = ImageFormat.Tiff;
     else if (Ext.Equals(".wmf")) format = ImageFormat.Wmf;
     else if (Ext.Equals(".memorybmp")) format = ImageFormat.MemoryBmp;

     return format;
 }

 //保存图像pic到文件fileName中,指定图像保存格式
 public static void SaveToFile(Image pic, string fileName, bool replace, ImageFormat format)
 {
     //若图像已存在,则删除
     if (System.IO.File.Exists(fileName) && replace)
     {
         System.IO.File.Delete(fileName);
     }

     //若不存在则创建
     if (!System.IO.File.Exists(fileName))
     {
         if (format == null)
         {
             format = getFormat(fileName); //根据拓展名获取图像的对应存储类型
         }

         if (format == ImageFormat.MemoryBmp)
         {
             pic.Save(fileName);
             MessageBox.Show("图片保存成功!");
         }
         else
         {
             pic.Save(fileName, format);//按给定格式保存图像
             MessageBox.Show("图片保存成功!");
         }
     }
 }

 // 缩放icon为指定的尺寸,并保存到路径PathName
 public static void saveImage(Image image, Size size, String PathName)
 {
     Image tmp = shrinkTo(image, size, false);
     SaveToFile(tmp, PathName, true, null);
 }

 // 截取屏幕指定区域为Image,保存到路径savePath下,haveCursor是否包含鼠标
 private static Image getScreen(int x = 0, int y = 0, int width = -1, int height = -1, String savePath = "", bool haveCursor = true)
 {
     if (width == -1)
     {
         width = SystemInformation.VirtualScreen.Width + 1280;//虚拟屏幕界限
     }
     if (height == -1)
     {
         height = SystemInformation.VirtualScreen.Height + 800;
     }

     Bitmap tmp = new Bitmap(width, height); //按指定大小创建位图
     Graphics g = Graphics.FromImage(tmp); //从位图创建Graphics对象
     g.CopyFromScreen(x, y, 0, 0, new Size(width, height)); //绘制

     // 绘制鼠标
     if (haveCursor)
     {
         try
         {
             CURSORINFO pci;
             pci.cbSize = Marshal.SizeOf(typeof(CURSORINFO));
             GetCursorInfo(out pci);
             System.Windows.Forms.Cursor cur = new System.Windows.Forms.Cursor(pci.hCursor);
             cur.Draw(g, new Rectangle(pci.ptScreenPos.x, pci.ptScreenPos.y, cur.Size.Width, cur.Size.Height));
         }
         catch (Exception ex)
         {
             // 若获取鼠标异常则不显示
         }
     }
     if (!savePath.Equals(""))
     {
         saveImage(tmp, tmp.Size, savePath); // 保存到指定的路径下
     }
     return tmp;  //返回构建的新图像
 }

 private static void GetCursorInfo(out CURSORINFO pci)
 {
     throw new NotImplementedException();
 }

 //截屏按钮
 private void button13_Click(object sender, EventArgs e)
 {
     screen = getScreen();                       // 截取屏幕  
     pictureBox1.Image = screen;
 }

       
//旋转90度按钮 
private void button14_Click(object sender, EventArgs e)
 {
     //获取需要旋转的图片
     //  Bitmap bmp = (Bitmap)screen;
     Bitmap bmp = (Bitmap)pictureBox1.Image;

     sw.Reset();
     sw.Restart();

     //向右90度旋转
     bmp.RotateFlip(RotateFlipType.Rotate270FlipXY);

     sw.Stop();
     label1.Text = "运行时间: " + sw.ElapsedMilliseconds.ToString();
     pictureBox2.Image = bmp.Clone() as Image;
 }

 补充:旋转使用了Image类的RotateFlip方法

4、运行结果 

        打开一张图片显示到pictureBox1中,然后点击相应的按钮,便会在pictureBox2中显示处理后的图片。

5、完整代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        //创建一个新的位图
        private Bitmap bitmap,  newbitmap;
        private Stopwatch sw;//计算运行时间

        //截屏的图片
        Image screen;

        public Form1()
        {
            InitializeComponent();
            sw = new Stopwatch();
        }

        struct POINT
        {
            public Int32 x;
            public Int32 y;
        }

        struct CURSORINFO
        {
            public Int32 cbSize;
            public Int32 flags;
            public IntPtr hCursor;
            public POINT ptScreenPos;
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        //保存按钮
        private void button2_Click(object sender, EventArgs e)
        {
            bool isSvae = true;
            if(saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fileName = saveFileDialog1.FileName.ToString();
                if(fileName != "" && fileName != null)
                {
                    string fileExtName = fileName.Substring(fileName.LastIndexOf('.') + 1).ToString();
                    System.Drawing.Imaging.ImageFormat imgformat = null;
                    if(fileExtName != "")
                    {
                        switch (fileExtName)
                        {
                            case "jpg":
                                imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
                                break;
                            case "bmp":
                                imgformat = System.Drawing.Imaging.ImageFormat.Bmp;
                                break;
                            case "gif":
                                imgformat = System.Drawing.Imaging.ImageFormat.Gif;
                                break;
                            default:
                                MessageBox.Show("只能存储为:jpg,bmp, gif 格式");
                                isSvae = false;
                                break;
                        }
                     }

                    //默认保存为jpg格式
                    if(imgformat == null)
                    {
                        imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
                    }

                    if(isSvae)
                    {
                        try
                        {
                            pictureBox2.Image.Save(fileName, imgformat);
                            MessageBox.Show("图片保存成功!");
                        }
                        catch
                        {
                            MessageBox.Show("保存失败! 你还没有截取过图片或者图片已经清空!");
                        }
                    }
                }
            }
        }

        //打开按钮
        private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string path = openFileDialog1.FileName;
                bitmap = (Bitmap) Bitmap.FromFile(path);
                pictureBox1.Image = bitmap.Clone() as Image;
            }
        }

        //添加暗角按钮
        private void button3_Click(object sender, EventArgs e)
        {
            if (bitmap != null)
            {
                newbitmap = bitmap.Clone() as Bitmap;

                sw.Reset();
                sw.Restart();

                int width = newbitmap.Width;
                int height = newbitmap.Height;
                float cx = width / 2;
                float cy = height / 2;
                float maxDist = cx * cx + cy * cy;
                float currDist = 0, factor;
                Color pixel;

                for (int i = 0; i < width; i++)
                {
                    for (int j = 0; j < height; j++)
                    {
                        currDist = ((float)i - cx) * ((float)i - cx) + ((float)j - cy) * ((float)j - cy);
                        factor = currDist / maxDist;

                        pixel = newbitmap.GetPixel(i, j);
                        int red = (int)(pixel.R * (1 - factor));
                        int green = (int)(pixel.G * (1 - factor));
                        int blue = (int)(pixel.B * (1 - factor));
                        newbitmap.SetPixel(i, j, Color.FromArgb(red, green, blue));
                    }
                }

                sw.Stop();
                label1.Text = "运行时间: " + sw.ElapsedMilliseconds.ToString();
                pictureBox2.Image = newbitmap.Clone() as Image;
            }
        }

        //降低亮度按钮
        private void button4_Click(object sender, EventArgs e)
        {
            if(bitmap != null)
            {
                newbitmap = bitmap.Clone() as Bitmap;
                sw.Reset();
                sw.Restart();
                Color pixel;
                int red, green, blue;
                for (int x = 0; x < newbitmap.Width; x++)
                {
                    for (int y = 0; y < newbitmap.Height; y++)
                    {
                        pixel = newbitmap.GetPixel(x, y);
                        red = (int)(pixel.R * 0.6);
                        green = (int)(pixel.G * 0.6);
                        blue = (int)(pixel.B * 0.6);
                        newbitmap.SetPixel(x, y, Color.FromArgb(red, green, blue));
                    }
                }

                sw.Stop();
                label1.Text = "运行时间: " + sw.ElapsedMilliseconds.ToString();
                pictureBox2.Image = newbitmap.Clone() as Image;
            }
        }

        //马赛克按钮
        private void button7_Click(object sender, EventArgs e)
        {
            if (bitmap != null)
            {
                newbitmap = bitmap.Clone() as Bitmap;
                sw.Reset();
                sw.Restart();
                int RIDIO = 50; // 马赛克的尺度,默认为周围的两个像素

                for (int h = 0; h < newbitmap.Height; h += RIDIO)
                {
                    for( int w = 0; w < newbitmap.Width; w+= RIDIO)
                    {
                        int avgRed = 0, avgGreed = 0, avgBlue = 0;
                        int count = 0;
                        for( int x = w; (x < w + RIDIO && x < newbitmap.Width);  x++)
                        {
                            for ( int y = h; (y < h + RIDIO && y < newbitmap.Height); y++)
                            {
                                Color pixel = newbitmap.GetPixel(x, y);
                                avgRed += pixel.R;
                                avgGreed += pixel.G;
                                avgBlue += pixel.B;
                                count++;
                            }
                        }

                        //取平均值
                        avgRed = avgRed / count;
                        avgBlue = avgBlue / count;
                        avgGreed = avgGreed / count;

                        //设置颜色
                        for( int x = w; ( x < w + RIDIO && x<newbitmap.Width); x++)
                        {
                            for (int y = h; ( y < h + RIDIO && ( y < newbitmap.Height) ); y++)
                             {
                                Color newColor = Color.FromArgb(avgRed, avgGreed, avgBlue);
                                newbitmap.SetPixel(x, y, newColor);
                             }
                        }    
                    }
                }

                sw.Stop();
                label1.Text = "运行时间: " + sw.ElapsedMilliseconds.ToString();
                pictureBox2.Image = newbitmap.Clone() as Image;
            }
         }

        //去色按钮
        private void button5_Click(object sender, EventArgs e)
        {
            if(bitmap != null)
            {
                newbitmap = bitmap.Clone() as Bitmap;
                sw.Reset();
                sw.Restart();
                Color pixel;
                int gray;
                for (int x = 0; x < newbitmap.Width; x++)
                {
                    for(int y = 0; y< newbitmap.Height; y++)
                    {
                        pixel = newbitmap.GetPixel(x, y);
                        gray = (int)(0.3 * pixel.R + 0.59 * pixel.G + 0.11 * pixel.B);
                        newbitmap.SetPixel(x, y, Color.FromArgb(gray, gray, gray));
                    }
                }

                sw.Stop();
                label1.Text = "运行时间: " + sw.ElapsedMilliseconds.ToString();
                pictureBox2.Image = newbitmap.Clone() as Image;
            }
        }

        //浮雕按钮
        private void button6_Click(object sender, EventArgs e)
        {
            if (bitmap != null)
            {
                newbitmap = bitmap.Clone() as Bitmap;

                sw.Reset();
                sw.Restart();
                Color pixel;
                int red, green, blue;
                
                for (int x = 0; x < newbitmap.Width; x++)
                {
                    for (int y = 0;y < newbitmap.Height; y++)
                    {
                        pixel = newbitmap.GetPixel(x, y);
                        red = (int)(255 - pixel.R);
                        green = (int)(255 - pixel.G);
                        blue = (int)(255 - pixel.B);
                        newbitmap.SetPixel(x, y, Color.FromArgb(red, green, blue));
                    }
                }

                sw.Stop ();
                label1.Text = "运行时间: " + sw.ElapsedMilliseconds.ToString();
                pictureBox2.Image = newbitmap.Clone() as Image;
            }
         }

        //扩散按钮
        private void button8_Click(object sender, EventArgs e)
        {
            if (bitmap != null)
            {
                newbitmap = bitmap.Clone() as Bitmap;
                sw.Reset();
                sw.Restart();
                Color pixel;
                int red, green, blue;

                for (int x = 0; x < newbitmap.Width; x++)
                {
                    for (int y = 0; y < newbitmap.Height; y++)
                    {
                        Random ran = new Random();
                        int RankKey = ran.Next(-5, 5);
                        if (x + RankKey >= newbitmap.Width || y + RankKey >= newbitmap.Height || x + RankKey < 0 || y + RankKey < 0)
                        {
                            continue;
                        }

                        pixel = newbitmap.GetPixel(x + RankKey, y + RankKey);
                        red = (int)(pixel.R);
                        green = (int)(pixel.G);
                        blue = (int)(pixel.B);
                        newbitmap.SetPixel(x, y, Color.FromArgb(red, green, blue));
                    }
                }

                sw.Stop();
                label1.Text = "运行时间: " + sw.ElapsedMilliseconds.ToString();
                pictureBox2.Image = newbitmap.Clone() as Image;
            }
         }

        //清除图片按钮
        private void button9_Click(object sender, EventArgs e)
        {
            pictureBox1.Image = null;
            pictureBox2.Image = null;
        }

        //保存2按钮
        private void button10_Click(object sender, EventArgs e)
        {
            if(saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string path = saveFileDialog1.FileName;
                ImageFormat imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
                pictureBox2.Image.Save(path, imgformat);
            }
        }

        //油画按钮
        private void button11_Click(object sender, EventArgs e)
        {
            if (bitmap != null)
            {
                newbitmap = bitmap.Clone() as Bitmap;
                //取得图片尺寸
                int width = newbitmap.Width;
                int height = newbitmap.Height;

                sw.Reset();
                sw.Restart();
                //产生随机数序列
                Random rnd = new Random();
                //取不同的值决定油画效果的不同程度
                int iModel = 2;
                int i = width - iModel;
                while (i > 1)
                {
                    int j = height - iModel;
                    while (j > 1)
                    {
                        int iPos = rnd.Next(100000) % iModel;
                        //将该点的RGB值设置成附近iModel点之内的任一点
                        Color color = newbitmap.GetPixel(i + iPos, j + iPos);
                        newbitmap.SetPixel(i, j, color);
                        j = j - 1;
                    }
                    i = i - 1;
                }

                sw.Stop();
                label1.Text = "运行时间: " + sw.ElapsedMilliseconds.ToString();
                pictureBox2.Image = newbitmap.Clone() as Image;
            }
         }

        //柔化按钮
        private void button12_Click(object sender, EventArgs e)
        {
            if (bitmap != null)
            {
                newbitmap = bitmap.Clone() as Bitmap;
                //取得图片尺寸
                int width = newbitmap.Width;
                int height = newbitmap.Height;

                sw.Reset();
                sw.Restart();
                Color piexl;

                //高斯模板
                int[] Gauss = { 1, 2, 1, 2, 4, 2, 1, 2, 1 };
                for(int x = 1; x < width - 1; x++)
                {
                    for(int y = 1; y < height - 1; y++)
                    {
                        int r = 0, g = 0, b = 0;
                        int index = 0;
                        for(int col = -1; col <= 1; col++)
                        {
                            for (int row = -1; row <= 1; row++)
                            {
                                piexl = newbitmap.GetPixel(x + row, y + col);
                                r += piexl.R * Gauss[index];
                                g += piexl.G * Gauss[index];
                                b += piexl.B * Gauss[index];
                                index++;
                            }
                        }
                        r /= 16;
                        g /= 16;
                        b /= 16;
                        //处理颜色溢出
                        r = r > 255 ? 255 : r;
                        r = r < 0 ? 0 : r;
                        g = g > 255 ? 255 : g;
                        g = g < 0 ? 0 : g;
                        b = b > 255 ? 255 : b;
                        b = b < 0 ? 0 : b;
                        bitmap.SetPixel(x - 1, y -1, Color.FromArgb(r, g, b));
                    }
                }

                sw.Stop();
                label1.Text = "运行时间: " + sw.ElapsedMilliseconds.ToString();
                pictureBox2.Image = newbitmap.Clone() as Image;
            }
         }

        /// 按指定尺寸对图像pic进行非拉伸缩放
        public static Bitmap shrinkTo(Image pic, Size S, Boolean cutting)
        {
            //创建图像
            Bitmap tmp = new Bitmap(S.Width, S.Height);//按指定大小创建图像

            //绘制
            Graphics g = Graphics.FromImage(tmp);//从位图创建Graphics对象
            g.Clear(Color.FromArgb(0, 0, 0)); //清空

            Boolean mode = (float)pic.Width / S.Width > (float)pic.Height / S.Height;  //zoom缩放
            if (cutting) mode = !mode;  //裁剪缩放

            //计算zoom绘制区域
            if (mode)
            {
                S.Height = (int)((float)pic.Height * S.Width / pic.Width);
            }
            else
            {
                S.Width = (int)((float)pic.Width * S.Height / pic.Height);
            }

            Point p = new Point((tmp.Width - S.Width) / 2, (tmp.Height - S.Height) / 2);

            g.DrawImage(pic, new Rectangle(p, S));
            return tmp;//返回构建的新图像
        }

        //根据文件拓展名,获取对应的存储类型
        public static ImageFormat getFormat(string filePath)
        {
            ImageFormat format = ImageFormat.MemoryBmp;
            String Ext = System.IO.Path.GetExtension(filePath).ToLower();

            if (Ext.Equals(".png")) format = ImageFormat.Png;
            else if (Ext.Equals(".jpg") || Ext.Equals(".jpeg")) format = ImageFormat.Jpeg;
            else if (Ext.Equals(".bmp")) format = ImageFormat.Bmp;
            else if (Ext.Equals(".gif")) format = ImageFormat.Gif;
            else if (Ext.Equals(".ico")) format = ImageFormat.Icon;
            else if (Ext.Equals(".emf")) format = ImageFormat.Emf;
            else if (Ext.Equals(".exif")) format = ImageFormat.Exif;
            else if (Ext.Equals(".tiff")) format = ImageFormat.Tiff;
            else if (Ext.Equals(".wmf")) format = ImageFormat.Wmf;
            else if (Ext.Equals(".memorybmp")) format = ImageFormat.MemoryBmp;

            return format;
        }

        //保存图像pic到文件fileName中,指定图像保存格式
        public static void SaveToFile(Image pic, string fileName, bool replace, ImageFormat format)
        {
            //若图像已存在,则删除
            if (System.IO.File.Exists(fileName) && replace)
            {
                System.IO.File.Delete(fileName);
            }

            //若不存在则创建
            if (!System.IO.File.Exists(fileName))
            {
                if (format == null)
                {
                    format = getFormat(fileName); //根据拓展名获取图像的对应存储类型
                }

                if (format == ImageFormat.MemoryBmp)
                {
                    pic.Save(fileName);
                    MessageBox.Show("图片保存成功!");
                }
                else
                {
                    pic.Save(fileName, format);//按给定格式保存图像
                    MessageBox.Show("图片保存成功!");
                }
            }
        }

        /// 缩放icon为指定的尺寸,并保存到路径PathName
        public static void saveImage(Image image, Size size, String PathName)
        {
            Image tmp = shrinkTo(image, size, false);
            SaveToFile(tmp, PathName, true, null);
        }

        // 截取屏幕指定区域为Image,保存到路径savePath下,haveCursor是否包含鼠标
        private static Image getScreen(int x = 0, int y = 0, int width = -1, int height = -1, String savePath = "", bool haveCursor = true)
        {
            if (width == -1)
            {
                width = SystemInformation.VirtualScreen.Width + 1280;//虚拟屏幕界限
            }
            if (height == -1)
            {
                height = SystemInformation.VirtualScreen.Height + 800;
            }

            Bitmap tmp = new Bitmap(width, height); //按指定大小创建位图
            Graphics g = Graphics.FromImage(tmp); //从位图创建Graphics对象
            g.CopyFromScreen(x, y, 0, 0, new Size(width, height)); //绘制

            // 绘制鼠标
            if (haveCursor)
            {
                try
                {
                    CURSORINFO pci;
                    pci.cbSize = Marshal.SizeOf(typeof(CURSORINFO));
                    GetCursorInfo(out pci);
                    System.Windows.Forms.Cursor cur = new System.Windows.Forms.Cursor(pci.hCursor);
                    cur.Draw(g, new Rectangle(pci.ptScreenPos.x, pci.ptScreenPos.y, cur.Size.Width, cur.Size.Height));
                }
                catch (Exception ex)
                {
                    // 若获取鼠标异常则不显示
                }
            }
            if (!savePath.Equals(""))
            {
                saveImage(tmp, tmp.Size, savePath); // 保存到指定的路径下
            }
            return tmp;  //返回构建的新图像
        }

        private static void GetCursorInfo(out CURSORINFO pci)
        {
            throw new NotImplementedException();
        }

        //旋转90度按钮
        private void button14_Click(object sender, EventArgs e)
        {
            //获取需要旋转的图片
            //  Bitmap bmp = (Bitmap)screen;
            Bitmap bmp = (Bitmap)pictureBox1.Image;

            sw.Reset();
            sw.Restart();

            //向右90度旋转
            bmp.RotateFlip(RotateFlipType.Rotate270FlipXY);

            sw.Stop();
            label1.Text = "运行时间: " + sw.ElapsedMilliseconds.ToString();
            pictureBox2.Image = bmp.Clone() as Image;
        }

        //截屏按钮
        private void button13_Click(object sender, EventArgs e)
        {
            screen = getScreen();                       // 截取屏幕  
            pictureBox1.Image = screen;
        }

       
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2169134.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【ARM 嵌入式 编译系列 10.4 -- GNU Binary Utilies】

文章目录 GNU Binary Utilities 详细介绍常用工具介绍1. arm-none-eabi-objcopy2. arm-none-eabi-readelf3. arm-none-eabi-size4. arm-none-eabi-objdump5. arm-none-eabi-nm6. arm-none-eabi-strip7. arm-none-eabi-ld8. arm-none-eabi-as9. arm-none-eabi-addr2line10. arm-…

linux内核双向链表使用list klist

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、list和klist是什么&#xff1f;二、代码示例1.list2.klist 总结 前言 提示&#xff1a;这里可以添加本文要记录的大概内容&#xff1a; linux内核中大量使…

Spring Boot打造甘肃非遗文化传承网站

摘 要 现代经济快节奏发展以及不断完善升级的信息化技术&#xff0c;让传统数据信息的管理升级为软件存储&#xff0c;归纳&#xff0c;集中处理数据信息的管理方式。本甘肃非物质文化网站就是在这样的大环境下诞生&#xff0c;其可以帮助管理者在短时间内处理完毕庞大的数据信…

如何像专家一样修复任何 iPhone 上的“iPhone 已禁用”错误

“我忘记了密码&#xff0c;并且我的 iPhone 在多次输入错误密码后就被禁用了&#xff0c;如何再次访问我的手机&#xff1f;” 作为最安全的数字设备之一&#xff0c;iPhone 必须使用正确的密码解锁。即使您可以使用 Face ID 或 Touch ID 访问您的设备&#xff0c;在充电或重…

交警车辆通入城行证管理建设方案和必要性-———未来之窗行业应用跨平台架构

一、系统目标 建立一个高效、便捷、规范的车辆入城通行证管理系统&#xff0c;提高交警部门的管理效率&#xff0c;优化城市交通流量&#xff0c;减少交通拥堵&#xff0c;保障城市交通安全。 二、系统功能模块 1. 通行证申请模块 - 提供在线申请入口&#xff0c;申请人填…

【MySQL】聚合函数、group by子句

目录 聚合函数 count([distinct] column) sum([distinct] column) avg([distinct] column) max([distinct] column) min([distinct] column) group by子句 1.如何显示每个部门的平均薪资和最高薪资 2.显示每个部门每种岗位的平均薪资和最低薪资 3.显示平均工资低于200…

maven给springboot项目打成jar包 maven springboot打包配置

基于maven的spring boot 打包分离依赖及配置文件 使用springCloud或springboot的过程中&#xff0c;发布到生产环境的网速受限&#xff0c;如果每次将60,70M甚至更大的jar包上传&#xff0c;速度太慢了&#xff0c;采取jar包和配置文件分离的方式可以极大的压缩jar包大小&#…

npm 安装newman时idealTree:vue: sill idealTree buildDeps卡住了(实测成功)

删除 C:\Users\{账户}\ 文件夹中的 .npmrc 文件在命令提示符里执行 npm cache verify 在命令提示符里执行 npm config set registry https://registry.npmmirror.com 切换淘宝源来源&#xff1a; https://blog.csdn.net/weixin_39245942/article/details/135748323

【Verilog学习日常】—牛客网刷题—Verilog企业真题—VL62

序列发生器 描述 编写一个模块&#xff0c;实现循环输出序列001011。 模块的接口信号图如下&#xff1a; 要求使用Verilog HDL实现&#xff0c;并编写testbench验证模块的功能。 输入描述&#xff1a; clk&#xff1a;时钟信号 rst_n&#xff1a;复位信号&#xff0c;低电平…

【学习笔记】手写 Tomcat 七

目录 一、优化 Dao 1. 设置 UserDaoImpl 为单例模式 2. 创建 Dao 工厂 3. 在 Service 层获取 UserDao 的实例 二、优化 Service 1. 设置 UserServiceImpl 为单例模式 2. 创建 Service 工厂 3. 在 Servlet 层获取 Service 实现类的对象 三、优化 Servlet 1. 使用配置…

Map+Set

我们前面接触过的string、vector、list这些都算序列式容器&#xff0c;它们都有一定的关联性&#xff0c;即使随便换位置也无伤大雅&#xff0c;因为是它们靠位置顺序来保存的。但是今天的MapSet就不是了&#xff0c;它们算关联式容器&#xff0c;两个位置之间有紧密的联系&…

Linux-df命令使用方法

Linux-df&#xff08;disk filesystem&#xff09;命令 df 命令是 Unix 和 Linux 系统中用于报告文件系统磁盘空间使用情况的工具。 df [OPTION]... [FILE]...OPTION 常用选项&#xff08;博主一般df -h用的较多&#xff0c;可读性较好&#xff09; -h&#xff1a;以人类可读的…

Uniapp 微信小程序 最新 获取用户头像 和 昵称 方法 有效可用

文章目录 前言代码实现运行效果技术分析 前言 同事有个需求 授权获取用户头像 和 昵称 。之前做过线上小程序发版上线流程 就实现了下 最新的方法和 api 有些变化 记录下 代码实现 先直接上代码 <template><view class"container"><buttonclass&qu…

如何部署北斗定位应用,基于国产自主架构LS2K1000LA-i处理器平台

北斗卫星导航系统(以下简称北斗系统)是着眼于国内经济社会发展需要,自主建设、独立运行的卫星导航系统。经过多年发展,北斗系统已成为面向全球用户提供全天候、全天时、高精度定位、导航与授时服务的重要新型基础设施。 图 1 北斗定位系统的应用优势 强可控:北斗系统是国…

Ollama本地部署大模型及应用

文章目录 前言一、下载安装1.Mac2.Windows3.linux4.docker5.修改配置&#xff08;可选&#xff09;1.linux系统2.window 系统3.mac系统 二、Ollama使用1.命令2.模型下载3.自定义模型4.API 服务 三、Open WebUI 使用四、Dify使用 前言 Ollama 是一个专注于本地部署大型语言模型…

第四届摩纳哥智能化可持续发展游艇码头交流会

第四届摩纳哥智能化可持续发展游艇码头交流会 游艇生态和经济转型 2024年9月23日&#xff0c;第四届摩纳哥智能化可持续发展游艇码头交流会于摩纳哥游艇俱乐部顺利落幕。该交流会由摩纳哥游艇码头顾问公司&#xff08;M3&#xff09;主办&#xff0c;吸引了全球250名游艇行业领…

数据集-目标检测系列-口罩检测数据集 mask>> DataBall

数据集-目标检测系列-口罩检测数据集 mask>> DataBall 数据集-目标检测系列-口罩检测数据集 mask 数据量&#xff1a;1W DataBall 助力快速掌握数据集的信息和使用方式&#xff0c;享有百种数据集&#xff0c;持续增加中。 数据项目地址&#xff1a; gitcode: https…

JAVA笔记 | 实际上用到的策略模式(可直接套用)

自己开发中用到了策略模式&#xff0c;这样写不一定是最好的&#xff0c;但是满足了业务场景跟使用要求&#xff0c;做个笔记&#xff0c;下次有用到可以快速复习跟套用 假设使用场景&#xff1a;有几只宠物&#xff0c;猫跟狗等&#xff0c;要求他们做各种动作&#xff0c;比如…

无人机之物流货运篇

一、无人机货运的崛起 随着电商、快递行业的蓬勃发展&#xff0c;传统的地面物流已经难以满足日益增长的快递量和对速度的追求。而无人机货运凭借其高效、快捷、灵活的特点&#xff0c;逐渐成为了物流行业的新宠。无人机可以在城市上空快速穿梭&#xff0c;不受地面交通拥堵的限…

语言模型发展史

四个阶段 第一阶段&#xff1a;基于规则和统计的语言模型 由人工设计特征并使用统计方法对固定长度的文本窗口序列进行建模分析&#xff0c;这种建模方式也被称为N-gram语言模型。 优点&#xff1a; 1&#xff09;采用极大似然估计, 参数易训练 2&#xff09;完全包含了前n-…