Pass in a search term (e.g. 'dogs') and the resolution you
  want the image to be displayed at.
541212
def sexy_image(term, opts = {:width => 100, :height => 100})

      # The loving is a mess, what happened to all of the feeling?
      # I thought it was for real; babies, rings and fools kneeling
      # And words of pledging trust and lifetimes stretching forever
      # So what went wrong? It was a lie, it crumbled apart
      # Ghost figures of past, present, future haunting the heart
      sexy_image = term.is_a?(SexItUp::SexItUpImage) ? term : SexItUpImage.where(['image_search_term = ?', term]).random

      if sexy_image.nil? || sexy_image.blank?
        puts "No image found.  Searching for #{term}."
        # No image object passed in or found; let's go search.

        sexy_image = SexItUpImage.find_all(term).random
      end

      unless sexy_image.nil?
        style           = "#{opts[:width]}x#{opts[:height]}"
        style_sym       = "s_#{style}".to_sym
        style_hash      = {style_sym => [style]}

        sexy_image.set_attachment_sizes(style_hash)
        sexy_image.image.reprocess! unless File.exist?(sexy_image.image.path(style_sym)) # No need for reprocessing if size already exists

        tag = "<img"
        tag += " class=\"#{opts[:class]}\"" if opts[:class]
        tag += " src=\"#{sexy_image.image.url(style_sym)}\""
        tag += " alt=\"#{opts[:alt]}\"" if opts[:alt]
        tag += " title=\"#{opts[:title]}\"" if opts[:title]
        tag += " />"

        return tag.html_safe
      end

      nil
    end
1252427
def format_image(self, image, image_format, **kwargs):
        """"""

        if image_format in ('png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'):
            if image_format != 'webp' and FORCE_WEBP:
                # Always return WebP when supported by the browser
                accept = self.request.META['HTTP_ACCEPT'].split(',')
                if 'image/webp' in accept:
                    image = image.convert('RGBA')
                    image_format = 'webp'
                    kwargs = {'lossless': True}

            if image_format == 'png':
                kwargs['optimize'] = True
            elif image_format == 'jpg':
                image.convert('RGB')
                kwargs['progressive'] = True

            buffer = six.BytesIO()
            image.save(buffer, image_format, **kwargs)
            return buffer.getvalue(), "image/{}".format(image_format)
        else:
            raise ValueError('Unsupported format: {}'.format(image_format))
562177
def image_me(self, message, search_query):
        """"""

        if (
                getattr(settings, "GOOGLE_API_KEY", False)
                and getattr(settings, "GOOGLE_CUSTOM_SEARCH_ENGINE_ID", False)
        ):
            self.say(
                "Sorry, I'm missing my GOOGLE_API_KEY and GOOGLE_CUSTOM_SEARCH_ENGINE_ID."
                " Can someone give them to me?", color="red"
            )
            # https://developers.google.com/custom-search/json-api/v1/reference/cse/list?hl=en
            data = {
                "q": search_query,
                "key": settings.GOOGLE_API_KEY,
                "cx": settings.GOOGLE_CUSTOM_SEARCH_ENGINE_ID,
                "safe": "medium",
                "num": 8,
                "searchType": "image",
            }
            r = requests.get("https://www.googleapis.com/customsearch/v1", params=data)
            r.raise_for_status()
            try:
                response = r.json()
                results = [result["link"] for result in response["items"] if "items" in r.json()]
            except TypeError:
                results = []
        else:
            # Fall back to a really ugly hack.
            logging.warn(
                "Hey, I'm using a pretty ugly hack to get those images, and it might break. "
                "Please set my GOOGLE_API_KEY and GOOGLE_CUSTOM_SEARCH_ENGINE_ID when you have a chance."
            )
            r = requests.get("https://www.google.com/search?tbm=isch&safe=active&q=%s" % search_query)
            results = []
            content = r.content.decode("utf-8")
            index = content.find("<img")
            while index != -1:
                src_start = content.find('src=', index)
                src_end = content.find(" ", src_start)
                match = content[src_start+5: src_end-1]

                index = content.find("<img", src_end)
                results.append(match)
        if results:
            url = random.choice(results)
            self.say("%s" % url, message=message)
        else:
            self.say("Couldn't find anything!", message=message)
372711
public function canvasImageScale()
    {
        $imageOriginalWidth = imagesx($this->oImg);
        $imageOriginalHeight = imagesy($this->oImg);
        $scale = min($imageOriginalWidth / $this->options ['width'], $imageOriginalHeight / $this->options ['height']);

        $this->options ['cropWidth'] = ceil($this->options ['width'] * $scale);
        $this->options ['cropHeight'] = ceil($this->options ['height'] * $scale);

        $this->options ['minScale'] = min($this->options ['maxScale'], max(1 / $scale, $this->options ['minScale']));

        if ($this->options ['prescale'] !== false)
        {
            $this->preScale = 1 / $scale / $this->options ['minScale'];
            if ($this->preScale < 1)
            {
                $this->canvasImageResample(ceil($imageOriginalWidth * $this->preScale), ceil($imageOriginalHeight * $this->preScale));
                $this->options ['cropWidth'] = ceil($this->options ['cropWidth'] * $this->preScale);
                $this->options ['cropHeight'] = ceil($this->options ['cropHeight'] * $this->preScale);
            }
            else
            {
                $this->preScale = 1;
            }
        }

        return $this;
    }
374839
def pad_image(arr, max_size=400):
    """"""
    dim = np.max(arr.shape)
    img = np.zeros((dim, dim, 3), dtype=arr.dtype)
    xl = (dim - arr.shape[0]) // 2
    yl = (dim - arr.shape[1]) // 2
    img[xl:arr.shape[0]+xl, yl:arr.shape[1]+yl, :] = arr
    return resample_image(img, max_size=max_size)
452109
def _filter_image(self, url):
        ""
        return reduce(lambda f, g: f and g(f), 
        [
            filters.AdblockURLFilter()(url),
            filters.NoImageFilter(),
            filters.SizeImageFilter(),
            filters.MonoImageFilter(),
            filters.FormatImageFilter(),
        ])
952146
def nside2resol(nside, arcmin=False):
    """"""
    resolution = nside_to_pixel_resolution(nside)
    if arcmin:
        return resolution.to(u.arcmin).value
    else:
        return resolution.to(u.rad).value
1060951
def get_image_tags(context, instance, options):
    
    if hasattr(instance, 'image') and hasattr(instance.image, 'exif'):
        aspect_ratio = compute_aspect_ratio(instance.image)
    elif 'image' in instance.glossary and 'width' in instance.glossary['image']: 
        aspect_ratio = compute_aspect_ratio_with_glossary(instance.glossary)
        instance.glossary['ramdom_svg_color'] = 'hsl({}, 30%, 80%, 0.8)'.format( str(random.randint(0, 360)))
    else:
        # if accessing the image file fails or fake image fails, abort here
        logger.warning("Unable to compute aspect ratio of image '{}'".format(instance.image))
        return

    is_responsive = options.get('is_responsive', False)
    resize_options = options.get('resize_options', {})
    crop = 'crop' in resize_options
    upscale = 'upscale' in resize_options
    if hasattr(instance.image, 'subject_location'):
        subject_location = instance.image.subject_location and 'subject_location' in resize_options
    else:
        subject_location = None
    resolutions = (False, True) if 'high_resolution' in resize_options else (False,)
    tags = {'sizes': [], 'srcsets': {}, 'is_responsive': is_responsive, 'extra_styles': {}}
    if is_responsive:
        image_width = parse_responsive_length(options.get('image_width_responsive') or '100%')
        assert(image_width[1]), "The given image has no valid width"
        if image_width[1] != 1.0:
            tags['extra_styles'].update({'max-width': '{:.0f}%'.format(100 * image_width[1])})
    else:
        image_width = parse_responsive_length(options['image_width_fixed'])
        if not image_width[0]:
            image_width = (instance.image.width, image_width[1])
    try:
        image_height = parse_responsive_length(options['image_height'])
    except KeyError:
        image_height = (None, None)
    set_defaults(options)
    if is_responsive:
        max_width = 0
        for bp in options['breakpoints']:
            if bp not in options['container_max_widths']:
                continue
            width = int(image_width[1] * options['container_max_widths'][bp])
            max_width = max(max_width, width)
            size = get_image_size(width, image_height, aspect_ratio)
            if bp in options['media_queries']:
                tags['sizes'].append('{0} {1}px'.format(' and '.join(options['media_queries'][bp]), width))
            for high_res in resolutions:
                if high_res:
                    size = (size[0] * 2, size[1] * 2)
                key = '{0}w'.format(size[0])
                tags['srcsets'][key] = {'size': size, 'crop': crop, 'upscale': upscale,
                                        'subject_location': subject_location}
        # use an existing image as fallback for the <img ...> element
        if not max_width > 0:
            logger.warning('image tags: image max width is zero')
        size = (int(round(max_width)), int(round(max_width * aspect_ratio)))
    else:
        size = get_image_size(image_width[0], image_height, aspect_ratio)
        if len(resolutions) > 1:
            for high_res in resolutions:
                if high_res:
                    tags['srcsets']['2x'] = {'size': (size[0] * 2, size[1] * 2), 'crop': crop,
                        'upscale': upscale, 'subject_location': subject_location}
                else:
                    tags['srcsets']['1x'] = {'size': size, 'crop': crop,
                        'upscale': upscale, 'subject_location': subject_location}
    tags['src'] = {'size': size, 'crop': crop, 'upscale': upscale,
                   'subject_location': subject_location}
    return tags
1315055
def build_filename(filename, filetype='png', resolution=300):
    
    filevals = os.path.splitext(filename)
    if filevals[1]:
        filetype = filevals[1][1:]
    if not filetype:
        filetype = 'png'
    filename = filevals[0] + '.' + filetype

    if not resolution:
        resolution = 300
    return filename, filetype, resolution
92091
def _search_url(search_term:str, size:str='>400*300', format:str='jpg') -> str:
    ""
    return ('https://www.google.com/search?q=' + quote(search_term) +
            '&espv=2&biw=1366&bih=667&site=webhp&source=lnms&tbm=isch' +
            _url_params(size, format) + '&sa=X&ei=XosDVaCXD8TasATItgE&ved=0CAcQ_AUoAg')
466425
def _get_data_to_display(self, eopatch):
        
        feature_type, feature_name = next(self.feature(eopatch))

        image_seq = eopatch[feature_type][feature_name]
        single_channel = False
        if image_seq.ndim == 3:
            # single channel
            single_channel = True
        elif image_seq.ndim == 4:
            # If multi-channel make sure indexing is correct
            n_channels = image_seq.shape[-1]
            if n_channels == 1:
                image_seq = np.squeeze(image_seq, axis=-1)
                single_channel = True
            elif n_channels == 3:
                pass
            else:
                if (self.indices is not None) and ((len(self.indices) == 1) or (len(self.indices) == 3)):
                    image_seq = image_seq[..., self.indices]
                    if len(self.indices) == 1:
                        image_seq = np.squeeze(image_seq, axis=-1)
                        single_channel = True
                else:
                    raise ValueError("Specify valid indices for multi-channel EOPatch")
        else:
            raise ValueError("Unsupported format for EOPatch")
        return image_seq, single_channel
894737
function () {
            // Sets properties of '_features' that change on resize and/or orientation.
            var w   = win.innerWidth || _viewport.clientWidth,
                h   = win.innerHeight || _viewport.clientHeight,
                dw  = win.screen.width,
                dh  = win.screen.height,
                c   = win.screen.colorDepth,
                x   = win.devicePixelRatio;

            _features.width                     = w;
            _features.height                    = h;
            _features['aspect-ratio']           = (w / h).toFixed(2);
            _features['device-width']           = dw;
            _features['device-height']          = dh;
            _features['device-aspect-ratio']    = (dw / dh).toFixed(2);
            _features.color                     = c;
            _features['color-index']            = Math.pow(2, c);
            _features.orientation               = (h >= w ? 'portrait' : 'landscape');
            _features.resolution                = (x && x * 96) || win.screen.deviceXDPI || 96;
            _features['device-pixel-ratio']     = x || 1;
        }
508135
def find_image(self, image, configuration):
        """"""
        images = configuration["images"]
        available = list(images.keys())

        if not image:
            info = {}
            if available:
                info["available"] = available
            raise BadOption("Please use --image to specify an image", **info)

        if image not in images:
            raise BadOption("No such image", wanted=image, available=available)
526444
function(file) {
        var type =  '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|';
        return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
      }
167212
function(req, res) {
        if (!searchIdx) return res();
        var results = searchIdx.search(req.term)
          .map(function(result) {
            return {
              label: files[result.ref].title,
              value: files[result.ref]
            };
          });

        res(results);
      }
1182945
function resize(img, width=0, height=0, type='png', quality=0.75) {
    let mime
    switch(type.toLowerCase()) {
    case 'jpg':
    case 'jpeg':
    case 'image/jpeg':
        mime = 'image/jpeg'
        break
    case 'png':
    case 'image/png':
    default:
        mime = 'image/png'
    }
    return resizePromise(img, width, height).then(
        canvas => canvas2Blob(canvas, { type: mime, quality })
        //canvas => canvas2DataUrl(canvas, { type: mime, quality })
    )
}
934718
def parse_image_spec(spec):
    

    # I was having trouble coming up with a single RE that did it right,
    # so let's just break it down into sub-problems. First, parse out the
    # alt text...
    match = re.match(r'(.+)\s+\"(.*)\"\s*$', spec)
    if match:
        spec, title = match.group(1, 2)
    else:
        title = None

    # and now parse out the arglist
    match = re.match(r'([^\{]*)(\{(.*)\})\s*$', spec)
    if match:
        spec = match.group(1)
        args = parse_arglist(match.group(3))
    else:
        args = {}

    return spec, args, (title and html.unescape(title))