Screenshot of a full element in Selenium C# - c#

I need to take a screenshot of a whole element in selenium C# using chromedriver. The element is table and though I am getting the width and height of the element, the screenshot I am getting is of only 15 rows.
IWebElement element = driver.FindElement(By.XPath("Xpath of the element"));
string fileName = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".jpg";
Byte[] byteArray = ((ITakesScreenshot)driver).GetScreenshot().AsByteArray;
System.Drawing.Bitmap screenshot = new System.Drawing.Bitmap(new System.IO.MemoryStream(byteArray));
System.Drawing.Rectangle croppedImage = new System.Drawing.Rectangle(element.Location.X, element.Location.Y, element.Size.Width, element.Size.Height);
screenshot = screenshot.Clone(croppedImage, screenshot.PixelFormat);
screenshot.Save(String.Format(#"path" + fileName, System.Drawing.Imaging.ImageFormat.Jpeg));
Is there any way other than this from which I can get the screenshot of the whole table scrolling the webpage?

Does the table have an ID? If so you could take a screenshot of the table using that id rather than the element name?
WebElement ele = driver.findElement(By.id("yourTableID"));
From the similar question (but not Xpath):
How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?
Seems to suggest you might need to force the window to be larger before taking the screenshot?
this.driver.manage().window().setSize(new Dimension(1680, 1050));

You can use this package https://www.nuget.org/packages/Noksa.WebDriver.ScreenshotsExtensions/
In order to take a screenshot of the element, use the OnlyElementDecorator:
using WDSE;
using WDSE.Decorators;
using WDSE.ScreenshotMaker;
var vcs = new OnlyElementDecorator(new ScreenshotMaker());
var screen = _driver.TakeScreenshot(vcs);

Related

Selenium C# How to FindElement of image?

Im working on a project that takes a screenshot of a product image.
This image is then cropped and saved.
Here is the code
Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
using (var ms = new MemoryStream(screenshot.AsByteArray))
using (var imgShot = Image.FromStream(ms))
using (var src = new Bitmap(imgShot))
{
IWebElement element = driver.FindElement(By.Name("viewport"));
Rectangle cropRect = new Rectangle(element.Location.X, element.Location.Y, element.Size.Width, element.Size.Height);
var clone = src.Clone(cropRect, src.PixelFormat);
clone.Save(_SavePath);
}
Referring to the image link below, How would I use C# Selenium driver.FindElement in order to select this image:
This is what I'm trying to use:
IWebElement element = driver.FindElement(By.Name("viewport"));
Image:
http://dealer.rectron.co.za/ImageServer.aspx?QualifyingProductID=c471d4fd-fd97-48b8-a709-441b18c1830c
Here is the HTML Code of the Image:
<html><head><meta name="viewport" content="width=device-width, minimum-scale=0.1"><title>ImageServer.aspx (335×328)</title></head><body style="margin: 0px; background: #0e0e0e;">[![][1]][1]</body></html>
When I try to crop the image, I get the following exception:
System.ArgumentException: 'Rectangle '{X=0,Y=0,Width=0,Height=0}' cannot have a width or height equal to 0.'
I think that they way I'm using FindElement, might be incorrect.
Thanks
Your locator is incorrect, you are creating a <meta> element that does not appear on the page and has no dimensions. You need to fix the locator as follows: IWebElement element = driver.FindElement(By.XPath("//img"));

Load image to image box using C#

I am trying to load an image to picture box the below way worked with me.
image1.Image = Properties.Resources._0;
what it i want make the code reading from resources as variable name like the way below.
var imagename = _0;
image1.Image = Properties.Resources.imagename;
Thanks
Use the ResourceManager and pass it a string:
var imageName = "_0";
image1.Image = (Image)Properties.Resources.ResourceManager.GetObject(imageName);

Live Tile not working due to error in setting image?

The App.xaml.cs page of my app contains the following method.
public static void SendLiveTileUpdate(Record rr)
{
string imageUristring = "ms-appdata:///local/" + rr.Id.ToString() + ".jpg";
XmlDocument wideTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideImageAndText01);
XmlNodeList wideTileTextAttrib = wideTileXml.GetElementsByTagName("text");
wideTileTextAttrib[0].InnerText = rr.Name;
XmlNodeList wideTileImageAttrib = wideTileXml.GetElementsByTagName("image");
//((XmlElement)wideTileImageAttrib[0]).SetAttribute("src", "ms-appdata:///local/" + rr.Id.ToString() + ".jpg");
((XmlElement)wideTileImageAttrib[0]).SetAttribute("src", imageUristring);
((XmlElement)wideTileImageAttrib[0]).SetAttribute("alt", "Image");
//Wide tile Layout done
XmlDocument sqTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquareImage);
XmlNodeList sqTileImageAttrib = sqTileXml.GetElementsByTagName("image");
((XmlElement)sqTileImageAttrib[0]).SetAttribute("src", imageUristring);
((XmlElement)sqTileImageAttrib[0]).SetAttribute("alt", "Image");
IXmlNode node = wideTileXml.ImportNode(sqTileXml.GetElementsByTagName("binding").Item(0), true);
wideTileXml.GetElementsByTagName("visual").Item(0).AppendChild(node);
//Square tile set and added to wide tile xml
TileNotification tileNot = new TileNotification(wideTileXml);
tileNot.ExpirationTime = DateTime.Now.AddDays(5);
updater.Update(tileNot);
}
On the page there is also the global variable updater, which is used on page initialization to call EnableNotificationQueue(true) (then later to update the queue as shown).
The problem is that when this code is run it doesn't work. I have deduced that it is something to do with the images because when the image assignments are excluded the live tile updates with the value of rr.Id.ToString(), but included the tile is never updated. this images referenced by imageUristring are present in the apps local storage (and the name corresponds with the Id of the method parameter), yet it still does not work. The images in question are under 200KB, and are 1920x1080. (I think that they will be scaled to fit the tile?)
What am I doing wrong? How could I get the tile to update with the image stored in the local storage?
Your images must be <= 1024x1024. From http://msdn.microsoft.com/en-us/library/windows/apps/Hh781198.aspx:
Tile images must have dimensions less than or equal to 1024x1024
pixels, have a file size of less than or equal to 200 KB, and be of
type .png, .jpg, .jpeg, or .gif.

Automate WebBrowser.ShowSaveAsDialog() or alternative method

Basically I wan't to save an image loaded in a webBrowser control. The only way I can get this to work at the moment is by showing the save as dialog.
is there a way to pass in a path and make it save itself? (hide the dialog I ask to show!)
is there another way to save the image? I can't seem to get documentstream to work. I have also tried webclient.filedownload(...) but get an error 302 ( "(302) Found Redirect.")
DownloadFileAsync gives no error but an empty jpeg file?
files are always jpegs, but not always at same location.
You should go with HttpWebRequest.
It has the capability to follow a 302 automatically.
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.contoso.com");
//increase this number if there are more then one redirects.
myHttpWebRequest.MaximumAutomaticRedirections = 1;
myHttpWebRequest.AllowAutoRedirect = true;
var myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
var buff = new byte[myHttpWebResponse.ContentLength];
// here you specify the path to the file. The path in this example is : image.jpg
// if you want to store it in the application root use:
// AppDomain.CurrentDomain.BaseDirectory + "\\image.jpg"
using (var sw = new BinaryWriter(File.Open("c:\\image.jpg", FileMode.OpenOrCreate)))
{
using (var br = new BinaryReader (myHttpWebResponse.GetResponseStream ()))
{
br.Read(buff, 0, (int)myHttpWebResponse.ContentLength);
sw.Write(buff);
}
}

How do I clear the image cache after editing an image on my site?

I'm using an outside page to update an image in my system. When I'm redirected back to the page I've worked in, I still see the old picture. I don't see my changes until I press ctrl+f5. Is their any way to redirect with history delete or any other solution?
Add a query string to your image source, it will prevent the browser from caching it. Some people use the date, I prefer the GUID
Guid g = Guid.NewGuid();
string GuidString = Convert.ToBase64String(g.ToByteArray());
GuidString = GuidString.Replace("=", "");
GuidString = GuidString.Replace("+", "");
Image1.ImageUrl = "/path/to/new/image.jpg?r=" + GuidString;
It will end up making your image source look similar to this:
<img src="/path/to/image.jpg?r=Vqad3W8ZUG6oXgFzZIw" id="Image1" runat="server" />
The decision to refresh or not is up to the browser. A standard technique for solving this is to add a timestamp to your images. For example:
<img src='/images/foo.jpg?ts=1'/>
When you update the image, send back:
<img src='/images/foo.jpg?ts=2'/>
The browser will see two different URL and request the image again. You can use a timestamp (last modified time of the file), a hash of the file contents, an incrementing integer, ... Anything to change the URL and force the browser to reload.
N.B. When serving static files, web servers will ignore the query string. So you don't need any code running to implement this. This technique also works well for any content that you want to force a refresh on including CSS, JS, ...
in C# there is a much simpler way. you set the bitmapimage CreateOptions to BitmapCreateOptions.IgnoreImageCache and it forces the image to load from file instead of using existing cache.
var bi = new BitmapImage();
StorageFile file = await StorageFile.GetFileFromPathAsync(filepath);
const uint requestedSize = 400;
const ThumbnailMode thumbnailMode = ThumbnailMode.PicturesView;
const ThumbnailOptions thumbnailOptions = ThumbnailOptions.ResizeThumbnail;
StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(thumbnailMode, requestedSize, thumbnailOptions);
bi.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
bi.DecodePixelHeight = 200;
bi.DecodePixelWidth = 200;
bi.SetSource(thumbnail);
return bi;

Categories

Resources