Search code examples
c#exceptionscreenshotrectangles

Crop image from X and Y?


var ssbytearray = ((ITakesScreenshot)excelSession).GetScreenshot().AsByteArray;
var screenshot = new Bitmap(new MemoryStream(ssbytearray));
var croppedScreenshot = new Rectangle(element.Location.X, element.Location.Y, element.Size.Width, element.Size.Height);
screenshot = screenshot.Clone(croppedScreenshot, screenshot.PixelFormat);

SaveScreenShot(saveLocation, screenshot);

In my code, I'm currently taking a screenshot of a Microsoft Office application that I called, "element" and it saves the image as its meant to. Unfortunately if I want to crop the image from the top or left side, it isn't as easy as replacing the X and Y coordinates with a number when creating the Rectangle. If I do try to change the X or Y coordinate with a value I get a SystemOutOfMemory exception. However if I want to crop it from the width and height and I try to change the value I'm able to.

I'd like to be able to crop the screenshot taken from the top and left side. Currently I'm only able to crop the screenshot from the bottom or right side using the width & height.

Any help's appreciated.


Solution

  • I solved this issue by changing the x, y, height & width values when creating the Rectangle. It will produce a System.OutOfMemory exception if the values you create the Rectangle with are bigger than the element you're trying to capture.

    However this causes problems when changing resolutions. Currently trying to solve that issue now.

    EDIT: To fix the second issue I came across I am changing the resolution of the system before & after the test runs so it can run on a resolution that's common on most systems, then change it back to its original.