Creates the thumbnail by using default.engine with multiple output
        sizes.  Appends @<ratio>x to the file name.
490446
def _create_alternative_resolutions(self, source_image, geometry_string,
                                        options, name):
        
        ratio = default.engine.get_image_ratio(source_image, options)
        geometry = parse_geometry(geometry_string, ratio)
        file_name, dot_file_ext = os.path.splitext(name)

        for resolution in settings.THUMBNAIL_ALTERNATIVE_RESOLUTIONS:
            resolution_geometry = (int(geometry[0] * resolution), int(geometry[1] * resolution))
            resolution_options = options.copy()
            if 'crop' in options and isinstance(options['crop'], string_types):
                crop = options['crop'].split(" ")
                for i in range(len(crop)):
                    s = re.match(r"(\d+)px", crop[i])
                    if s:
                        crop[i] = "%spx" % int(int(s.group(1)) * resolution)
                resolution_options['crop'] = " ".join(crop)

            image = default.engine.create(source_image, resolution_geometry, options)
            thumbnail_name = '%(file_name)s%(suffix)s%(file_ext)s' % {
                'file_name': file_name,
                'suffix': '@%sx' % resolution,
                'file_ext': dot_file_ext
            }
            thumbnail = ImageFile(thumbnail_name, default.storage)
            default.engine.write(image, resolution_options, thumbnail)
            size = default.engine.get_image_size(image)
            thumbnail.set_size(size)
196969
private ByteArrayInputStream generateThumbImageByPercent(InputStream inputStream,
                                                             ThumbImage thumbImage) throws IOException {
        LOGGER.debug("根据传入比例生成缩略图");
        // 在内存当中生成缩略图
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        //@formatter:off
        Thumbnails
                .of(inputStream)
                .scale(thumbImage.getPercent())
                .toOutputStream(out);
        //@formatter:on
        return new ByteArrayInputStream(out.toByteArray());
    }
1032547
function MegaPixImage(srcImage, errorCallback) {
        var self = this;

        if (window.Blob && srcImage instanceof Blob) {
            (function() {
                var img = new Image(),
                    URL = window.URL && window.URL.createObjectURL ? window.URL :
                        window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null;
                if (!URL) { throw Error("No createObjectURL function found to create blob url"); }
                img.src = URL.createObjectURL(srcImage);
                self.blob = srcImage;
                srcImage = img;
            }());
        }
        if (!srcImage.naturalWidth && !srcImage.naturalHeight) {
            srcImage.onload = function() {
                var listeners = self.imageLoadListeners;
                if (listeners) {
                    self.imageLoadListeners = null;
                    // IE11 doesn't reliably report actual image dimensions immediately after onload for small files,
                    // so let's push this to the end of the UI thread queue.
                    setTimeout(function() {
                        for (var i = 0, len = listeners.length; i < len; i++) {
                            listeners[i]();
                        }
                    }, 0);
                }
            };
            srcImage.onerror = errorCallback;
            this.imageLoadListeners = [];
        }
        this.srcImage = srcImage;
    }
227116
def create_sprite_image(examples):
    

    def generate_image_from_thubnails(thumbnails, thumbnail_dims):
      """Generates a sprite atlas image from a set of thumbnails."""
      num_thumbnails = tf.shape(thumbnails)[0].eval()
      images_per_row = int(math.ceil(math.sqrt(num_thumbnails)))
      thumb_height = thumbnail_dims[0]
      thumb_width = thumbnail_dims[1]
      master_height = images_per_row * thumb_height
      master_width = images_per_row * thumb_width
      num_channels = 3
      master = np.zeros([master_height, master_width, num_channels])
      for idx, image in enumerate(thumbnails.eval()):
        left_idx = idx % images_per_row
        top_idx = int(math.floor(idx / images_per_row))
        left_start = left_idx * thumb_width
        left_end = left_start + thumb_width
        top_start = top_idx * thumb_height
        top_end = top_start + thumb_height
        master[top_start:top_end, left_start:left_end, :] = image
      return tf.image.encode_png(master)

    image_feature_name = 'image/encoded'
    sprite_thumbnail_dim_px = 32
    with tf.compat.v1.Session():
      keys_to_features = {
          image_feature_name:
              tf.FixedLenFeature((), tf.string, default_value=''),
      }
      parsed = tf.parse_example(examples, keys_to_features)
      images = tf.zeros([1, 1, 1, 1], tf.float32)
      i = tf.constant(0)
      thumbnail_dims = (sprite_thumbnail_dim_px,
                        sprite_thumbnail_dim_px)
      num_examples = tf.constant(len(examples))
      encoded_images = parsed[image_feature_name]

      # Loop over all examples, decoding the image feature value, resizing
      # and appending to a list of all images.
      def loop_body(i, encoded_images, images):
        encoded_image = encoded_images[i]
        image = tf.image.decode_jpeg(encoded_image, channels=3)
        resized_image = tf.image.resize(image, thumbnail_dims)
        expanded_image = tf.expand_dims(resized_image, 0)
        images = tf.cond(
            tf.equal(i, 0), lambda: expanded_image,
            lambda: tf.concat([images, expanded_image], 0))
        return i + 1, encoded_images, images

      loop_out = tf.while_loop(
          lambda i, encoded_images, images: tf.less(i, num_examples),
          loop_body, [i, encoded_images, images],
          shape_invariants=[
              i.get_shape(),
              encoded_images.get_shape(),
              tf.TensorShape(None)
          ])

      # Create the single sprite atlas image from these thumbnails.
      sprite = generate_image_from_thubnails(loop_out[2], thumbnail_dims)
      return sprite.eval()
757863
public function createThumbnail($sFileName, $iThumbSize = null, $blCrop = true)
    {
        $sFilePath = $this->getMediaPath($sFileName);

        if (is_readable($sFilePath)) {
            if (!$iThumbSize) {
                $iThumbSize = $this->_iDefaultThumbnailSize;
            }

            list($iImageWidth, $iImageHeight, $iImageType) = getimagesize($sFilePath);

            switch ($iImageType) {
                case 1:
                    $rImg = imagecreatefromgif($sFilePath);
                    break;

                case 2:
                    $rImg = imagecreatefromjpeg($sFilePath);
                    break;

                case 3:
                    $rImg = imagecreatefrompng($sFilePath);
                    break;

                default:
                    throw new \Exception('Invalid filetype');
                    break;
            }

            $iThumbWidth = $iImageWidth;
            $iThumbHeight = $iImageHeight;

            $iThumbX = 0;
            $iThumbY = 0;

            if ($blCrop) {
                if ($iImageWidth < $iImageHeight) {
                    $iThumbWidth = $iThumbSize;
                    $iThumbHeight = $iImageHeight / ($iImageWidth / $iThumbWidth);

                    $iThumbY = (($iThumbSize - $iThumbHeight) / 2);
                } elseif ($iImageHeight < $iImageWidth) {
                    $iThumbHeight = $iThumbSize;
                    $iThumbWidth = $iImageWidth / ($iImageHeight / $iThumbHeight);

                    $iThumbX = (($iThumbSize - $iThumbWidth) / 2);
                }
            } else {
                if ($iImageWidth < $iImageHeight) {
                    if ($iImageHeight > $iThumbSize) {
                        $iThumbWidth *= ($iThumbSize / $iImageHeight);
                        $iThumbHeight *= ($iThumbSize / $iImageHeight);
                    }
                } elseif ($iImageHeight < $iImageWidth) {
                    if ($iImageHeight > $iThumbSize) {
                        $iThumbWidth *= ($iThumbSize / $iImageWidth);
                        $iThumbHeight *= ($iThumbSize / $iImageWidth);
                    }
                }
            }

            $rTmpImg = imagecreatetruecolor($iThumbWidth, $iThumbHeight);
            imagecopyresampled($rTmpImg, $rImg, $iThumbX, $iThumbY, 0, 0, $iThumbWidth, $iThumbHeight, $iImageWidth, $iImageHeight);

            if ($blCrop) {
                $rThumbImg = imagecreatetruecolor($iThumbSize, $iThumbSize);
                imagefill($rThumbImg, 0, 0, imagecolorallocate($rThumbImg, 0, 0, 0));

                imagecopymerge($rThumbImg, $rTmpImg, 0, 0, 0, 0, $iThumbSize, $iThumbSize, 100);
            } else {
                $rThumbImg = $rTmpImg;
            }

            $sThumbName = $this->getThumbName($sFileName, $iThumbSize);

            imagejpeg($rThumbImg, $this->getThumbnailPath($sThumbName));

            return $sThumbName;
        }

        return false;
    }
445849
def resize(fname, basewidth, opFilename):
    
    if basewidth == 0:
        basewidth = 300
    img = Image.open(fname)
    wpercent = (basewidth/float(img.size[0]))
    hsize = int((float(img.size[1])*float(wpercent)))
    img = img.resize((basewidth,hsize), Image.ANTIALIAS)
    img.save(opFilename)
1374345
def save_thumbnail(self, thumbnail):
        
        filename = thumbnail.name
        try:
            self.thumbnail_storage.delete(filename)
        except Exception:
            pass
        self.thumbnail_storage.save(filename, thumbnail)

        thumb_cache = self.get_thumbnail_cache(
            thumbnail.name, create=True, update=True)

        # Cache thumbnail dimensions.
        if settings.THUMBNAIL_CACHE_DIMENSIONS:
            dimensions_cache, created = (
                models.ThumbnailDimensions.objects.get_or_create(
                    thumbnail=thumb_cache,
                    defaults={'width': thumbnail.width,
                              'height': thumbnail.height}))
            if not created:
                dimensions_cache.width = thumbnail.width
                dimensions_cache.height = thumbnail.height
                dimensions_cache.save()

        signals.thumbnail_created.send(sender=thumbnail)
961782
public function generate()
    {
        $return = '';

        if (empty($this->thumbnailSize)) {
            $this->thumbnailSize = [
                Config::get('imageWidth'),
                Config::get('imageHeight'),
                'box',
            ];
        }

        $file = FilesModel::findByPk($this->varValue);
        if (null === $file && null !== $this->fallbackImage) {
            $file = FilesModel::findByPk($this->fallbackImage);
        }
        if (null !== $file) {
            $altTag = $file->name;
            $size   = deserialize($this->thumbnailSize);
            $image  = Image::create($file->path, $size)->executeResize();

            $return .= sprintf(
                '<img src="%s" width="%s" height="%s" alt="%s" class="uploaded-image">',
                $image->getResizedPath(),
                $image->getTargetWidth(),
                $image->getTargetHeight(),
                $altTag
            );
        }

        if ($this->addMetaWizard) {
//@todo add meta wizard here
        }

        $return .= parent::generate();

        if ($this->enableReset) {
            $return .= sprintf(
                '<input type="checkbox" name="%s" class="checkbox" value=""><label>%s</label> ',
                $this->strName.'_reset',
                'Reset'
            );
        }

        return $return;
    }
936866
public function generateThumbnail(ThumbnailTypeVersion $type)
    {
        $app = Application::getFacadeApplication();
        $config = $app->make('config');
        $image = $this->getImagineImage();
        $imageSize = $image->getSize();
        $bitmapFormat = $app->make(BitmapFormat::class);
        $inplaceOperations = false;
        $inplacePixelsLimit = (float) $config->get('concrete.misc.inplace_image_operations_limit');
        if ($inplacePixelsLimit >= 1) {
            $totalImagePixels = $imageSize->getWidth() * $imageSize->getHeight() * max($image->layers()->count(), 1);
            if ($totalImagePixels > $inplacePixelsLimit) {
                $inplaceOperations = true;
                $this->releaseImagineImage();
            }
        }

        $filesystem = $this->getFile()
            ->getFileStorageLocationObject()
            ->getFileSystemObject();

        $height = $type->getHeight();
        $width = $type->getWidth();
        if ($height && $width) {
            $size = new Box($width, $height);
        } elseif ($width) {
            $size = $imageSize->widen($width);
        } else {
            $size = $imageSize->heighten($height);
        }

        // isCropped only exists on the CustomThumbnail type
        if (method_exists($type, 'isCropped') && $type->isCropped()) {
            $thumbnailMode = ImageInterface::THUMBNAIL_OUTBOUND;
        } else {
            switch ($type->getSizingMode()) {
                case ThumbnailType::RESIZE_EXACT:
                    $thumbnailMode = ImageInterface::THUMBNAIL_OUTBOUND;
                    break;
                case ThumbnailType::RESIZE_PROPORTIONAL:
                default:
                    $thumbnailMode = ImageInterface::THUMBNAIL_INSET;
                    break;
            }
        }
        if ($inplaceOperations) {
            $thumbnailMode |= ImageInterface::THUMBNAIL_FLAG_NOCLONE;
        }
        if ($type->isUpscalingEnabled()) {
            $thumbnailMode |= ImageInterface::THUMBNAIL_FLAG_UPSCALE;
        }

        $thumbnail = $image->thumbnail($size, $thumbnailMode);
        unset($image);
        $thumbnailPath = $type->getFilePath($this);
        if ($type->isKeepAnimations() && $thumbnail->layers()->count() > 1) {
            $isAnimation = true;
            $thumbnailFormat = BitmapFormat::FORMAT_GIF;
        } else {
            $thumbnailFormat = $app->make(ThumbnailFormatService::class)->getFormatForFile($this);
            $isAnimation = false;
        }

        $mimetype = $bitmapFormat->getFormatMimeType($thumbnailFormat);
        $thumbnailOptions = $bitmapFormat->getFormatImagineSaveOptions($thumbnailFormat);
        if ($isAnimation) {
            $thumbnailOptions['animated'] = true;
        }

        $filesystem->write(
            $thumbnailPath,
            $thumbnail->get($thumbnailFormat, $thumbnailOptions),
            [
                'visibility' => AdapterInterface::VISIBILITY_PUBLIC,
                'mimetype' => $mimetype,
            ]
        );
        unset($thumbnail);
        gc_collect_cycles();

        $app['director']->dispatch('on_thumbnail_generate',
            new \Concrete\Core\File\Event\ThumbnailGenerate($thumbnailPath, $type)
        );

        if ($type->getHandle() == $config->get('concrete.icons.file_manager_listing.handle') && !$this->fvHasListingThumbnail) {
            $this->fvHasListingThumbnail = true;
            $this->save();
        }
        if ($type->getHandle() == $config->get('concrete.icons.file_manager_detail.handle') && !$this->fvHasDetailThumbnail) {
            $this->fvHasDetailThumbnail = true;
            $this->save();
        }
    }
857881
def THUMBNAIL_OPTIONS(self):
        
        from django.core.exceptions import ImproperlyConfigured

        size = self._setting('DJNG_THUMBNAIL_SIZE', (200, 200))
        if not (isinstance(size, (list, tuple)) and len(size) == 2 and isinstance(size[0], int) and isinstance(size[1], int)):
            raise ImproperlyConfigured("'DJNG_THUMBNAIL_SIZE' must be a 2-tuple of integers.")
        return {'crop': True, 'size': size}
899726
def generate_thumb(self, image):
        
        image_file = image.file
        picture = Image.open(image_file).convert('RGB')
        picture.thumbnail((10, 10))
        picture.filter(ImageFilter.GaussianBlur(radius=4))
        absolute_path = self.build_thumb_path(image)
        self.save_thumb(picture, absolute_path)
1039323
def generateThumbnail(self):
        """"""
        source = ROOT / self.source.name
        thumbnail = source.parent / '_{}.jpg'.format(source.namebase)

        # -- Save thumbnail and put into queue
        poster = source.parent / '__{}.jpg'.format(source.namebase)
        cmd = [FROG_FFMPEG, '-i', str(source), '-ss', '1', '-vframes', '1', str(thumbnail), '-y']
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        proc.communicate()
        image = pilImage.open(thumbnail)
        image.save(poster)
        self.poster = poster.replace(ROOT, '')

        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 = thumbnail.replace(ROOT, '')
        image.save(thumbnail)
1042942
public ContentPackageBuilder thumbnailImage(InputStream is) throws IOException {
    metadata.setThumbnailImage(IOUtils.toByteArray(is));
    return this;
  }
1109946
public function create($mixed, $savePath, $width, $height, $fit = false, $format = false)
    {
        if ($format === false) {
            $format = $this->getThumbnailsFormat();
        }
        switch ($format) {
            case ThumbnailFormatService::FORMAT_AUTO:
                $format = $this->app->make(ThumbnailFormatService::class)->getAutomaticFormatForFile($savePath);
                break;
        }
        $thumbnailOptions = [
            'jpeg_quality' => $this->getJpegCompression(),
            'png_compression_level' => $this->getPngCompression(),
        ];
        $filesystem = $this->getStorageLocation()->getFileSystemObject();

        if ($mixed instanceof ImageInterface) {
            $image = $mixed;
        } else {
            $image = Image::open($mixed);
        }
        if ($fit) {
            $thumb = $image->thumbnail(new Box($width, $height), ImageInterface::THUMBNAIL_OUTBOUND);
            $filesystem->write(
                $savePath,
                $thumb->get($format, $thumbnailOptions)
            );
        } else {
            if ($height < 1) {
                $thumb = $image->thumbnail($image->getSize()->widen($width));
            } elseif ($width < 1) {
                $thumb = $image->thumbnail($image->getSize()->heighten($height));
            } else {
                $thumb = $image->thumbnail(new Box($width, $height));
            }
            $filesystem->write(
                $savePath,
                $thumb->get($format, $thumbnailOptions)
            );
        }
    }
579240
protected function createThumbnail()
    {
		$this->thumbnail = $this->thumbnailName();

    	if (! $this->validFile($this->thumbnailPath())) {
    		$img = $this->intervention
				->make($this->imagePath())
				->resize($this->width(), $this->height(), function ($constraint) {
            		$constraint->aspectRatio();
            		$constraint->upsize();
        		});

        	$img->save($this->thumbnailPath());
    	}
    }
990699
def resize_image(self, data, size):
        
        from machina.core.compat import PILImage as Image
        image = Image.open(BytesIO(data))

        # Resize!
        image.thumbnail(size, Image.ANTIALIAS)

        string = BytesIO()
        image.save(string, format='PNG')
        return string.getvalue()
1285189
def expand_gallery(generator, metadata):
    
    if "gallery" not in metadata or metadata['gallery'] is None:
        return  # If no gallery specified, we do nothing

    lines = [ ]
    base_path = _image_path(generator)
    in_path = path.join(base_path, metadata['gallery'])
    template = generator.settings.get('GALLERY_TEMPLATE', DEFAULT_TEMPLATE)
    thumbnail_name = generator.settings.get("GALLERY_THUMBNAIL", DEFAULT_GALLERY_THUMB)
    thumbnail_prefix = generator.settings.get("")
    resizer = _resizer(thumbnail_name, '?x?', base_path)
    for dirpath, _, filenames in os.walk(in_path):
        for filename in filenames:
            if not filename.startswith('.'):
                url = path.join(dirpath, filename).replace(base_path, "")[1:]
                url = path.join('/static', generator.settings.get('IMAGE_PATH', DEFAULT_IMAGE_DIR), url).replace('\\', '/')
                logger.debug("GALLERY: {0}".format(url))
                thumbnail = resizer.get_thumbnail_name(filename)
                thumbnail = path.join('/', generator.settings.get('THUMBNAIL_DIR', DEFAULT_THUMBNAIL_DIR), thumbnail).replace('\\', '/')
                lines.append(template.format(
                    filename=filename,
                    url=url,
                    thumbnail=thumbnail,
                ))
    metadata['gallery_content'] = "\n".join(lines)