Takes a snapshot of the device and return it as a PIL Image.
767379
def takeSnapshot(self, reconnect=False):
        '''
        
        '''

        if PROFILE:
            profileStart()

        global PIL_AVAILABLE
        if not PIL_AVAILABLE:
            try:
                global Image
                from PIL import Image
                PIL_AVAILABLE = True
            except:
                raise Exception("You have to install PIL to use takeSnapshot()")

        sdk_version = self.getSdkVersion()
        USE_ADB_FRAMEBUFFER_METHOD = (sdk_version < 14 or sdk_version >= 23)
        if USE_ADB_FRAMEBUFFER_METHOD:
            self.__checkTransport()

            self.__send('framebuffer:', checkok=True, reconnect=False)
            # case 1: // version
            #           return 12; // bpp, size, width, height, 4*(length, offset)
            # case 2: // version
            #           return 13; // bpp, colorSpace, size, width, height, 4*(length, offset)
            # let's assume version==1 and change later if it's not
            received = self.__receive(1 * 4 + 12 * 4)
            (version, bpp, size, width, height, roffset, rlen, boffset, blen, goffset, glen, aoffset, alen) = \
                struct.unpack('<' + 'L' * 13, received)
            if version == 2:
                # receive one more
                received += self.__receive(4)
                (version, bpp, colorspace, size, width, height, roffset, rlen, boffset, blen, goffset, glen, aoffset,
                 alen) = struct.unpack('<' + 'L' * 14, received)
            if DEBUG:
                if version == 1:
                    print >> sys.stderr, "    takeSnapshot:", (
                        version, bpp, size, width, height, roffset, rlen, boffset, blen, goffset, glen, aoffset, alen)
                elif version == 2:
                    print >> sys.stderr, "    takeSnapshot:", (
                        version, bpp, colorspace, width, height, roffset, rlen, boffset, blen, goffset, glen, aoffset,
                        alen)
                else:
                    print >> sys.stderr, "    takeSnapshot: unknown version", version

            offsets = {roffset: 'R', goffset: 'G', boffset: 'B'}
            if bpp == 32:
                if alen != 0:
                    offsets[aoffset] = 'A'
                else:
                    warnings.warn('''framebuffer is specified as 32bpp but alpha length is 0''')
            argMode = ''.join([offsets[o] for o in sorted(offsets)])
            if DEBUG:
                if version == 1:
                    print >> sys.stderr, "    takeSnapshot:", (
                        version, bpp, size, width, height, roffset, rlen, boffset, blen, goffset, blen, aoffset, alen,
                        argMode)
                elif version == 2:
                    print >> sys.stderr, "    takeSnapshot:", (
                        version, bpp, colorspace, size, width, height, roffset, rlen, boffset, blen, goffset, blen,
                        aoffset, alen,
                        argMode)

            if argMode == 'BGRA':
                argMode = 'RGBA'
            if bpp == 16:
                mode = 'RGB'
                argMode += ';16'
            else:
                mode = argMode
            self.__send('\0', checkok=False, reconnect=False)
            if DEBUG:
                print >> sys.stderr, "    takeSnapshot: reading %d bytes" % size
            received = self.__receive(size)
            if reconnect:
                self.socket = AdbClient.connect(self.hostname, self.port, self.timeout)
                self.__setTransport()
            if DEBUG:
                print >> sys.stderr, "    takeSnapshot: Image.frombuffer(%s, %s, %s, %s, %s, %s, %s)" % (
                    mode, (width, height), 'data', 'raw', argMode, 0, 1)
            image = Image.frombuffer(mode, (width, height), received, 'raw', argMode, 0, 1)
        else:
            # ALTERNATIVE_METHOD: screencap
            received = self.shell('/system/bin/screencap -p').replace("\r\n", "\n")
            if not received:
                raise RuntimeError('"/system/bin/screencap -p" result was empty')
            stream = StringIO.StringIO(received)
            try:
                image = Image.open(stream)
            except IOError, ex:
                print >> sys.stderr, ex
                print >> sys.stderr, repr(stream)
                print >> sys.stderr, repr(received)
                raise RuntimeError('Cannot convert stream to image: ' + ex.message)

        # Just in case let's get the real image size
        (w, h) = image.size
        if w == self.display['height'] and h == self.display['width']:
            # FIXME: We are not catching the 180 degrees rotation here
            if 'orientation' in self.display:
                r = (0, 90, 180, -90)[self.display['orientation']]
            else:
                r = 90
            image = image.rotate(r, expand=1).resize((h, w))

        if PROFILE:
            profileEnd()
        return image
412873
def MobileDeviceProvisioningProfile(self, data=None, subset=None):
        """"""
        return self.factory.get_object(
            jssobjects.MobileDeviceProvisioningProfile, data, subset)
1287936
def _convert(self, format):
        
        if self.format == format:
            return self
        else:
            image = Image(self.pil_image)
            image._format = format
            return image
970498
def get_plain_image_as_widget(self):
        
        pixbuf = self.get_plain_image_as_pixbuf()
        image = Gtk.Image()
        image.set_from_pixbuf(pixbuf)
        image.show()
        return image
1124526
def screen(self):
        """"""
        hwnd = win32gui.GetDesktopWindow()
        left, top, right, bottom = self.rect
        width, height = right-left, bottom-top
        # copy bits to temporary dc
        win32gui.BitBlt(self._hdcmem, 0, 0, width, height, 
                        self._hdcwin, left, top, win32con.SRCCOPY)
        # read bits into buffer
        windll.gdi32.GetDIBits(self._hdcmem, self._hbmp.handle, 0, height, self._buf, ctypes.byref(self._bi), win32con.DIB_RGB_COLORS)
        # make a PIL Image
        img = Image.frombuffer('RGB', (width, height), self._buf, 'raw', 'BGRX', 0, 1)
        img = img.transpose(Image.FLIP_TOP_BOTTOM)
        return img
1343494
def saveViewSnapshot(self, view):
        '''
        
        '''

        if not view:
            raise ValueError("view must be provided to take snapshot")
        filename = self.snapshotDir + os.sep + '${serialno}-' + view.variableNameFromId() + '-${timestamp}' + '.' + self.snapshotFormat.lower()
        d = FileDialog(self, self.device.substituteDeviceTemplate(filename))
        saveAsFilename = d.askSaveAsFilename()
        if saveAsFilename:
            _format = os.path.splitext(saveAsFilename)[1][1:].upper()
            self.printOperation(view, Operation.VIEW_SNAPSHOT, filename, _format)
            view.writeImageToFile(saveAsFilename, _format)
601150
def screenshot(self, filename=None):
        
        tmpfile = tempfile.mktemp(prefix='atx-screencap-', suffix='.tiff')
        try:
            idevice("screenshot", "--udid", self.udid, tmpfile)
        except subprocess.CalledProcessError as e:
            sys.exit(e.message)

        try:
            image = Image.open(tmpfile)
            image.load()
            if filename:
                image.save(filename)
            return image
        finally:
            if os.path.exists(tmpfile):
                os.unlink(tmpfile)
79281
function Snapsie() {
    // private methods
    
    function isQuirksMode(inDocument) {
        return (inDocument.compatMode == 'BackCompat');
    }
    
    function getDrawableElement(inDocument) {
        if (isQuirksMode(inDocument)) {
            var body = inDocument.getElementsByTagName('body')[0];
            return body;
        }
        else {
            // standards mode
            return inDocument.documentElement;
        }
    }
    
    /**
     * Returns the canonical Windows path for a given path. This means
     * basically replacing any forwards slashes with backslashes.
     *
     * @param path  the path whose canonical form to return
     */
    function getCanonicalPath(path) {
        path = path.replace(/\//g, '\\');
        path = path.replace(/\\\\/g, '\\');
        return path;
    }

    // public methods
    
    /**
     * Saves a screenshot of the current document to a file. If frameId is
     * specified, a screenshot of just the frame is captured instead.
     *
     * @param outputFile  the file to which to save the screenshot
     * @param frameId     the frame to capture; omit to capture entire document
     */
    this.saveSnapshot = function(outputFile, frameId) {
        var drawableElement = getDrawableElement(document);
        var drawableInfo = {
              overflow  : drawableElement.style.overflow
            , scrollLeft: drawableElement.scrollLeft
            , scrollTop : drawableElement.scrollTop
        };
        drawableElement.style.overflow = 'hidden';
        
        var capturableDocument;
        var frameBCR = { left: 0, top: 0 };
        if (!frameId) {
            capturableDocument = document;
        }
        else {
            var frame = document.getElementById(frameId);
            capturableDocument = frame.document;
            
            // scroll as much of the frame into view as possible
            frameBCR = frame.getBoundingClientRect();
            window.scroll(frameBCR.left, frameBCR.top);
            frameBCR = frame.getBoundingClientRect();
        }
        
        var nativeObj = new ActiveXObject('Snapsie.CoSnapsie');
        nativeObj.saveSnapshot(
            getCanonicalPath(outputFile),
            frameId,
            drawableElement.scrollWidth,
            drawableElement.scrollHeight,
            drawableElement.clientWidth,
            drawableElement.clientHeight,
            drawableElement.clientLeft,
            drawableElement.clientTop,
            frameBCR.left,
            frameBCR.top
        );
        
        // revert
        
        drawableElement.style.overflow = drawableInfo.overflow;
        drawableElement.scrollLeft = drawableInfo.scrollLeft;
        drawableElement.scrollTop = drawableInfo.scrollTop;
    }
}
799083
def recoverpix(doc, item):
    
    x = item[0]  # xref of PDF image
    s = item[1]  # xref of its /SMask
    
    try:
        pix1 = fitz.Pixmap(doc, x)     # make pixmap from image
    except:
        print("xref %i " % x + doc._getGCTXerrmsg())
        return None                    # skip if error

    if s == 0:                    # has no /SMask
        return pix1               # no special handling
    
    try:
        pix2 = fitz.Pixmap(doc, s)    # create pixmap of /SMask entry
    except:
        print("cannot create mask %i for image xref %i" % (s,x))
        return pix1               # return w/ failed transparency
        
    # check that we are safe
    if not (pix1.irect == pix2.irect and \
            pix1.alpha == pix2.alpha == 0 and \
            pix2.n == 1):
        print("unexpected /SMask situation: pix1", pix1, "pix2", pix2)
        return pix1
    pix = fitz.Pixmap(pix1)       # copy of pix1, alpha channel added
    pix.setAlpha(pix2.samples)    # treat pix2.samples as alpha values
    pix1 = pix2 = None            # free temp pixmaps
    return pix
733499
def image_data(verbose=False):
  """"""
  # This is a principled use of the `global` statement; don't lint me.
  global _IMAGE_DATA  # pylint: disable=global-statement
  if _IMAGE_DATA is None:
    if verbose:
      logger.info("--- Downloading image.")
    with contextlib.closing(urllib.request.urlopen(IMAGE_URL)) as infile:
      _IMAGE_DATA = infile.read()
  return _IMAGE_DATA
1298606
def pil_image(self):
        """"""
        if not self._pil_image:
            if self._format == "SVG":
                raise VectorImageError("can't rasterise vector images")
            self._pil_image = PIL.Image.open(StringIO(self.contents))
        return self._pil_image
160519
def snapshot(self):
        """"""
        self._snapshot = {
            'name': self.name,
            'volume': self.volume,
            'muted': self.muted,
            'latency': self.latency
        }
        _LOGGER.info('took snapshot of current state of %s', self.friendly_name)
890419
def getImage(self):
        '''
        

        '''
        self.lock.acquire()
        image = self.data
        self.lock.release()
        
        return image
468809
def grab(self, monitor):
        # type: (Monitor) -> ScreenShot
        

        # pylint: disable=too-many-locals

        # Convert PIL bbox style
        if isinstance(monitor, tuple):
            monitor = {
                "left": monitor[0],
                "top": monitor[1],
                "width": monitor[2] - monitor[0],
                "height": monitor[3] - monitor[1],
            }

        core = self.core
        rect = CGRect(
            (monitor["left"], monitor["top"]), (monitor["width"], monitor["height"])
        )

        image_ref = core.CGWindowListCreateImage(rect, 1, 0, 0)
        if not image_ref:
            raise ScreenShotError("CoreGraphics.CGWindowListCreateImage() failed.")

        width = int(core.CGImageGetWidth(image_ref))
        height = int(core.CGImageGetHeight(image_ref))
        prov = copy_data = None
        try:
            prov = core.CGImageGetDataProvider(image_ref)
            copy_data = core.CGDataProviderCopyData(prov)
            data_ref = core.CFDataGetBytePtr(copy_data)
            buf_len = core.CFDataGetLength(copy_data)
            raw = ctypes.cast(data_ref, ctypes.POINTER(ctypes.c_ubyte * buf_len))
            data = bytearray(raw.contents)

            # Remove padding per row
            bytes_per_row = int(core.CGImageGetBytesPerRow(image_ref))
            bytes_per_pixel = int(core.CGImageGetBitsPerPixel(image_ref))
            bytes_per_pixel = (bytes_per_pixel + 7) // 8

            if bytes_per_pixel * width != bytes_per_row:
                cropped = bytearray()
                for row in range(height):
                    start = row * bytes_per_row
                    end = start + width * bytes_per_pixel
                    cropped.extend(data[start:end])
                data = cropped
        finally:
            if prov:
                core.CGDataProviderRelease(prov)
            if copy_data:
                core.CFRelease(copy_data)

        return self.cls_image(data, monitor, size=Size(width, height))
1217511
def pretty_print_device(device):
    """"""
    logging.info('Device Instance ID: %s' % device['id'])
    if 'nickname' in device:
        logging.info('    Nickname: %s' % device['nickname'])
    if 'modelId' in device:
        logging.info('    Model: %s' % device['modelId'])
    logging.info('')
274433
def _take_screenshot(self):
        
        raw_png = self._wda.screenshot()
        img = Image.open(BytesIO(raw_png))
        return img
456142
def screenshot(self, scale=None, quality=None):
        
        output_dir = BuiltIn().get_variable_value('${OUTPUTDIR}')
        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d%H%M%S')
        screenshot_path = '%s%s%s.png' % (output_dir, os.sep, st)
        self.device.screenshot(screenshot_path, scale, quality)
        logger.info('\n<a href="%s">%s</a><br><img src="%s">' % (screenshot_path, st, screenshot_path), html=True)