How to save a canvas as PNG in Selenium?

SeleniumAutomation TestingTesting Tools

We can save a canvas as png in Selenium. We shall first identify the canvas with the help of any locators like xpath, css, and so on. Then obtain the value of src attribute with the getAttribute method.

We shall build an URL in java with the class URL and have a BufferedImage via ImageIOclass. Then utilize the same class to save the canvas with the png extension in a location.

Let us try to save the below image within the project folder.


Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
public class SaveCanvas{
   public static void main(String[] args) {
      System.setProperty("", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify canvas
      WebElement l = driver.findElement(By.xpath("//img[@title='Tutorialspoint']"));
      // get src value of element
      String v = l.getAttribute("src");
      // creating URL
      URL i = new URL(v);
      //having BufferedImage with ImageIO class
      BufferedImage s =;
      // save image in location with .png extension
      ImageIO.write(s, "png", new File("Logo.png"));


Logo.png file gets created within the project folder.

Published on 28-Dec-2020 13:14:44