Return a PNG image for a document page number. If zoom is other than 0, one of
        the 4 page quadrants are zoomed-in instead and the corresponding clip returned.
517045
def _get_page_data(self, pno, zoom=0):
        
        dlist = self.dlist_tab[pno]  # get display list
        if not dlist:  # create if not yet there
            self.dlist_tab[pno] = self.doc[pno].getDisplayList()
            dlist = self.dlist_tab[pno]
        r = dlist.rect  # page rectangle
        mp = r.tl + (r.br - r.tl) * 0.5  # rect middle point
        mt = r.tl + (r.tr - r.tl) * 0.5  # middle of top edge
        ml = r.tl + (r.bl - r.tl) * 0.5  # middle of left edge
        mr = r.tr + (r.br - r.tr) * 0.5  # middle of right egde
        mb = r.bl + (r.br - r.bl) * 0.5  # middle of bottom edge
        mat = fitz.Matrix(2, 2)  # zoom matrix
        if zoom == 1:  # top-left quadrant
            clip = fitz.Rect(r.tl, mp)
        elif zoom == 4:  # bot-right quadrant
            clip = fitz.Rect(mp, r.br)
        elif zoom == 2:  # top-right
            clip = fitz.Rect(mt, mr)
        elif zoom == 3:  # bot-left
            clip = fitz.Rect(ml, mb)
        if zoom == 0:  # total page
            pix = dlist.getPixmap(alpha=False)
        else:
            pix = dlist.getPixmap(alpha=False, matrix=mat, clip=clip)
        return pix.getPNGData()
298086
def get_large_image(self, page=1):
        
        url = self.get_large_image_url(page=page)
        return self._get_url(url)
917459
def thumbnail(self):
        
        if not self.status:
            return None

        images = self.status.images

        return images[0].url if images else None
695763
def thumbnail(self):
        
        if 'THUMBNAIL_RESOURCE' in self.image_resources:
            return pil_io.convert_thumbnail_to_pil(
                self.image_resources.get_data('THUMBNAIL_RESOURCE')
            )
        elif 'THUMBNAIL_RESOURCE_PS4' in self.image_resources:
            return pil_io.convert_thumbnail_to_pil(
                self.image_resources.get_data('THUMBNAIL_RESOURCE_PS4'), 'BGR'
            )
        return None
418003
def _text_image(page):
    
    img = None
    alt = page.data.get('label') or page.data.get('title')
    source = _image(page)
    if source:
        img = "![%s](%s)" % (alt, source)
    return img
1358378
def get_image(self, size, latitude_interval, longitude_interval, max_elevation, min_elevation=0,
                  unknown_color = (255, 255, 255, 255), zero_color = (0, 0, 255, 255),
                  min_color = (0, 0, 0, 255), max_color = (0, 255, 0, 255),
                  mode='image'):
        

        if not size or len(size) != 2:
            raise Exception('Invalid size %s' % size)
        if not latitude_interval or len(latitude_interval) != 2:
            raise Exception('Invalid latitude interval %s' % latitude_interval)
        if not longitude_interval or len(longitude_interval) != 2:
            raise Exception('Invalid longitude interval %s' % longitude_interval)

        width, height = size
        width, height = int(width), int(height)

        latitude_from,  latitude_to  = latitude_interval
        longitude_from, longitude_to = longitude_interval


        if mode == 'array':
            import numpy as np
            array = np.empty((height,width))
            for row in range(height):
                for column in range(width):
                    latitude  = latitude_from  + float(row) / height * (latitude_to  - latitude_from)
                    longitude = longitude_from + float(column) / width * (longitude_to - longitude_from)
                    elevation = self.get_elevation(latitude, longitude)
                    array[row,column] = elevation

            return array

        elif mode == 'image':
            try:    import Image as mod_image
            except: from PIL import Image as mod_image
            try:    import ImageDraw as mod_imagedraw
            except: from PIL import ImageDraw as mod_imagedraw

            image = mod_image.new('RGBA', (width, height),
                              (255, 255, 255, 255))
            draw = mod_imagedraw.Draw(image)

            max_elevation -= min_elevation

            for row in range(height):
                for column in range(width):
                    latitude  = latitude_from  + float(row) / height * (latitude_to  - latitude_from)
                    longitude = longitude_from + float(column) / width * (longitude_to - longitude_from)
                    elevation = self.get_elevation(latitude, longitude)
                    if elevation == None:
                        color = unknown_color
                    else:
                        elevation_coef = (elevation - min_elevation) / float(max_elevation)
                        if elevation_coef < 0: elevation_coef = 0
                        if elevation_coef > 1: elevation_coef = 1
                        color = mod_utils.get_color_between(min_color, max_color, elevation_coef)
                        if elevation <= 0:
                            color = zero_color
                    draw.point((column, height - row), color)

            return image
        else:
            raise Exception('Invalid mode ' + mode)
51408
def get_bounding_box_list_render_image(pdf_file_name, input_doc):
    """"""

    program_to_use = "pdftoppm" # default to pdftoppm
    if args.gsRender: program_to_use = "Ghostscript"

    # Threshold value set in range 0-255, where 0 is black, with 191 default.
    if not args.threshold: args.threshold = 191
    threshold = args.threshold
    if not args.numSmooths: args.numSmooths = 0
    if not args.numBlurs: args.numBlurs = 0

    temp_dir = ex.program_temp_directory # use the program default; don't delete dir!

    temp_image_file_root = os.path.join(temp_dir, ex.temp_file_prefix + "PageImage")
    if args.verbose:
        print("\nRendering the PDF to images using the " + program_to_use + " program,"
              "\nthis may take a while...")

    # Do the rendering of all the files.
    render_pdf_file_to_image_files(pdf_file_name, temp_image_file_root, program_to_use)

    # Currently assuming that sorting the output will always put them in correct order.
    outfiles = sorted(glob.glob(temp_image_file_root + "*"))

    if args.verbose:
        print("\nAnalyzing the page images with PIL to find bounding boxes,"
              "\nusing the threshold " + str(args.threshold) + "."
              "  Finding the bounding box for page:\n")

    bounding_box_list = []

    for page_num, tmp_image_file_name in enumerate(outfiles):
        curr_page = input_doc.getPage(page_num)

        # Open the image in PIL.  Retry a few times on fail in case race conditions.
        max_num_tries = 3
        time_between_tries = 1
        curr_num_tries = 0
        while True:
            try:
                # PIL for some reason fails in Python 3.4 if you open the image
                # from a file you opened yourself.  Works in Python 2 and earlier
                # Python 3.  So original code is commented out, and path passed.
                #
                # tmpImageFile = open(tmpImageFileName)
                # im = Image.open(tmpImageFile)
                im = Image.open(tmp_image_file_name)
                break
            except (IOError, UnicodeDecodeError) as e:
                curr_num_tries += 1
                if args.verbose:
                    print("Warning: Exception opening image", tmp_image_file_name,
                          "on try", curr_num_tries, "\nError is", e, file=sys.stderr)
                # tmpImageFile.close() # see above comment
                if curr_num_tries > max_num_tries: raise # re-raise exception
                time.sleep(time_between_tries)

        # Apply any blur or smooth operations specified by the user.
        for i in range(args.numBlurs):
            im = im.filter(ImageFilter.BLUR)
        for i in range(args.numSmooths):
            im = im.filter(ImageFilter.SMOOTH_MORE)

        # Convert the image to black and white, according to a threshold.
        # Make a negative image, because that works with the PIL getbbox routine.

        if args.verbose:
            print(page_num+1, end=" ") # page num numbering from 1
        # Note that the point method calls the function on each pixel, replacing it.
        #im = im.point(lambda p: p > threshold and 255) # create a positive image
        #im = im.point(lambda p: p < threshold and 255)  # create a negative image
        # Below code is easier to understand than tricky use of "and" in evaluation.
        im = im.point(lambda p: 255 if p < threshold else 0)  # create a negative image

        if args.showImages:
            im.show() # usually for debugging or param-setting

        # Calculate the bounding box of the negative image, and append to list.
        bounding_box = calculate_bounding_box_from_image(im, curr_page)
        bounding_box_list.append(bounding_box)

        # Clean up the image files after they are no longer needed.
        # tmpImageFile.close() # see above comment
        os.remove(tmp_image_file_name)

    if args.verbose:
        print()
    return bounding_box_list
1206178
def _getPageObjNumber(self, pno):
        """"""
        if self.isClosed:
            raise ValueError("operation illegal for closed doc")

        return _fitz.Document__getPageObjNumber(self, pno)
754757
def take_screenshot(self):
    """"""

    if not self.failed:
        return

    browser = getattr(world, 'browser', None)
    if not browser:
        return

    try:
        scenario_name = self.scenario.name
        scenario_index = \
            self.scenario.feature.scenarios.index(self.scenario) + 1
    except AttributeError:
        scenario_name = self.background.keyword
        scenario_index = 0

    if self.outline is None:
        outline_index_str = ''
    else:
        outline_index = self.scenario.outlines.index(self.outline) + 1
        outline_index_str = '_{}'.format(outline_index)

    base_name = FORMAT.format(
        feature_file=os.path.relpath(self.feature.filename),
        scenario_index=scenario_index,
        scenario_name=scenario_name,
        outline_index=outline_index_str,
    )
    base_name = re.sub(r'\W', '_', base_name, flags=re.UNICODE)
    base_name = os.path.join(DIRECTORY, base_name)

    world.browser.save_screenshot('{}.png'.format(base_name))

    with open('{}.html'.format(base_name), 'w') as page_source_file:
        page_source_file.write(world.browser.page_source)
770076
def file_to_png(fp):
	
	import PIL.Image # pylint: disable=import-error
	with io.BytesIO() as dest:
		PIL.Image.open(fp).save(dest, "PNG", optimize=True)
		return dest.getvalue()
1121700
static function thumbnail($pic, $dst_pic, $max_width, $max_height = null, $qulitity = 100, $copy = true)
    {
        $im = self::readfile($pic);
        if ($im === false)
        {
            return false;
        }

        $old_w = imagesx($im);
        $old_h = imagesy($im);

        if ($max_height == null)
        {
            $max_height = $max_width;
        }

        if ($old_w > $max_width or $old_h > $max_height)
        {

            $w_h = $old_w / $old_h;
            $h_w = $old_h / $old_w;
            if ($w_h > $h_w)
            {
                $width = $max_width;
                $height = $width * $h_w;
            }
            else
            {
                $height = $max_height;
                $width = $height * $w_h;
            }
            $newim = imagecreatetruecolor($width, $height);
            imagecopyresampled($newim, $im, 0, 0, 0, 0, $width, $height, $old_w, $old_h);
            imagejpeg($newim, $dst_pic, $qulitity);
            imagedestroy($im);
            return true;
        }
        elseif ($pic != $dst_pic and $copy)
        {
            return copy($pic, $dst_pic);
        }
        else
        {
            return false;
        }
    }
289202
def thumbnail_image(realfile, filename, size=(200, 75), suffix=True, quality=None):
    
    from PIL import Image

    im = Image.open(realfile)
    file, ext = os.path.splitext(realfile)
    if im.size[0]<=size[0] and im.size[1]<=size[1]:
        #the image size is smaller than thumbnail size, so we don't need to 
        #thumbnail the image
        return filename, filename
    im.thumbnail(size, Image.ANTIALIAS)
    format = ext[1:].upper()
    if format == 'JPG':
        format = 'JPEG'
    if suffix:
        ofile = file + ".thumbnail" + ext
    else:
        ofile = realfile
    im.save(ofile, format, quality=quality or QUALITY)
    file1, ext1 = os.path.splitext(filename)
    if suffix:
        ofile1 = file1 + ".thumbnail" + ext
    else:
        ofile1 = filename
    return ofile, ofile1
1313263
def getPageImageList(self, pno):
        
        if self.isClosed or self.isEncrypted:
            raise ValueError("operation illegal for closed / encrypted doc")
        if self.isPDF:
            return self._getPageInfo(pno, 2)
        return []
713561
def process_png(data)
      type   = 'png'
      width  = 0
      height = 0
      x_dpi  = 96
      y_dpi  = 96

      offset = 8
      data_length = data.size

      # Search through the image data to read the height and width in th the
      # IHDR element. Also read the DPI in the pHYs element.
      while offset < data_length

        length = data[offset + 0, 4].unpack("N")[0]
        png_type   = data[offset + 4, 4].unpack("A4")[0]

        case png_type
        when "IHDR"
          width  = data[offset +  8, 4].unpack("N")[0]
          height = data[offset + 12, 4].unpack("N")[0]
        when "pHYs"
          x_ppu = data[offset +  8, 4].unpack("N")[0]
          y_ppu = data[offset + 12, 4].unpack("N")[0]
          units = data[offset + 16, 1].unpack("C")[0]

          if units == 1
            x_dpi = x_ppu * 0.0254
            y_dpi = y_ppu * 0.0254
          end
        end

        offset = offset + length + 12

        break if png_type == "IEND"
      end
      raise "#{filename}: no size data found in png image.\n" unless height

      [type, width, height, x_dpi, y_dpi]
    end
131660
def image(self, name, x=None, y=None, w=0,h=0,type='',link=''):
        ""
        if not name in self.images:
            #First use of image, get info
            if(type==''):
                pos=name.rfind('.')
                if(not pos):
                    self.error('image file has no extension and no type was specified: '+name)
                type=substr(name,pos+1)
            type=type.lower()
            if(type=='jpg' or type=='jpeg'):
                info=self._parsejpg(name)
            elif(type=='png'):
                info=self._parsepng(name)
            else:
                #Allow for additional formats
                #maybe the image is not showing the correct extension,
                #but the header is OK,
                succeed_parsing = False
                #try all the parsing functions
                parsing_functions = [self._parsejpg,self._parsepng,self._parsegif]
                for pf in parsing_functions:
                    try:
                        info = pf(name)
                        succeed_parsing = True
                        break;
                    except:
                        pass
                #last resource
                if not succeed_parsing:
                    mtd='_parse'+type
                    if not hasattr(self,mtd):
                        self.error('Unsupported image type: '+type)
                    info=getattr(self, mtd)(name)
                mtd='_parse'+type
                if not hasattr(self,mtd):
                    self.error('Unsupported image type: '+type)
                info=getattr(self, mtd)(name)
            info['i']=len(self.images)+1
            self.images[name]=info
        else:
            info=self.images[name]
        #Automatic width and height calculation if needed
        if(w==0 and h==0):
            #Put image at 72 dpi
            w=info['w']/self.k
            h=info['h']/self.k
        elif(w==0):
            w=h*info['w']/info['h']
        elif(h==0):
            h=w*info['h']/info['w']
        # Flowing mode
        if y is None:
            if (self.y + h > self.page_break_trigger and not self.in_footer and self.accept_page_break()):
                #Automatic page break
                x = self.x
                self.add_page(self.cur_orientation)
                self.x = x
            y = self.y
            self.y += h
        if x is None:
            x = self.x
        self._out(sprintf('q %.2f 0 0 %.2f %.2f %.2f cm /I%d Do Q',w*self.k,h*self.k,x*self.k,(self.h-(y+h))*self.k,info['i']))
        if(link):
            self.link(x,y,w,h,link)
663181
def _insertImage(self, filename=None, pixmap=None, stream=None, overlay=1, matrix=None, _imgname=None, _imgpointer=None):
        """"""
        return _fitz.Page__insertImage(self, filename, pixmap, stream, overlay, matrix, _imgname, _imgpointer)
262283
function (pageNum) {
            var index = util.clamp(pageNum - 1, 0, this.numPages - 1),
                page = this.state.pages[index];
            return { top: page.y0, left: page.x0 };
        }