在C#中截取屏幕的某些部分?

时间:2010-12-31 04:18:32

标签: c# bitmap screenshot

我想截取屏幕一部分的屏幕截图,然后将该信息存储在图像数组中。有没有办法修改这个类: http://pastebin.com/PDPPxmPT 这样它可以让我截取特定区域的截图?例如,如果我想要位图的x,y像素来源为200,200且x,y目的地为600,700,我将如何进行此操作?

2 个答案:

答案 0 :(得分:2)

我修改了here

编辑:这是代码

public static Color[,] takeScreenshot(int x=0, int y=0, int width=0, int height = 0)
        {
    if (width==0)
        width = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
    if (height==0)
        height = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
            Bitmap screenShotBMP = new Bitmap(width,
                height, PixelFormat.Format32bppArgb);

            Graphics screenShotGraphics = Graphics.FromImage(screenShotBMP);

            screenShotGraphics.CopyFromScreen(x,
                y, 0, 0, new Size(width,height),
                CopyPixelOperation.SourceCopy);

            screenShotGraphics.Dispose();

            return bitmap2imagearray(screenShotBMP);
        } 

public static Color[,] bitmap2imagearray(Bitmap b)
        {
            Color[,] imgArray = new Color[b.Width, b.Height];
            for (int y = 0; y < b.Height; y++)
            {
                for (int x = 0; x < b.Width; x++)
                {
                    imgArray[x, y] = b.GetPixel(x, y);
                }
            }
            return imgArray;
        }

答案 1 :(得分:0)

不是答案,但包括来自pastebin的代码,因为它可能会在将来的某个时间消失,并且可能对其他人有用。

    public static Color[,] takeScreenshot()
    {
        Bitmap screenShotBMP = new Bitmap(System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width,
            System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);

        Graphics screenShotGraphics = Graphics.FromImage(screenShotBMP);

        screenShotGraphics.CopyFromScreen(System.Windows.Forms.Screen.PrimaryScreen.Bounds.X,
            System.Windows.Forms.Screen.PrimaryScreen.Bounds.Y, 0, 0, System.Windows.Forms.Screen.PrimaryScreen.Bounds.Size,
            CopyPixelOperation.SourceCopy);

        screenShotGraphics.Dispose();

        return bitmap2imagearray(screenShotBMP);
    } 

    public static Color[,] bitmap2imagearray(Bitmap b)
    {
        Color[,] imgArray = new Color[b.Width, b.Height];
        for (int y = 0; y < b.Height; y++)
        {
            for (int x = 0; x < b.Width; x++)
            {
                imgArray[x, y] = b.GetPixel(x, y);
            }
        }
        return imgArray;
    }