Extracts an image of a video and returns its path.

        If the requested thumbnail is not within the duration of the video
        an `InvalidTimeError` is thrown.
162053
def get_thumbnail(self, video_path, at_time=0.5):
        
        filename = os.path.basename(video_path)
        filename, __ = os.path.splitext(filename)
        _, image_path = tempfile.mkstemp(suffix='_{}.jpg'.format(filename))

        video_duration = self.get_media_info(video_path)['duration']
        if at_time > video_duration:
            raise exceptions.InvalidTimeError()
        thumbnail_time = at_time

        cmds = [self.ffmpeg_path, '-i', video_path, '-vframes', '1']
        cmds.extend(['-ss', str(thumbnail_time), '-y', image_path])

        process = self._spawn(cmds)
        self._check_returncode(process)

        if not os.path.getsize(image_path):
            # we somehow failed to generate thumbnail
            os.unlink(image_path)
            raise exceptions.InvalidTimeError()

        return image_path
142129
def _read_metadata(self):
        
        if self._is_metadata_init():
            return
        try:
            log.debug('Reading metadata of "{path}" ...'.format(path=self._filepath))
            data = metadata.parse(self._filepath)
            videotracks = data.get_videotracks()
            if len(videotracks) > 0:
                self._fps = videotracks[0].get_framerate()
                self._time_ms = videotracks[0].get_duration_ms()
                self._framecount = videotracks[0].get_framecount()
        except:
            # FIXME: find out what type the metadata parser can throw
            log.debug('... FAIL')
            log.exception('Exception was thrown.')
1332561
def parse_path(path):
        
        import pymediainfo

        metadata = Metadata()
        log.debug('pymediainfo: parsing "{path}" ...'.format(path=path))
        parseRes = pymediainfo.MediaInfo.parse(str(path))
        log.debug('... parsing FINISHED')
        for track in parseRes.tracks:
            log.debug('... found track type: "{track_type}"'.format(track_type=track.track_type))
            if track.track_type == 'Video':
                duration_ms = track.duration
                framerate = track.frame_rate
                framecount = track.frame_count
                log.debug('mode={mode}'.format(mode=track.frame_rate_mode))
                if duration_ms is None or framerate is None:
                    log.debug('... Video track does not have duration and/or framerate.')
                    continue
                log.debug('... duration = {duration_ms} ms, framerate = {framerate} fps'.format(duration_ms=duration_ms,
                                                                                               framerate=framerate))
                metadata.add_metadata(
                    MetadataVideoTrack(
                        duration_ms=duration_ms,
                        framerate=float(framerate),
                        framecount=framecount
                    )
                )
        return metadata
185676
function ( item ) {  // function to obtain the URL of the thumbnail image
				var href;

				if (item.element) {
					href = $(item.element).find('img').attr('src');
				}

				if (!href && item.type === 'image' && item.href) {
					href = item.href;
				}

				return href;
			}
48732
def content_type(path)
      path = path.downcase
      return 'image/jpeg' if path.end_with?('.jpg')
      return 'image/jpeg' if path.end_with?('.jpeg')
      return 'image/png' if path.end_with?('.png')
      return 'application/json' if path.end_with?('.geojson')
      return 'video/quicktime' if path.end_with?('.mov')
      return 'video/mp4' if path.end_with?('.m4v')
      return 'video/mp4' if path.end_with?('.mp4')
      raise "Unknown content-type for file #{path}"
    end
886417
def image_url(path, only_path=False, cache_buster=True, dst_color=None, src_color=None, spacing=None, collapse_x=None, collapse_y=None):
    
    return _image_url(path, only_path, cache_buster, dst_color, src_color, False, None, spacing, collapse_x, collapse_y)
120112
def get_thumbnail_image(self, page=1):
        
        url = self.get_thumbnail_image_url(page=page)
        return self._get_url(url)
1079124
def __get_img(self):
        
        with self.fs.open(self.__img_path, 'rb') as fd:
            img = PIL.Image.open(fd)
            img.load()
            return img
1105946
def thumbnail_preview(src_path):
  '''  '''
  try:
    assert(exists(src_path))

    width = '1980'

    dest_dir = mkdtemp(prefix='pyglass')
    cmd = [QLMANAGE, '-t', '-s', width, src_path, '-o', dest_dir]
    assert(check_call(cmd) == 0)

    src_filename = basename(src_path)
    dest_list = glob(join(dest_dir, '%s.png' % (src_filename)))
    assert(dest_list)

    dest_path = dest_list[0]
    assert(exists(dest_path))

    return dest_path
  except:
    return None
265448
def _get_thumbnail_filename(self, source, geometry_string, options):
        
        key = tokey(source.key, geometry_string, serialize(options))
        # make some subdirs
        path = '%s/%s/%s' % (key[:2], key[2:4], key)
        return '%s%s.%s' % (settings.THUMBNAIL_PREFIX, path, EXTENSIONS[options['format']])
719107
def fetch_image(self,rtsp_server_uri = _source,timeout_secs = 15):
        
        
        self._check_ffmpeg()
        cmd = "ffmpeg -rtsp_transport tcp -i {} -loglevel quiet -frames 1 -f image2pipe -".format(rtsp_server_uri)

        #stdout = _sp.check_output(ffmpeg_cmd,timeout = timeout_secs)
        with _sp.Popen(cmd, shell=True,  stdout=_sp.PIPE) as process:
            try:
                stdout,stderr = process.communicate(timeout=timeout_secs)
            except _sp.TimeoutExpired as e:
                process.kill()
                raise TimeoutError("Connection to {} timed out".format(rtsp_server_uri),e)
        
        return _Image.open(_io.BytesIO(stdout))
897067
def renderThumbnail(self, relpath=""):
        
        # return from cache if available
        cachekey, html = self.checkCache('Thumbnail', relpath)
        if html is not None:
            return html
        # else regenerate
        rec = self.imgrec[0]
        html = self._renderSingleImage(rec.fullimage, rec.thumbnail, relpath)
        # save to cache
        return self.writeCache(cachekey, html)
1196385
public static Bitmap getThumbnail(Context context, Uri uri, String mimeType) {
        if (DEBUG)
            Log.d(TAG, "Attempting to get thumbnail");

        if (!isMediaUri(uri)) {
            Log.e(TAG, "You can only retrieve thumbnails for images and videos.");
            return null;
        }

        Bitmap bm = null;
        if (uri != null) {
            final ContentResolver resolver = context.getContentResolver();
            Cursor cursor = null;
            try {
                cursor = resolver.query(uri, null, null, null, null);
                if (cursor.moveToFirst()) {
                    final int id = cursor.getInt(0);
                    if (DEBUG)
                        Log.d(TAG, "Got thumb ID: " + id);

                    if (mimeType.contains("video")) {
                        bm = MediaStore.Video.Thumbnails.getThumbnail(
                                resolver,
                                id,
                                MediaStore.Video.Thumbnails.MINI_KIND,
                                null);
                    }
                    else if (mimeType.contains(FileUtils.MIME_TYPE_IMAGE)) {
                        bm = MediaStore.Images.Thumbnails.getThumbnail(
                                resolver,
                                id,
                                MediaStore.Images.Thumbnails.MINI_KIND,
                                null);
                    }
                }
            } catch (Exception e) {
                if (DEBUG)
                    Log.e(TAG, "getThumbnail", e);
            } finally {
                if (cursor != null)
                    cursor.close();
            }
        }
        return bm;
    }
128394
def get_video_json(video):
    

    return json.dumps({
        'id': video.id,
        'edit_link': reverse('wagtailvideos:edit', args=(video.id,)),
        'title': video.title,
        'preview': {
            'url': video.thumbnail.url if video.thumbnail else '',
        }
    })
228997
def generate_image_from_url(url=None, timeout=30):
    

    file_name = posixpath.basename(url)
    img_tmp = NamedTemporaryFile(delete=True)

    try:
        response = requests.get(url, timeout=timeout)
        response.raise_for_status()
    except Exception as e:  # NOQA
        return None, None

    img_tmp.write(response.content)
    img_tmp.flush()

    image = File(img_tmp)
    image.seek(0)

    return file_name, image
551200
async def get_image(
        self,
        input_source: str,
        output_format: str = IMAGE_JPEG,
        extra_cmd: Optional[str] = None,
        timeout: int = 15,
    ) -> Optional[bytes]:
        """"""
        command = ["-an", "-frames:v", "1", "-c:v", output_format]

        # open input for capture 1 frame
        is_open = await self.open(
            cmd=command,
            input_source=input_source,
            output="-f image2pipe -",
            extra_cmd=extra_cmd,
        )

        # error after open?
        if not is_open:
            _LOGGER.warning("Error starting FFmpeg.")
            return None

        # read image
        try:
            proc_func = functools.partial(self._proc.communicate, timeout=timeout)
            image, _ = await self._loop.run_in_executor(None, proc_func)
            return image

        except (subprocess.TimeoutExpired, ValueError):
            _LOGGER.warning("Timeout reading image.")
            self.kill()
            return None
659881
def thumbnail(self, id):
        
        res = self._raw_api_request('thumb', data={'i': id})
        if not res:
            raise PuushError("Getting thumbnail failed.")
        return res