Using the DrawImage method in the Graphics class, there are 30 overload methods for this method. Only one is introduced here, which I think is the most intuitive one. The code is as follows:
1 using System.Drawing; 2 3 namespace kq.Utils 4 { 5 public static class CommonTools 6 { 7 8 public static Bitmap getVerifyCode(Bitmap srcBmp, Rectangle rectangle) 9 { 10 //Initialize a bmp Object, 90 for the width of the picture, 37 for the height 11 Bitmap bmp = new Bitmap(90, 37); 12 Graphics g = Graphics.FromImage(bmp); 13 g.DrawImage(srcBmp, 0, 0, rectangle, GraphicsUnit.Pixel); 14 return bmp; 15 } 16 } 17 }
In g.DrawImage method, the first parameter represents the original image to be intercepted, the second third parameter (0, 0) represents the xy coordinate of the starting point drawn in bmp, the fourth parameter rectangle represents the region to be intercepted from srcBmp, the last parameter GraphicsUnit.Pixel represents the unit of the above parameters representing the distance and the region, and Pixel represents the Pixel.
Here's how to use it:
1 using kq.Utils; 2 using OpenQA.Selenium; 3 using OpenQA.Selenium.Chrome; 4 using System.Drawing; 5 6 namespace kq 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 try 13 { 14 string screenImg = @"d:\screenImg.png"; 15 16 Bitmap fromBmp = new Bitmap(screenImg); 17 Rectangle section1 = new Rectangle(936, 523, 90, 37); 18 19 Bitmap bmp = CommonTools.getVerifyCode(fromBmp, section1); 20 21 bmp.Save(@"d:\Verification Code.bmp"); 22 } 23 catch (System.Exception e) 24 { 25 System.Console.WriteLine(e.Message); 26 } 27 28 } 29 } 30 }
Suppose we want to intercept the verification code part of a picture. The (936523) in the code represents the coordinates of the upper left corner of the verification code in the original picture, and (90, 37) represents the length and height of the verification code respectively. The above units are pixels, as shown in the following figure:
The final result is as follows: