To be used when need to screenshot particular element.

@param driver  WebDriver instance
@param element WebElement instance to be screen shot
@param useDevicePixelRatio whether or not take into account device pixel ratio
@return ElementSnapshot instance
765693
public static ElementSnapshot shootElement(WebDriver driver, WebElement element, boolean useDevicePixelRatio) {
        Browser browser = new Browser(driver, useDevicePixelRatio);
        ElementSnapshot elementSnapshot = new ElementSnapshot(driver, browser.getDevicePixelRatio());
        browser.scrollToElement(element);
        elementSnapshot.setImage(browser.takeScreenshot(),browser.getBoundingClientRect(element));
        return elementSnapshot;
    }
390352
private Element buildImageElement(Media media, Element element) {
    if (media.isValid()) {
      element.setAttribute("src", media.getUrl());
    }
    return element;
  }
761927
function bracketDevicePixelRatio() {
      var i, scale,
        brackets = [ 1, 1.3, 1.5, 2, 2.6, 3 ],
        baseRatio = window.devicePixelRatio || 1;

      for ( i = 0; i < brackets.length; i++ ) {
        scale = brackets[ i ];

        if ( scale >= baseRatio || ( baseRatio - scale ) < 0.1 ) {
          return scale;
        }
      }
      return brackets[ brackets.length - 1 ];
    }
1126273
public static BufferedImage resizeScreenshotIfNeeded(WebDriver driver, BufferedImage screenshotImage) {
        Double devicePixelRatio = 1.0;

        try {
            devicePixelRatio = ((Number) ((JavascriptExecutor) driver).executeScript(JS_RETRIEVE_DEVICE_PIXEL_RATIO)).doubleValue();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        if (devicePixelRatio > 1.0 && screenshotImage.getWidth() > 0) {
            Long screenSize = ((Number) ((JavascriptExecutor) driver).executeScript("return Math.max(" +
                            "document.body.scrollWidth, document.documentElement.scrollWidth," +
                            "document.body.offsetWidth, document.documentElement.offsetWidth," +
                            "document.body.clientWidth, document.documentElement.clientWidth);"
            )).longValue();

            Double estimatedPixelRatio = ((double)screenshotImage.getWidth()) / ((double)screenSize);

            if (estimatedPixelRatio > 1.0) {

                int newWidth = (int) (screenshotImage.getWidth() / estimatedPixelRatio);
                int newHeight = (int) (screenshotImage.getHeight() / estimatedPixelRatio);

                Image tmp = screenshotImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
                BufferedImage scaledImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);

                Graphics2D g2d = scaledImage.createGraphics();
                g2d.drawImage(tmp, 0, 0, null);
                g2d.dispose();

                return scaledImage;
            }
            else return screenshotImage;
        }
        else return screenshotImage;
    }
714550
@Override
	public void doTag() throws JspException, IOException {
		final PageContext pageContext = (PageContext)getJspContext();
		final ServletRequest request = pageContext.getRequest();

		// Get the current capture state
		CaptureLevel captureLevel = CurrentCaptureLevel.getCaptureLevel(request);
		if(captureLevel.compareTo(CaptureLevel.META) >= 0) {
			E elem = createElement();
			element = elem;
			evaluateAttributes(elem, pageContext.getELContext());

			// Set currentNode
			Node parentNode = CurrentNode.getCurrentNode(request);
			CurrentNode.setCurrentNode(request, elem);
			try {
				// Find the optional parent page
				Page currentPage = CurrentPage.getCurrentPage(request);
				if(currentPage != null) currentPage.addElement(elem);

				Long elementKey;
				if(parentNode != null) elementKey = parentNode.addChildElement(elem, this);
				else elementKey = null;
				// Freeze element once body done
				try {
					doBody(elem, captureLevel);
				} finally {
					// Note: Page freezes all of its elements
					if(currentPage == null) elem.freeze();
				}
				// Write now
				if(captureLevel == CaptureLevel.BODY) {
					JspWriter out = pageContext.getOut();
					if(elementKey == null) {
						try {
							writeTo(out, new PageElementContext(pageContext));
						} catch(JspException | IOException | RuntimeException e) {
							throw e;
						} catch(Exception e) {
							throw new JspTagException(e);
						}
					} else {
						// Write an element marker instead
						// TODO: Do not write element marker for empty elements, such as passwordTable at http://localhost:8080/docs/ao/infrastructure/ao/regions/mobile-al/workstations/francis.aoindustries.com/
						NodeBodyWriter.writeElementMarker(elementKey, out);
					}
				}
			} finally {
				// Restore previous currentNode
				CurrentNode.setCurrentNode(request, parentNode);
			}
		}
	}
91907
@Override
    DeviceProxy get_device_i(int i) {
	synchronized (this) {
	    DeviceProxy dp = null;
	    final Iterator it = elements.iterator();
	    while (dp == null && it.hasNext()) {
		final GroupElement e = (GroupElement) it.next();
		dp = e.get_device_i(i--);
	    }
	    return dp;
	}
    }
549021
static float getRelativeX (NativeEvent e, Element target) {
    return (e.getClientX() - target.getAbsoluteLeft() + target.getScrollLeft() +
            target.getOwnerDocument().getScrollLeft()) / HtmlGraphics.experimentalScale;
  }
409926
public static GraphicsDevice getGraphicsDeviceIsShowingOn(final Component component)
	{
		final GraphicsDevice graphicsDevice = component.getGraphicsConfiguration().getDevice();
		return graphicsDevice;
	}
898429
protected String nativeCaptureToDataURL(CanvasElement canvas, Element element, String mimeType) {
        VideoElement videoElement = (VideoElement) element;
        int width = videoElement.getVideoWidth();
        int height = videoElement.getVideoHeight();
        if (Double.isNaN(width) || Double.isNaN(height)) {
            width = videoElement.getClientWidth();
            height = videoElement.getClientHeight();
        }
        canvas.setWidth(width);
        canvas.setHeight(height);
        Context2d context = canvas.getContext2d();
        context.drawImage(videoElement, 0, 0, width, height);
        return canvas.toDataUrl(mimeType);
    }
877712
def is_webdriver_ios(webdriver):
        
        browser = webdriver.capabilities['browserName']

        if (browser == u('iPhone') or 
            browser == u('iPad')):
            return True
        else:
            return False
486566
public static WebElement isElementPresentAndGetFirstOne(By element) {

        final WebDriver webDriver = Context.getDriver();

        webDriver.manage().timeouts().implicitlyWait(DriverFactory.IMPLICIT_WAIT * 2, TimeUnit.MICROSECONDS);

        final List<WebElement> foundElements = webDriver.findElements(element);
        final boolean exists = !foundElements.isEmpty();

        webDriver.manage().timeouts().implicitlyWait(DriverFactory.IMPLICIT_WAIT, TimeUnit.MICROSECONDS);

        if (exists) {
            return foundElements.get(0);
        } else {
            return null;
        }

    }
417420
public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {
    OperaWebElement body = (OperaWebElement) findElementByCssSelector(":root");
    return target.convertFromPngBytes(body.captureScreen().getPng());
  }
655386
@Override
  @SuppressWarnings("deprecation")
  public byte[] takeScreenshot() {
    ViewHierarchyAnalyzer viewAnalyzer = ViewHierarchyAnalyzer.getDefaultInstance();

    // TODO ddary review later, but with getRecentDecorView() it seems to work better
    // long drawingTime = 0;
    // View container = null;
    // for (View view : viewAnalyzer.getTopLevelViews()) {
    // if (view != null && view.isShown() && view.hasWindowFocus()
    // && view.getDrawingTime() > drawingTime) {
    // container = view;
    // drawingTime = view.getDrawingTime();
    // }
    // }
    // final View mainView = container;
    final View mainView = viewAnalyzer.getRecentDecorView();
    if (mainView == null) {
      throw new SelendroidException("No open windows.");
    }
    done = false;
    long end =
        System.currentTimeMillis() + serverInstrumentation.getAndroidWait().getTimeoutInMillis();
    final byte[][] rawPng = new byte[1][1];
    serverInstrumentation.getCurrentActivity().runOnUiThread(new Runnable() {
      public void run() {
        synchronized (syncObject) {
          Display display =
              serverInstrumentation.getCurrentActivity().getWindowManager().getDefaultDisplay();
          Point size = new Point();
          try {
            display.getSize(size);
          } catch (NoSuchMethodError ignore) { // Older than api level 13
            size.x = display.getWidth();
            size.y = display.getHeight();
          }

          // Get root view
          View view = mainView.getRootView();

          // Create the bitmap to use to draw the screenshot
          final Bitmap bitmap = Bitmap.createBitmap(size.x, size.y, Bitmap.Config.ARGB_8888);
          final Canvas canvas = new Canvas(bitmap);

          // Get current theme to know which background to use
          final Activity activity = serverInstrumentation.getCurrentActivity();
          final Theme theme = activity.getTheme();
          final TypedArray ta =
              theme.obtainStyledAttributes(new int[] {android.R.attr.windowBackground});
          final int res = ta.getResourceId(0, 0);
          final Drawable background = activity.getResources().getDrawable(res);

          // Draw background
          background.draw(canvas);

          // Draw views
          view.draw(canvas);

          ByteArrayOutputStream stream = new ByteArrayOutputStream();
          if (!bitmap.compress(Bitmap.CompressFormat.PNG, 70, stream)) {
            throw new RuntimeException("Error while compressing screenshot image.");
          }
          try {
            stream.flush();
            stream.close();
          } catch (IOException e) {
            throw new RuntimeException("I/O Error while capturing screenshot: " + e.getMessage());
          } finally {
            Closeable closeable = (Closeable) stream;
            try {
              if (closeable != null) {
                closeable.close();
              }
            } catch (IOException ioe) {
              // ignore
            }
          }
          rawPng[0] = stream.toByteArray();
          mainView.destroyDrawingCache();
          done = true;
          syncObject.notify();
        }
      }
    });

    waitForDone(end, serverInstrumentation.getAndroidWait().getTimeoutInMillis(),
        "Failed to take screenshot.");
    return rawPng[0];
  }
219001
def take_reference_screenshot(webdriver, file_name):
        
        folder_location = os.path.join(ProjectUtils.get_project_root(),
                                       WebScreenShotUtil.REFERENCE_SCREEN_SHOT_LOCATION)

        WebScreenShotUtil.__capture_screenshot(
            webdriver, folder_location, file_name + ".png")
731945
def add_assert_screenshot_methods(context_or_world, scenario):
    
    file_suffix = scenario.name

    def assert_screenshot(element_or_selector, filename, threshold=0, exclude_elements=[], driver_wrapper=None,
                          force=False):
        VisualTest(driver_wrapper, force).assert_screenshot(element_or_selector, filename, file_suffix, threshold,
                                                            exclude_elements)

    def assert_full_screenshot(filename, threshold=0, exclude_elements=[], driver_wrapper=None, force=False):
        VisualTest(driver_wrapper, force).assert_screenshot(None, filename, file_suffix, threshold, exclude_elements)

    # Monkey patching assert_screenshot method in PageElement to use the correct test name
    def assert_screenshot_page_element(self, filename, threshold=0, exclude_elements=[], force=False):
        VisualTest(self.driver_wrapper, force).assert_screenshot(self.web_element, filename, file_suffix, threshold,
                                                                 exclude_elements)

    context_or_world.assert_screenshot = assert_screenshot
    context_or_world.assert_full_screenshot = assert_full_screenshot
    PageElement.assert_screenshot = assert_screenshot_page_element
180130
function getImageIdSpecificToolState(element, toolType) {
    const enabledElement = external.cornerstone.getEnabledElement(element);
    // If we don't have any tool state for this imageId, return undefined

    if (
      !enabledElement.image ||
      toolState.hasOwnProperty(enabledElement.image.imageId) === false
    ) {
      return;
    }

    const imageIdToolState = toolState[enabledElement.image.imageId];

    // If we don't have tool state for this type of tool, return undefined
    if (imageIdToolState.hasOwnProperty(toolType) === false) {
      return;
    }

    const toolData = imageIdToolState[toolType];

    return toolData;
  }
1225878
function simulateScreenshot(driver, w, h, browserName) {
  var scrollPos;
  var isRetina;
  var rawImageString;

  return browser
    .executeScript(driver, hideScrollbarScript + infoScript)
    .then(function(info) {
      scrollPos = info.slice(0, 4);
      isRetina = info[4];
      return browser.takeScreenshot(driver);
    })
    .then(function(res) {
      rawImageString = res;
      return browser.executeScript(driver, showScrollbarScript);
    })
    .then(function() {
      var left = Math.min(scrollPos[0], scrollPos[2] - w);
      var top = Math.min(scrollPos[1], scrollPos[3] - h);

      var config = {
        left: left < 0 ? 0 : left,
        top: top < 0 ? 0 : top,
        width: w,
        height: h,
      };

      if (browserName === 'chrome') {
        // chrome already takes partial ss. Browser size is adjusted correctly
        // except for width. If it's retina then instead of cropping w, we need
        // to crop w * 2. FF still takes the right dimensions regardless of
        // retina-ness so nothing to adjust here.
        config = {
          left: 0,
          top: 0,
          width: isRetina ? w * 2 : w,
          height: 99999,
        };
      }
      var buf = new Buffer(rawImageString, 'base64');

      return cropP(buf, config);
    });
}