Generate a thumbnail for a given image file.

    :param file file: The source image file to thumbnail
    :param int size: The thumbnail size in pixels (Thumbnails are squares)
    :param tuple bbox: An optionnal Bounding box definition for the thumbnail
11541
def make_thumbnail(file, size, bbox=None):
    '''
    
    '''
    image = Image.open(file)
    if bbox:
        thumbnail = crop_thumbnail(image, size, bbox)
    else:
        thumbnail = center_thumbnail(image, size)
    return _img_to_file(thumbnail)
268474
public static Bitmap getThumbnail(Context context, File file) {
        return getThumbnail(context, getUri(context, file), getMimeType(file));
    }
1337969
def _pack_image(filename, max_size, form_field='image', f=None):
        """"""
        # image must be less than 700kb in size
        if f is None:
            try:
                if os.path.getsize(filename) > (max_size * 1024):
                    raise TweepError('File is too big, must be less than %skb.' % max_size)
            except os.error as e:
                raise TweepError('Unable to access file: %s' % e.strerror)

            # build the mulitpart-formdata body
            fp = open(filename, 'rb')
        else:
            f.seek(0, 2)  # Seek to end of file
            if f.tell() > (max_size * 1024):
                raise TweepError('File is too big, must be less than %skb.' % max_size)
            f.seek(0)  # Reset to beginning of file
            fp = f

        # image must be gif, jpeg, or png
        file_type = mimetypes.guess_type(filename)
        if file_type is None:
            raise TweepError('Could not determine file type')
        file_type = file_type[0]
        if file_type not in ['image/gif', 'image/jpeg', 'image/png']:
            raise TweepError('Invalid file type for image: %s' % file_type)

        if isinstance(filename, six.text_type):
            filename = filename.encode('utf-8')

        BOUNDARY = b'Tw3ePy'
        body = []
        body.append(b'--' + BOUNDARY)
        body.append('Content-Disposition: form-data; name="{0}";'
                    ' filename="{1}"'.format(form_field, filename)
                    .encode('utf-8'))
        body.append('Content-Type: {0}'.format(file_type).encode('utf-8'))
        body.append(b'')
        body.append(fp.read())
        body.append(b'--' + BOUNDARY + b'--')
        body.append(b'')
        fp.close()
        body = b'\r\n'.join(body)

        # build headers
        headers = {
            'Content-Type': 'multipart/form-data; boundary=Tw3ePy',
            'Content-Length': str(len(body))
        }

        return headers, body
1159488
def call(file, *args, format: nil)
      img = ::MiniMagick::Image.new(file.path)
      img.quiet
      img.format(format.to_s.downcase, nil) if format
      send(@method, img, *args)
      post_processing(img)

      ::File.open(img.path, "rb")
    end
827030
def create_thumbnail(img, width, height):
    
    size = (width, height)
    img.thumbnail(size)
    return img
63442
def add_file(self, filename, block_size=4096):
        
        with open(filename, "rb") as f:
            for chunk in iter(lambda: f.read(block_size), b""):
                self.hash.update(chunk)
1129788
def set(self, image_file, source=None):
        
        image_file.set_size()  # make sure its got a size
        self._set(image_file.key, image_file)
        if source is not None:
            if not self.get(source):
                # make sure the source is in kvstore
                raise ThumbnailError('Cannot add thumbnails for source: `%s` '
                                     'that is not in kvstore.' % source.name)

            # Update the list of thumbnails for source.
            thumbnails = self._get(source.key, identity='thumbnails') or []
            thumbnails = set(thumbnails)
            thumbnails.add(image_file.key)

            self._set(source.key, list(thumbnails), identity='thumbnails')
292060
def generate_file_rst(fname, target_dir, src_dir, plot_gallery):
    
    base_image_name = os.path.splitext(fname)[0]
    image_fname = '%s_%%s.png' % base_image_name
    root_image_fname = 'root_%s_%%s.png' % base_image_name
    root_fig_num = 1

    this_template = rst_template
    last_dir = os.path.split(src_dir)[-1]
    # to avoid leading . in file names, and wrong names in links
    if last_dir == '.' or last_dir == 'examples':
        last_dir = ''
    else:
        last_dir += '_'
    short_fname = last_dir + fname
    src_file = os.path.join(src_dir, fname)
    example_file = os.path.join(target_dir, fname)
    shutil.copyfile(src_file, example_file)

    # The following is a list containing all the figure names
    figure_list = []

    image_dir = os.path.join(target_dir, 'images')
    thumb_dir = os.path.join(image_dir, 'thumb')
    if not os.path.exists(image_dir):
        os.makedirs(image_dir)
    if not os.path.exists(thumb_dir):
        os.makedirs(thumb_dir)
    image_path = os.path.join(image_dir, image_fname)
    root_image_path = os.path.join(image_dir, root_image_fname)

    stdout_path = os.path.join(image_dir,
                               'stdout_%s.txt' % base_image_name)
    time_path = os.path.join(image_dir,
                               'time_%s.txt' % base_image_name)
    thumb_file = os.path.join(thumb_dir, fname[:-3] + '.png')
    time_elapsed = 0
    if plot_gallery and fname.startswith('plot'):
        # generate the plot as png image if file name
        # starts with plot and if it is more recent than an
        # existing image.
        first_image_file = image_path % 1
        first_root_image_file = root_image_path % 1
        if os.path.exists(stdout_path):
            stdout = open(stdout_path).read()
        else:
            stdout = ''
        if os.path.exists(time_path):
            time_elapsed = float(open(time_path).read())

        if (not os.path.exists(first_image_file) or
            not os.path.exists(first_root_image_file) or
                os.stat(first_image_file).st_mtime <=
                                    os.stat(src_file).st_mtime):
            # We need to execute the code
            print('plotting %s' % fname)
            t0 = time()
            import matplotlib.pyplot as plt
            plt.close('all')
            cwd = os.getcwd()
            try:
                # First CD in the original example dir, so that any file
                # created by the example get created in this directory
                orig_stdout = sys.stdout
                os.chdir(os.path.dirname(src_file))
                my_buffer = StringIO()
                my_stdout = Tee(sys.stdout, my_buffer)
                sys.stdout = my_stdout
                my_globals = {'pl': plt}
                execfile(os.path.basename(src_file), my_globals)
                time_elapsed = time() - t0
                sys.stdout = orig_stdout
                my_stdout = my_buffer.getvalue()
                if '__doc__' in my_globals:
                    # The __doc__ is often printed in the example, we
                    # don't with to echo it
                    my_stdout = my_stdout.replace(
                                            my_globals['__doc__'],
                                            '')
                my_stdout = my_stdout.strip()
                if my_stdout:
                    stdout = '**Script output**::\n\n  %s\n\n' % (
                        '\n  '.join(my_stdout.split('\n')))
                open(stdout_path, 'w').write(stdout)
                open(time_path, 'w').write('%f' % time_elapsed)
                os.chdir(cwd)

                # In order to save every figure we have two solutions :
                # * iterate from 1 to infinity and call plt.fignum_exists(n)
                #   (this requires the figures to be numbered
                #    incrementally: 1, 2, 3 and not 1, 2, 5)
                # * iterate over [fig_mngr.num for fig_mngr in
                #   matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]
                for fig_num in (fig_mngr.num for fig_mngr in
                        matplotlib._pylab_helpers.Gcf.get_all_fig_managers()):
                    # Set the fig_num figure as the current figure as we can't
                    # save a figure that's not the current figure.
                    plt.figure(fig_num)
                    plt.savefig(image_path % fig_num)
                    figure_list.append(image_fname % fig_num)
                for canvas in ROOT.gROOT.GetListOfCanvases():
                    maybe_root_filename = os.path.join(os.path.dirname(src_file), canvas.name)
                    if os.path.isfile(maybe_root_filename):
                        os.rename(maybe_root_filename, os.path.join(image_dir, canvas.name))
                        figure_list.append(canvas.name)
                        canvas.Close()
                    else:
                        canvas.SaveAs(root_image_path % root_fig_num)
                        canvas.Close()
                        figure_list.append(root_image_fname % root_fig_num)
                        root_fig_num += 1
            except:
                print(80 * '_')
                print('%s is not compiling:' % fname)
                traceback.print_exc()
                print(80 * '_')
            finally:
                os.chdir(cwd)
                sys.stdout = orig_stdout

            print(" - time elapsed : %.2g sec" % time_elapsed)
        else:
            figure_list = [f[len(image_dir):]
                            for f in glob.glob(image_path % '[1-9]')]
                            #for f in glob.glob(image_path % '*')]

        # generate thumb file
        this_template = plot_rst_template
        from matplotlib import image
        if os.path.exists(first_image_file):
            image.thumbnail(first_image_file, thumb_file, 0.2)
        elif os.path.exists(first_root_image_file):
            image.thumbnail(first_root_image_file, thumb_file, 0.2)

    if not os.path.exists(thumb_file):
        # create something not to replace the thumbnail
        shutil.copy('images/blank_image.png', thumb_file)

    docstring, short_desc, end_row = extract_docstring(example_file)

    # Depending on whether we have one or more figures, we're using a
    # horizontal list or a single rst call to 'image'.
    if len(figure_list) == 1:
        figure_name = figure_list[0]
        image_list = SINGLE_IMAGE % figure_name.lstrip('/')
    else:
        image_list = HLIST_HEADER
        for figure_name in figure_list:
            image_list += HLIST_IMAGE_TEMPLATE % figure_name.lstrip('/')

    f = open(os.path.join(target_dir, fname[:-2] + 'rst'), 'w')
    f.write(this_template % locals())
    f.flush()
1047738
def _get_or_add_image(self, image_file):
        
        image_part, rId = self.part.get_or_add_image_part(image_file)
        desc, image_size = image_part.desc, image_part._px_size
        return rId, desc, image_size
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()
672251
def thumbnail!
      begin
        image = MiniMagick::Image.open(@file.path)
        image.resize("#{Pushfile.settings[:images][:thumb][:width]}x")
      rescue
        @thumb = nil
      else
        t = @name.split('.'); ext = t.pop
        @thumb = t.join(".").concat("_thumb.#{ext}")
        image.write("/tmp/#{@thumb}") rescue @thumb = nil
      end
    end
146588
def get_thumbnail(self, original, size, crop, options):
        
        try:
            image = self.create(original, size, crop, options)
        except ThumbnailError:
            image = None
        finally:
            self.cleanup(original)
        return image
744098
public function generateThumbnails(File $file, $thumbnailLinks = false)
    {
        $links = [];
        if (!$file->getIsImage()) {
            return $links;
        }
        $generator = $this->getThumbnailGenerator();

        // Small thumbnail
        $smallWidth = UploadField::config()->uninherited('thumbnail_width');
        $smallHeight = UploadField::config()->uninherited('thumbnail_height');

        // Large thumbnail
        $width = $this->config()->get('thumbnail_width');
        $height = $this->config()->get('thumbnail_height');

        // Generate links if client requests them
        // Note: Thumbnails should always be generated even if links are not
        if ($thumbnailLinks) {
            $links['smallThumbnail'] = $generator->generateThumbnailLink($file, $smallWidth, $smallHeight);
            $links['thumbnail'] = $generator->generateThumbnailLink($file, $width, $height);
        } else {
            $generator->generateThumbnail($file, $smallWidth, $smallHeight);
            $generator->generateThumbnail($file, $width, $height);
        }

        $this->extend('updateGeneratedThumbnails', $file, $links, $generator);
        return $links;
    }
426209
def set_thumbnail(self, thumbnail):
        
        self.thumbnail = thumbnail
        if isinstance(self.thumbnail, str):
            from .files import ThumbnailFile
            self.thumbnail = ThumbnailFile(path=self.thumbnail)

        if self.thumbnail:
            self.add_file(self.thumbnail)
485889
public EmbedBuilder setThumbnail(InputStream thumbnail, String fileType) {
        delegate.setThumbnail(thumbnail, fileType);
        return this;
    }
317784
def img_box(img, box):
    
    if isinstance(box, tuple):
        box = Box.from_tup(box)

    if len(img.shape) == 3:
        return img[box.y:box.y + box.height, box.x:box.x + box.width, :]
    else:
        return img[box.y:box.y + box.height, box.x:box.x + box.width]
869122
def create_image(self, image_file, caption):
        
        suffix = 'png'
        if image_file:
            img = Image.open(os.path.join(self.gallery, image_file))
            width, height = img.size
            ratio = width/WIDTH
            img = img.resize((int(width // ratio),
                              int(height // ratio)),
                             Image.ANTIALIAS)
        else:
            img = Image.new('RGB', (WIDTH, HEIGHT), 'black')
            image = self.add_caption(img, caption)
            
        image = img

        return image