1

How can I get an image on a webpage with Selenium and encode it to a Base64 string which gets added to a variable? I'm using Selenium C# but any language will probably work.

Keavon
  • 6,837
  • 9
  • 51
  • 79

2 Answers2

2

I am not quite sure what you are asking. What do you mean by "get an image on a webpage"? Do you mean:

  1. grab a screenshot of your page and compare it with some given value? or
  2. take a screenshot of specific element on webpage?
  3. download an image contained in (ie) <img> tag and do something with it?

For taking screenshots, it is widely disucessed here. Although mostly java solutions, they probably could be ported to C# with ease. If what you need is nr 3, then get the URL (ie using xpath //img[@id=\"yourId\"]@src ) and download it using something like WebClient and convert that to base64:

  var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
  var baseString = System.Convert.ToBase64String(plainTextBytes);
Community
  • 1
  • 1
Erki M.
  • 5,022
  • 1
  • 48
  • 74
  • I am referring to option 3, the image in an `` tag. – Keavon Mar 02 '14 at 23:01
  • 1
    1. get the image url. 2. download it 3. open the bytestream of the file 4. convert it to base64. . .. ... X. $$$profit$$$ – Erki M. Mar 02 '14 at 23:03
  • What if the image URL expires after it is first loaded in the page? Is there a way to take it from the local loaded copy? – Keavon Mar 03 '14 at 01:38
  • If the link is dead on the server, then you are out of luck with this approach. Anyway, you could possible take screenshot of that image. Check [here](http://stackoverflow.com/questions/3422262/take-a-screenshot-with-selenium-webdriver/21376753#21376753) . It is java implementation, but you can port it to C#. You could probably use the [Bitmap](http://msdn.microsoft.com/en-us/library/system.drawing.bitmap%28v=vs.110%29.aspx) class by using the `Clone()` method. – Erki M. Mar 03 '14 at 09:09
  • Someone already implemented and shared. Check [here](http://webcache.googleusercontent.com/search?q=cache:x-X285hepOEJ:brantleytec.blogspot.com/2013/02/webdriver-screen-shot-in-c.html+&cd=3&hl=et&ct=clnk&gl=ee&client=firefox-a) – Erki M. Mar 03 '14 at 09:11
1

This code will helps you, I am using it for my own report, instead of storing report in seperate location, better to convert into base64 form and add it to report.

   String Base64StringofScreenshot="";
    File src = ((TakesScreenshot) driverThread).getScreenshotAs(OutputType.FILE);
    byte[] fileContent = FileUtils.readFileToByteArray(src);
    Base64StringofScreenshot = "data:image/png;base64,"+Base64.getEncoder().encodeToString(fileContent);
ravi creed
  • 371
  • 3
  • 6