Add a image to a screenshot object
182330
def add_image(self, im):
        
        for im_tmp in self.images:
            if im_tmp.kind == im.kind:
                self.images.remove(im_tmp)
                break
        self.images.append(im)
1227681
public static Bitmap createScreenshot(Context context) {
        if (!hasScreenshotPermission(context)) {
            LogUtils.log(ScreenshotUtils.class, Log.ERROR, "Screenshot permission denied.");
            return null;
        }

        final WindowManager windowManager =
                (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

        final Bitmap bitmap = SurfaceControlCompatUtils.screenshot(0, 0);

        // Bail if we couldn't take the screenshot.
        if (bitmap == null) {
            LogUtils.log(ScreenshotUtils.class, Log.ERROR, "Failed to take screenshot.");
            return null;
        }

        final int width = bitmap.getWidth();
        final int height = bitmap.getHeight();
        final int rotation = windowManager.getDefaultDisplay().getRotation();

        final int outWidth;
        final int outHeight;
        final float rotationDegrees;

        switch (rotation) {
            case Surface.ROTATION_90:
                outWidth = height;
                outHeight = width;
                rotationDegrees = 90;
                break;
            case Surface.ROTATION_180:
                outWidth = width;
                outHeight = height;
                rotationDegrees = 180;
                break;
            case Surface.ROTATION_270:
                outWidth = height;
                outHeight = width;
                rotationDegrees = 270;
                break;
            default:
                return bitmap;
        }

        // Rotate the screenshot to match the screen orientation.
        final Bitmap rotatedBitmap =
                Bitmap.createBitmap(outWidth, outHeight, Bitmap.Config.RGB_565);
        final Canvas c = new Canvas(rotatedBitmap);

        c.translate(outWidth / 2.0f, outHeight / 2.0f);
        c.rotate(-rotationDegrees);
        c.translate(-width / 2.0f, -height / 2.0f);
        c.drawBitmap(bitmap, 0, 0, null);

        bitmap.recycle();

        return rotatedBitmap;
    }
560715
function(){
			var image = document.createElement("img");
			image.id = this._prefix+this._id;
			image.src = Commands.NO_IMAGE;
			image.className = "progressPane_running";
			this._anchor.appendChild(image);
		}
1315830
def add_pic(self, post_data):
        '''
        
        '''
        img_entity = self.request.files['file'][0]
        filename = img_entity["filename"]

        if filename and allowed_file(filename):
            pass
        else:
            return False

        _, hou = os.path.splitext(filename)
        signature = str(uuid.uuid1())
        outfilename = '{0}{1}'.format(signature, hou)
        outpath = 'static/upload/{0}'.format(signature[:2])
        if os.path.exists(outpath):
            pass
        else:
            os.makedirs(outpath)
        with open(os.path.join(outpath, outfilename), "wb") as fileout:
            fileout.write(img_entity["body"])
        path_save = os.path.join(signature[:2], outfilename)
        sig_save = os.path.join(signature[:2], signature)

        imgpath = os.path.join(outpath, signature + '_m.jpg')
        imgpath_sm = os.path.join(outpath, signature + '_sm.jpg')

        ptr_image = Image.open(os.path.join('static/upload', path_save))
        tmpl_size = (768, 768)
        thub_size = (256, 256)
        (imgwidth, imgheight) = ptr_image.size
        if imgwidth < tmpl_size[0] and imgheight < tmpl_size[1]:
            tmpl_size = (imgwidth, imgheight)
        ptr_image.thumbnail(tmpl_size)

        im0 = ptr_image.convert('RGB')
        im0.save(imgpath, 'JPEG')

        im0.thumbnail(thub_size)
        im0.save(imgpath_sm, 'JPEG')

        create_pic = MEntity.create_entity(signature,
                                           path_save,
                                           post_data['desc'] if 'desc' in post_data else '',
                                           kind=post_data['kind'] if 'kind' in post_data else '1')
        if self.entity_ajax == False:
            self.redirect('/entity/{0}_m.jpg'.format(sig_save))
        else:
            if create_pic:
                output = {'path_save': imgpath}
            else:
                output = {'path_save': ''}
            return json.dump(output, self)
499331
public void takeScreenshot(String filename) throws IOException {
		File screenshot = ((TakesScreenshot) driver)
				.getScreenshotAs(OutputType.FILE);
		FileUtils.copyFile(screenshot, new File(filename));
	}
1100089
def save_as_png(self, filename, width=300, height=250, render_time=1):
        """"""
        self.driver.set_window_size(width, height)
        self.driver.get('file://{path}/{filename}'.format(
            path=os.getcwd(), filename=filename + ".html"))
        time.sleep(render_time)
        self.driver.save_screenshot(filename + ".png")
274433
def _take_screenshot(self):
        
        raw_png = self._wda.screenshot()
        img = Image.open(BytesIO(raw_png))
        return img
135679
def create_screenshot(self, app_id, filename, position=1):
        
        # prepare file for upload
        with open(filename, 'rb') as s_file:
            s_content = s_file.read()
        s_encoded = b64encode(s_content)
        url = self.url('create_screenshot') % app_id

        mtype, encoding = mimetypes.guess_type(filename)
        if mtype is None:
            mtype = 'image/jpeg'

        data = {'position': position,
                'file': {'type': mtype,
                         'data': s_encoded}}
        return self.conn.fetch('POST', url, data)
813645
def __capture_screenshot(webdriver, folder_location, file_name):
        ""
        # Check folder location exists.
        if not os.path.exists(folder_location):
            os.makedirs(folder_location)

        file_location = os.path.join(folder_location, file_name)

        if isinstance(webdriver, remote.webdriver.WebDriver):
            # If this is a remote webdriver.  We need to transmit the image data
            # back across system boundries as a base 64 encoded string so it can
            # be decoded back on the local system and written to disk.
            base64_data = webdriver.get_screenshot_as_base64()
            screenshot_data = base64.decodestring(base64_data)
            screenshot_file = open(file_location, "wb")
            screenshot_file.write(screenshot_data)
            screenshot_file.close()
        else:
            webdriver.save_screenshot(file_location)
1053112
def screenshot(self, filename=None):
        '''
        
        '''
        image = self.d.screenshot()
        if self.rotation:
            method = getattr(Image, 'ROTATE_{}'.format(self.rotation*90))
            image = image.transpose(method)
        if filename:
            image.save(filename)
        return image
408267
def add_image(self, figure, dpi=72):
        '''
        
        '''
        name = os.path.join(self._dir, '/fig%s.png' % self.fig_counter)
        self.fig_counter += 1
        figure.savefig(name, dpi=dpi)
        plt.close(figure)
        self.body += '<img src="%s" />\n' % name
707221
function() {
        var that = this;

        // Save a screenshot.
        if ($$logging.get('screenshots').enabled) {
            var filename = $$logging.get('screenshots').filename.replace('{date}', moment().format('YYYYMMDDhhmmss'));
            logger.info('Saving screenshot to ' + filename);

            var winCmd = path.join(__dirname, '../tools', 'nircmd.exe');
            var winArgs = ['savescreenshotfull', filename];

            var macCmd = '/usr/sbin/screencapture';
            var macArgs = ['-x', '-t', 'jpg', '-C', filename];

            var cmd = process.platform === 'win32' ? winCmd : macCmd;
            var args = process.platform === 'win32' ? winArgs : macArgs;

            var screenshot = child_process.spawn(cmd, args);
            screenshot.on('close', function(code, signal) {
                logger.info('Screenshot saved, restarting.');
                restart();
            });
        } else {
            restart();
        }

        function restart() {
            var restartCount = that.get('restartCount');
            restartCount++;

            var logList = 'App went away: ' + restartCount + ' times\n\n';
            _.each($$logging.get('logCache'), function(log) {
                logList += log.time + ' ' + log.level + ': ' + log.msg + '\n';
            });
            logger.error(logList);

            that.trigger('crash');

            if (restartCount >= that.get('restartMachineAfter')) {
                logger.info('Already restarted app ' + that.get('restartMachineAfter') + ' times, rebooting machine.');
                that.restartMachine();
                return;
            }

            that.set('restartCount', restartCount);
            that._isStartingUp = false;
            that._isShuttingDown = false;
            that.restartApp();
        }
    }
1338544
def saveLastScreenImage(self):
        
        bitmap = self.getLastScreenImage()
        _, target_file = tempfile.mkstemp(".png")
        cv2.imwrite(target_file, bitmap)
21125
def update_screen(image)
      if @show_prompt
        MiniTerm.print("\r#{prompt.text}\r")
        @show_prompt = false
      end

      (0...active_width).each do |index|
        if (image_char = image[index]) != window_buffer[index]
          MiniTerm.set_posn(column: prompt.length + index)
          MiniTerm.print(image_char)
        end
      end
    end
171750
private void silentlySaveScreenshotTo(final File file) {
		try {
			saveScreenshotTo(file);
			LOG.info("Screenshot saved: " + file.getAbsolutePath());
		} catch (Exception e) {
			LOG.warn("Error while taking screenshot " + file.getName() + ": "
					+ e);
		}
	}
1064703
def screenshot_raw(self, includes='subtitles'):
        """"""
        from PIL import Image
        res = self.node_command('screenshot-raw', includes)
        if res['format'] != 'bgr0':
            raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
                    .format(res['format']))
        img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
        b,g,r,a = img.split()
        return Image.merge('RGB', (r,g,b))
1133993
def create_screenshot(name, data, path, font, is_module):
    
    desktop_color = get_color_for_name(name)

    # if this screenshot is for a module then add modules name etc
    if is_module:
        data.append(
            {"full_text": name.split("-")[0], "color": desktop_color, "separator": True}
        )
        data.append(
            {"full_text": "py3status", "color": COLOR_PY3STATUS, "separator": True}
        )

    img = Image.new("RGB", (WIDTH, HEIGHT), COLOR_BG)
    d = ImageDraw.Draw(img)

    # top bar
    d.rectangle((0, 0, WIDTH, TOP_BAR_HEIGHT), fill=desktop_color)
    x = X_OFFSET

    # add text and separators
    for part in reversed(data):
        text = part.get("full_text")
        color = part.get("color", COLOR)
        background = part.get("background")
        separator = part.get("separator")
        urgent = part.get("urgent")

        # urgent background
        if urgent:
            color = COLOR_URGENT
            background = COLOR_URGENT_BG

        size = font.getsize(text)

        if background:
            d.rectangle(
                (
                    WIDTH - x - (size[0] // SCALE),
                    TOP_BAR_HEIGHT + PADDING,
                    WIDTH - x - 1,
                    HEIGHT - PADDING,
                ),
                fill=background,
            )

        x += size[0] // SCALE

        txt = Image.new("RGB", size, background or COLOR_BG)
        d_text = ImageDraw.Draw(txt)
        d_text.text((0, 0), text, font=font, fill=color)
        # resize to actual size wanted and add to image
        txt = txt.resize((size[0] // SCALE, size[1] // SCALE), Image.ANTIALIAS)
        img.paste(txt, (WIDTH - x, TOP_BAR_HEIGHT + PADDING))

        if separator:
            x += SEP_PADDING_RIGHT
            d.line(
                (
                    (WIDTH - x, TOP_BAR_HEIGHT + PADDING),
                    (WIDTH - x, TOP_BAR_HEIGHT + 1 + PADDING + FONT_SIZE),
                ),
                fill=COLOR_SEP,
                width=1,
            )
            x += SEP_PADDING_LEFT

    img.save(os.path.join(path, "%s.png" % name))
    print(" %s.png" % name)