Exemplo n.º 1
0
    def get_thumbnail(self, size='small'):
        """Return a dict with two keys:
        - hide: True if this item shouldn't show a thumbnail
        - url: The URL to the thumbnail image (None if hide is True)
        The result of the method is cached.
        This logic is old and kind of weird, it might need review"""
        thumbnail = cache.get('version.%s.thumbnail.%s' % (self.id, size))
        if thumbnail is None:
            if self.article and self.article.hide_thumbnail:
                thumbnail = {
                    'hide': True,
                    'url': None,
                }
            else:
                if self.article and self.article.thumbnail is not None:
                    thumbnail = {
                        'hide': False,
                        'url': self.article.thumbnail,
                    }
                else:
                    # Define "main image" as the earliest one occurring (sorted by row, column, content)
                    content = self.get_first_image_content()
                    if content is not None:
                        thumbnail = {
                            'hide': False,
                            'url': json.loads(content.content)['src'],
                        }
                    else:
                        # There are no images in this article (shouldn't really happen)
                        thumbnail = {
                            'hide': True,
                            'url': None,
                        }

                # Statically use the 150px version. This should be optimized; save
                # the available sizes with the model and use the smallest appropriate one.
                if thumbnail['url'] is not None and Image.url_is_local(thumbnail['url']):
                    if size == 'small':
                        size_string = str(min(settings.THUMB_SIZES))
                    else:
                        size_string = str(settings.THUMB_SIZES[-2])
                    t = thumbnail['url']
                    # Remove previous size spec if existing
                    t = re.sub('-\d+(?P<ext>\.[a-z]{3}[a-z]?)$', '\g<ext>', t)
                    thumbnail['url'] = '%s-%s%s' % (
                        t[:t.rfind('.')],
                        size_string,
                        t[t.rfind('.'):]
                    )

        cache.set('version.%s.thumbnail.%s' % (self.id, size), thumbnail, 60 * 60 * 24)
        return thumbnail
Exemplo n.º 2
0
def image_width(value, arg=940):
    """
    Will return URL with image version width appended to file name if width is valid, or first in THUMB_SIZES if not
    """

    width = int(arg)

    if not Image.url_is_local(value):
        return value

    if width not in settings.THUMB_SIZES:
        width = settings.THUMB_SIZES[0]

    return re.sub(r"(.+)\.(.+)$", r"\1-%s.\2" % width, value)
Exemplo n.º 3
0
def _format_thumbnail_url(url, size):
    """Create and return thumbnail url

    Adds correct size query parameter if it's a local file.
    """
    if not Image.url_is_local(url):
        return url

    if size == 'small':
        size_string = str(min(settings.THUMB_SIZES))
    else:
        size_string = str(settings.THUMB_SIZES[-2])

    # Remove previous size spec if existing
    url = re.sub('-\d+(?P<ext>\.[a-z]{3}[a-z]?)$', '\g<ext>', url)
    url = '%s-%s%s' % (
        url[:url.rfind('.')],
        size_string,
        url[url.rfind('.'):]
    )
    return url
Exemplo n.º 4
0
    def get_image_source(self):
        if self.type != 'image':
            raise Exception("You can only call this method on image contents, check your code logic")

        source = self.get_content['src']

        if not Image.url_is_local(source):
            # Not an image from the image archive; don't touch it
            return source

        for size in settings.THUMB_SIZES:
            if ('-%s') % size in source:
                return source

        column_size = settings.COLUMN_SPAN_MAP[12 // self.column.span]
        if column_size > max(settings.THUMB_SIZES):
            # No thumbs are large enough, use the original
            # Not technically possible right now (the largest column is 940px and the largest thumb is 1880)
            return source
        else:
            thumb_size = min([t for t in settings.THUMB_SIZES if t >= column_size])

        name, extension = source.rsplit('.', 1)
        return '%s-%s.%s' % (name, thumb_size, extension)
Exemplo n.º 5
0
def addGallery(request):
    if request.method == 'GET':
        form = UploadForm()
        c = RequestContext({'form': form})
        c.update(csrf(request))
        return (SimpleTemplateResponse('admin/upload.html', c))
    else:
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            # First, copy zipfile to a tmpfile
            zipfile = NamedTemporaryFile(delete=False)
            zipfile.write(request.FILES['file'].read())
            zipfile.close()
            # Now we got the Zip, unzip it!!
            imagesObj = imagesFromZip(zipfile.name)
            imagesList = imagesObj.listImages()
            # Is there images in this zip ?
            if len(imagesList) > 0:
                # regexp for extractiong name ...
                nameRe = re.compile('/([^/]+)$')
                # Create corresponding gallery
                gallery = Gallery()
                gallery.title = form.cleaned_data['title']
                gallery.desc = form.cleaned_data['desc']
                gallery.category = form.cleaned_data['category']
                gallery.save()  # Must save gallery
                # Now, for each images in it, create an image object and bind it to gallery
                for imgPath in imagesList:
                    src = PILImage.open(imgPath)
                    m = nameRe.search(imgPath)
                    imgObj = Image()
                    imgObj.gallery = gallery
                    # First, put the original sized picture
                    # use StringIO hack to save image to a string ...
                    output = StringIO.StringIO()
                    src.save(output, 'JPEG')
                    imgObj.original.save(m.groups()[0],
                                         ContentFile(output.getvalue()))
                    output.close()
                    # Then, resize it to something like 1600*1200
                    (orig_w, orig_h) = src.size
                    orig_s = orig_w * orig_h
                    new_s = 1024 * 768
                    ratio = orig_s / new_s
                    # Resize only if requested size is lower than original
                    if ratio > 1:
                        (new_w, new_h) = (orig_w / (sqrt(ratio)),
                                          orig_h / (sqrt(ratio)))
                        resized = src.resize((int(new_w), int(new_h)))
                    else:  # Else, just keep original one ...
                        (new_w, new_h) = (orig_w, orig_h)
                        resized = src
                    output = StringIO.StringIO()
                    resized.save(output, 'JPEG')
                    imgObj.screen.save(m.groups()[0],
                                       ContentFile(output.getvalue()))
                    output.close()
                    # Finally, get a thumb of 150px*150px, work on resized picture to be faster
                    if new_w < new_h:
                        maxi = new_w
                    else:
                        maxi = new_h
                    thumb = resized.transform((150, 150), PILImage.EXTENT,
                                              (0, 0, maxi, maxi))
                    output = StringIO.StringIO()
                    thumb.save(output, 'JPEG')
                    imgObj.thumb.save(m.groups()[0],
                                      ContentFile(output.getvalue()))
                    output.close()
                    imgObj.save()
                gallery.save()
                return (HttpResponseRedirect(
                    reverse('gallery.admin.views.editGallery',
                            kwargs={'id': gallery.pk})))
            # Cleanup...
            imagesObj.cleanup()
            os.rm(zipfile)
        else:
            c = RequestContext(request, csrf(request))
            c['form'] = form
            return (SimpleResponseTemplate('admin/upload.html', c))
Exemplo n.º 6
0
def addGallery(request):
    if request.method == 'GET':
        form = UploadForm()
        c  = RequestContext(request, {
        'form' : form
        })
        c.update(csrf(request))
        return(SimpleTemplateResponse('admin/upload.html', c))
    else:
        form = UploadForm(request.POST,request.FILES)
        if form.is_valid():
            # First, copy zipfile to a tmpfile
            zipfile = NamedTemporaryFile(delete=False)
            zipfile.write(request.FILES['file'].read())
            zipfile.close()
            # Now we got the Zip, unzip it!!
            imagesObj = imagesFromZip(zipfile.name)
            imagesList = imagesObj.listImages()
            # Is there images in this zip ?
            if len(imagesList) > 0:
                # regexp for extractiong name ...
                nameRe = re.compile('/([^/]+)$')
                # Create corresponding gallery
                gallery = Gallery()
                gallery.title = form.cleaned_data['title']
                gallery.desc  = form.cleaned_data['desc']
                gallery.category = form.cleaned_data['category']
                gallery.save() # Must save gallery 
                # Now, for each images in it, create an image object and bind it to gallery
                for imgPath in imagesList:
                    src = PILImage.open(imgPath)
                    m = nameRe.search(imgPath)
                    imgObj = Image()
                    imgObj.gallery = gallery
                    # First, put the original sized picture
                    # use StringIO hack to save image to a string ...
                    output = StringIO.StringIO()
                    src.save(output,'JPEG')
                    imgObj.original.save(m.groups()[0],ContentFile(output.getvalue()))
                    output.close()
                    # Then, resize it to something like 1600*1200
                    (orig_w,orig_h) = src.size
                    orig_s = orig_w * orig_h
                    new_s = 1024*768
                    ratio = orig_s/new_s
                    # Resize only if requested size is lower than original
                    if ratio > 1:
                        (new_w, new_h) = ( orig_w/(sqrt(ratio)),orig_h/(sqrt(ratio)) )
                        resized = src.resize((int(new_w),int(new_h)))
                    else: # Else, just keep original one ...
                        (new_w, new_h) = (orig_w, orig_h)
                        resized = src
                    output = StringIO.StringIO()
                    resized.save(output,'JPEG')
                    imgObj.screen.save(m.groups()[0],ContentFile(output.getvalue()))
                    output.close()
                    # Finally, get a thumb of 150px*150px, work on resized picture to be faster
                    if new_w < new_h:
                        maxi = new_w
                    else:
                        maxi = new_h
                    thumb = resized.transform((150,150),PILImage.EXTENT,(0,0,maxi,maxi))
                    output = StringIO.StringIO()
                    thumb.save(output,'JPEG')
                    imgObj.thumb.save(m.groups()[0],ContentFile(output.getvalue()))
                    output.close()
                    imgObj.save()
                gallery.save()
                return(HttpResponseRedirect(reverse('gallery.admin.views.editGallery',kwargs={'id': gallery.pk})))
            # Cleanup...
            imagesObj.cleanup()
            os.rm(zipfile)
        else:
            c = RequestContext(request,csrf(request))
            c['form'] = form
            return(SimpleTemplateResponse('admin/upload.html', c))