Takes a screenshot of the current screen.

@param filename
the name of the file where the screenshot will be saved
@throws IOException
if something goes wrong while saving the screenshot
499331
public void takeScreenshot(String filename) throws IOException {
		File screenshot = ((TakesScreenshot) driver)
				.getScreenshotAs(OutputType.FILE);
		FileUtils.copyFile(screenshot, new File(filename));
	}
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];
  }
1305690
public File newFile(String fileName) throws IOException {
        File file = new File(getRoot(), fileName);
        if (!file.createNewFile()) {
            throw new IOException(
                    "a file with the name \'" + fileName + "\' already exists in the test folder");
        }
        return file;
    }
753516
public static void delete(String filename) {
		File file = new File(filename);
		if(file.exists()){
			file.delete();
		}
	}
459640
public void setScreenImage(byte[] content) {
        logger.entering(content);
        this.screenImage = Arrays.copyOf(content, content.length);
        logger.exiting();
    }
172615
def take_screenshot(to_file = nil, opts = {})
        # puts "calling new take screenshot: #{$screenshot_supported}"
        # unless $screenshot_supported
        #   puts " [WARN] Screenhost not supported, check whether win32screenshot gem is installed" 
        #   return
        # end

        if to_file
          screenshot_image_filepath = to_file
        else
          screenshot_image_filename =  "screenshot_" + Time.now.strftime("%m%d%H%M%S") + ".jpg"
          the_dump_dir = opts[:to_dir] || default_dump_dir
          FileUtils.mkdir_p(the_dump_dir) unless File.exists?(the_dump_dir)
          screenshot_image_filepath = File.join(the_dump_dir, screenshot_image_filename)
          screenshot_image_filepath.gsub!("/", "\\") if is_windows?

          FileUtils.rm_f(screenshot_image_filepath) if File.exist?(screenshot_image_filepath)
        end

          # save screenshot with selenium
          @web_browser.driver.save_screenshot(screenshot_image_filepath)
          notify_screenshot_location(screenshot_image_filepath)

      end
1367632
public void readFile(String filename) throws ConverterException {
        try {
            content = "";
            final InputStream input = ResourceManager.getInputStream(filename);
            while (input.available() > 0) {
                content = content + (char) input.read();
            }
            input.close();
        } catch (Exception e) {
            throw new ConverterException(e);
        }
    }
537379
protected void save(final String fileName, final SessionListener callback) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                Exception thrownException = null;
                try {
                    save(fileName);
                } catch (Exception e) {
                	// ZAP: Log exceptions
                	log.warn(e.getMessage(), e);
                    thrownException = e;
                }
                if (callback != null) {
                    callback.sessionSaved(thrownException);
                }
            }
        });
        t.setPriority(Thread.NORM_PRIORITY-2);
        t.start();
    }
121513
public void write(String filename) throws Exception {
    data = new TiffOutputStream(input);
    data.setByteOrder(byteOrder);
    try {
      data.create(filename);
      writeHeader();
      writeIfds();
      data.close();
    } catch (Exception ex) {
      ex.printStackTrace();
      if (data != null) {
        data.close();
      }
      throw ex;
    }
  }
65678
public function takeScreenshot($name = NULL) {
    $file_name = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $name;
    $message = "Screenshot created in @file_name";
    $this->createScreenshot($file_name, $message, FALSE);
  }
967453
protected void writeScreenshot(ScreenshotEntry screenshotEntry) throws IOException {

        int heigth = screenshotEntry.getHeight() * Integer.parseInt(this.configuration.getImageHeight()) / 100;
        int width = screenshotEntry.getWidth() * Integer.parseInt(this.configuration.getImageWidth()) / 100;

        boolean large = width > Integer.parseInt(this.configuration.getMaxImageWidth());

        if (large) {

            writer.append(".").append(screenshotEntry.getPhase().name()).append(NEW_LINE);
            writer.append(screenshotEntry.getLink()).append(" -> file://").append(screenshotEntry.getPath()).append("[")
            .append(this.resourceBundle.getString("asciidoc.reporter.screenshot"))
            .append("]").append(NEW_LINE).append(NEW_LINE);

        } else {

            writer.append(".").append(screenshotEntry.getPhase().name()).append(NEW_LINE);
            writer.append("image::").append(screenshotEntry.getLink())
                .append("[screenshot," + width + "," + heigth + "]")
                .append(NEW_LINE).append(NEW_LINE);
        }

    }
981132
public static void takeScreenshotOfElement(IElement element, File toSaveAs) throws IOException, WidgetException {
		
		for(int i = 0; i < 10; i++) { //Loop up to 10x to ensure a clean screenshot was taken
			log.info("Taking screen shot of locator " + element.getByLocator() + " ... attempt #" + (i+1));
			
			//Scroll to element
			element.scrollTo();
			
			//Take picture of the page
			WebDriver wd = SessionManager.getInstance().getCurrentSession().getWrappedDriver();
			File screenshot;
			boolean isRemote = false;
			if(!(wd instanceof RemoteWebDriver)) {
				screenshot = ((TakesScreenshot) wd).getScreenshotAs(OutputType.FILE);		
			}
			else {
				Augmenter augmenter = new Augmenter();
				screenshot = ((TakesScreenshot) augmenter.augment(wd)).getScreenshotAs(OutputType.FILE);
				isRemote = true;
			}
			BufferedImage fullImage = ImageIO.read(screenshot);
			WebElement ele = element.getWebElement();
			
			//Parse out the picture of the element
			Point point = ele.getLocation();
			int eleWidth = ele.getSize().getWidth();
			int eleHeight = ele.getSize().getHeight();
			int x; 
			int y;
			if(isRemote) {
				x = ((Locatable)ele).getCoordinates().inViewPort().getX();
				y = ((Locatable)ele).getCoordinates().inViewPort().getY();
			}
			else {
				x = point.getX();
				y = point.getY();
			}
			log.debug("Screenshot coordinates x: "+x+", y: "+y);
			BufferedImage eleScreenshot = fullImage.getSubimage(x, y, eleWidth, eleHeight);	
			ImageIO.write(eleScreenshot, "png", screenshot);
			
			//Ensure clean snapshot (sometimes WebDriver takes bad pictures and they turn out all black)
			if(!isBlack(ImageIO.read(screenshot))) {
				FileUtils.copyFile(screenshot, toSaveAs);
				break;
			}
		}
	}
1170964
public static void backup(final String filename) throws IOException {
        final File dest = createFile(filename);
        if (dest.exists()) {
            final File backupFile = generateBackupFilename(filename);
            LOGGER.debug("backing up file from " + filename + " to "
                    + backupFile.getName());
            if (!dest.renameTo(backupFile)) {
                throw new IOException("Could not rename file from "
                        + dest.getName() + " to " + backupFile.getName());
            }
        }
    }
118466
public void save() throws IOException {
        FileChooser.SimpleFileFilter filter = FileChooser.SimpleFileFilter.getWritableImageFIlter();
        JFileChooser chooser = FileChooser.getInstance();
        chooser.setFileFilter(filter);
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.setSelectedFiles(new File[0]);
        int returnVal = chooser.showSaveDialog(null);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();
            if (!filter.accept(file)) {
                file = new File(file.getParentFile(), file.getName() + ".png");
            }
            save(file);
        }
    }
512357
def screenshot(self, filename=None, scale=1.0, method=None):
        
        image = None
        method = method or self._screenshot_method
        if method == 'minicap':
            try:
                image = self._adb_minicap(scale)
            except Exception as e:
                logger.warn("use minicap failed, fallback to screencap. error detail: %s", e)
                self._screenshot_method = 'screencap'
                return self.screenshot(filename=filename, scale=scale)
        elif method == 'screencap':
            image = self._adb_screencap(scale)
        else:
            raise RuntimeError("No such method(%s)" % method)

        if filename:
            image.save(filename)
        return image
1123467
public void save(File file) throws IOException {
        try (FileOutputStream fout = new FileOutputStream(file)) {
            save(fout);
        }
    }
799061
protected void snapshot(String fileName) throws Exception {
	    configuration.save(new File(fileName));
        model.snapshotSessionDb(this.fileName, fileName);
	}