Generates a square thumbnail
13526
def generateThumbnail(self):
        """"""
        image = pilImage.open(ROOT / self.source.name)
        box, width, height = cropBox(self.width, self.height)

        # Resize
        image.thumbnail((width, height), pilImage.ANTIALIAS)
        # Crop from center
        box = cropBox(*image.size)[0]
        image = image.crop(box)
        # save
        self.thumbnail = self.source.name.replace(self.hash, '__{}'.format(self.hash))
        image.save(ROOT / self.thumbnail.name)
997121
function(fileId, imgOrCanvas, maxSize, fromServer, customResizeFunction) {
            var promiseToReturn = new qq.Promise(),
                fileOrUrl, options;

            if (this._imageGenerator) {
                fileOrUrl = this._thumbnailUrls[fileId];
                options = {
                    customResizeFunction: customResizeFunction,
                    maxSize: maxSize > 0 ? maxSize : null,
                    scale: maxSize > 0
                };

                // If client-side preview generation is possible
                // and we are not specifically looking for the image URl returned by the server...
                if (!fromServer && qq.supportedFeatures.imagePreviews) {
                    fileOrUrl = this.getFile(fileId);
                }

                /* jshint eqeqeq:false,eqnull:true */
                if (fileOrUrl == null) {
                    promiseToReturn.failure({container: imgOrCanvas, error: "File or URL not found."});
                }
                else {
                    this._imageGenerator.generate(fileOrUrl, imgOrCanvas, options).then(
                        function success(modifiedContainer) {
                            promiseToReturn.success(modifiedContainer);
                        },

                        function failure(container, reason) {
                            promiseToReturn.failure({container: container, error: reason || "Problem generating thumbnail"});
                        }
                    );
                }
            }
            else {
                promiseToReturn.failure({container: imgOrCanvas, error: "Missing image generator module"});
            }

            return promiseToReturn;
        }
272181
def bbox(ctx, tile):
    """"""
    geom = TilePyramid(
        ctx.obj['grid'],
        tile_size=ctx.obj['tile_size'],
        metatiling=ctx.obj['metatiling']
    ).tile(*tile).bbox(pixelbuffer=ctx.obj['pixelbuffer'])
    if ctx.obj['output_format'] in ['WKT', 'Tile']:
        click.echo(geom)
    elif ctx.obj['output_format'] == 'GeoJSON':
        click.echo(geojson.dumps(geom))
474555
def __create_image(self, inpt, hashfun):
        """"""
        if hashfun not in generator.HASHES.keys():
            print ("Unknown or unsupported hash function. Using default: %s"
                   % self.DEFAULT_HASHFUN)
            algo = self.DEFAULT_HASHFUN
        else:
            algo = hashfun
        return generator.generate(inpt, algo)
512416
function createPictures(id, farm, server, secret) {

		var NO_LIMIT = 2048;
		var sizes = [
			{id: 't', max: 100},
			{id: 'm', max: 240},
			{id: 'n', max: 320},
			{id: '', max: 500},
			{id: 'z', max: 640},
			{id: 'c', max: 800},
			{id: 'b', max: 1024},
			{id: 'h', max: 1600},
			{id: 'k', max: 2048},
			{id: 'o', max: NO_LIMIT}
		];

		return sizes.map(function(size) {
			return {
				source: createPhotoUrl(id, farm, server, secret, size.id),

				// Note: this is a guess that's almost certain to be wrong (unless square source)
				width: size.max,
				height: size.max
			};
		});
	}
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)
564504
def thumb(self, obj):
        
        format, created = Format.objects.get_or_create(name='newman_thumb',
                                                       defaults={
            'max_width': 100,
            'max_height': 100,
            'flexible_height': False,
            'stretch': False,
            'nocrop': True,
        })

        if created:
            format.sites = Site.objects.all()

        info = obj.get_formated_photo(format)

        return '<a href="%(href)s"><img src="%(src)s"></a>' % {
            'href': '%s/' % obj.pk,
            'src': info['url']
        }
676373
def _thumbnail_resize(self, image, thumb_size, crop=None, bg=None):
        """"""

        if crop == 'fit':
            img = ImageOps.fit(image, thumb_size, Image.ANTIALIAS)
        else:
            img = image.copy()
            img.thumbnail(thumb_size, Image.ANTIALIAS)

        if bg:
            img = self._bg_square(img, bg)

        return img
1324385
def set_current_thumbnail(self, thumbnail):
        """"""
        self.current_thumbnail = thumbnail
        self.figure_viewer.load_figure(
                thumbnail.canvas.fig, thumbnail.canvas.fmt)
        for thumbnail in self._thumbnails:
            thumbnail.highlight_canvas(thumbnail == self.current_thumbnail)
739652
def write(self, image, options, thumbnail):
        
        if options['format'] == 'JPEG' and options.get(
                'progressive', settings.THUMBNAIL_PROGRESSIVE):
            image['options']['interlace'] = 'line'

        image['options']['quality'] = options['quality']

        args = settings.THUMBNAIL_CONVERT.split(' ')
        args.append(image['source'] + '[0]')

        for k in image['options']:
            v = image['options'][k]
            args.append('-%s' % k)
            if v is not None:
                args.append('%s' % v)

        flatten = "on"
        if 'flatten' in options:
            flatten = options['flatten']

        if settings.THUMBNAIL_FLATTEN and not flatten == "off":
            args.append('-flatten')

        suffix = '.%s' % EXTENSIONS[options['format']]

        with NamedTemporaryFile(suffix=suffix, mode='rb') as fp:
            args.append(fp.name)
            args = map(smart_str, args)
            p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            returncode = p.wait()
            out, err = p.communicate()

            if returncode:
                raise EngineError(
                    "The command %r exited with a non-zero exit code and printed this to stderr: %s"
                    % (args, err)
                )
            elif err:
                logger.error("Captured stderr: %s", err)

            thumbnail.write(fp.read())
294497
def generate_by_hash(hashcode):
    """"""
    img = Image.new(IMAGE_MODE, IMAGE_SIZE, BACKGROUND_COLOR)
    if len(hashcode) < 32:
        print ("hashcode must have lenght >= 32, %s" % hashcode)
        raise FalseHashError

    allowed = "0123456789abcdef"
    hashcheck = [c in allowed for c in hashcode]
    if False in hashcheck:
        print ("hashcode has not allowed structure %s" % hashcode)
        raise FalseHashError

    pixelmap = setup_pixelmap(hashcode)
    draw_image(pixelmap, img)
    return img
1236240
def image_placeholder(width: Union[int, str] = 1920,
                          height: Union[int, str] = 1080) -> str:
        
        url = 'http://placehold.it/{width}x{height}'
        return url.format(width=width, height=height)
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;
        }
    }
1019870
def qr2scad(stream):
    """"""

    img = Image.open(stream)

    # Convert to black and white 8-bit
    if img.mode != 'L':
        img = img.convert('L')

    # Invert color to get the right bounding box
    img = ImageOps.invert(img)

    bbox = img.getbbox()

    # Crop to only contain contents within the PDPs
    img = img.crop(bbox)

    width, height = img.size

    assert width == height,\
        'The QR code should be a square, but we found it to be %(w)sx%(h)s' % {
            'w': width,
            'h': height
        }

    qr_side = width

    # QR code superpixel size
    qr_pixel_size = (list(img.getdata()).index(0) / PDP_SIDE)

    # Get the resize factor from the PDP size
    new_size = qr_side / qr_pixel_size

    # Set a more reasonable size
    img = img.resize((new_size, new_size))
    qr_side = new_size

    img_matrix = img.load()

    result = 'module _qr_code_dot() {\n'
    result += '    cube([%(block_side)s, %(block_side)s, 1]);\n' % {
        'block_side': BLOCK_SIDE
    }
    result += '}\n'

    result += 'module qr_code() {\n'
    for row in range(qr_side):
        for column in range(qr_side):
            if img_matrix[column, row] != 0:
                result += '    translate([%(x)s, %(y)s, 0])' % {
                    'x': BLOCK_SIZE * column - qr_side / 2,
                    'y': -BLOCK_SIZE * row + qr_side / 2
                }
                result += ' _qr_code_dot();\n'
    result += '}\n'
    result += 'qr_code_size = %d;' % (qr_side)

    return result
641205
def _tile_image(self, data):
        
        image = Image.open(BytesIO(data))
        return image.convert('RGBA')
729223
def _create_thumbnail(self, model_instance, thumbnail, image_name):
        
        thumbnail = self._do_resize(thumbnail, self.thumbnail_size)
        full_image_name = self.generate_filename(model_instance, image_name)
        thumbnail_filename = _get_thumbnail_filename(full_image_name)
        thumb = self._get_simple_uploaded_file(thumbnail, thumbnail_filename)
        self.storage.save(thumbnail_filename, thumb)
1085576
def set_thumbnail(self, thumbnail):
        ''''''
        self._thumbnail = thumbnail
        return self._listitem.setThumbnailImage(thumbnail)