def image_crop(context, image, ratio=1.0, size=None, preserve_name=False, preserve_path=False):
    """
    {% image_crop image[url] [ratio=1.0] [size=None] %}
    """

    # Get instance or string
    if isinstance(image, basestring):
        image = Image.open(image)

    if size:
        size = size.split('x')
    
    path = image.filename
    i = path.rindex('/')
    imgid = 'tmp_' + path[i+1:]
    path = path[:i+1]

    if not preserve_name:
        imgid = uuid.uuid1().hex
        imgid = imgid + '.' + image.format.lower()

    if not preserve_path:
        path = MEDIACONTENT_STATIC_PATH + '/'

    filename = path + imgid

    nimage = crop_aspect(image, ratio, size)
    nimage.save(filename)
    
    image = Image.open(filename)
    url = filename
    url = re.sub(MEDIA_ROOT, MEDIA_URL, url)
    url = re.sub(STATIC_ROOT, STATIC_URL, url)
    image.url = url
    return image
def image_crop(context,
               image,
               ratio=1.0,
               size=None,
               preserve_name=False,
               preserve_path=False):
    """
    {% image_crop image[url] [ratio=1.0] [size=None] %}
    """

    # Get instance or string
    if isinstance(image, basestring):
        image = Image.open(image)

    if size:
        size = size.split('x')

    path = image.filename
    i = path.rindex('/')
    imgid = 'tmp_' + path[i + 1:]
    path = path[:i + 1]

    if not preserve_name:
        imgid = uuid.uuid1().hex
        imgid = imgid + '.' + image.format.lower()

    if not preserve_path:
        path = MEDIACONTENT_STATIC_PATH + '/'

    filename = path + imgid

    nimage = crop_aspect(image, ratio, size)
    nimage.save(filename)

    image = Image.open(filename)
    url = filename
    url = re.sub(MEDIA_ROOT, MEDIA_URL, url)
    url = re.sub(STATIC_ROOT, STATIC_URL, url)
    image.url = url
    return image
Exemplo n.º 3
0
    def save(self, *args, **kwargs):

        changed_image = self.content != self.__original_image

        if not self.id and not self.pub_date:
            self.pub_date = datetime.datetime.today()

        crop_original = kwargs.get('crop_original', False)

        super(MediaContent, self).save(*args, **kwargs)
        self.mimetype = mimetypes.guess_type(self.content.path)[0]

        if self.mimetype:
            content_type = self.mimetype.replace('/', '_')
        else:
            # assume everything else is text/plain
            content_type = 'text_plain'

        i = self.content.name.rindex('/')
        thumbnail = u'%sthumbnail_%s' % (unicode(
            self.content.name[:i + 1]), unicode(self.content.name[i + 1:]))
        gallery = u'%sgallery_%s' % (unicode(
            self.content.name[:i + 1]), unicode(self.content.name[i + 1:]))
        orig = self.content.name

        if (not self.thumbnail or not self.gallery
                or changed_image) and content_type.split('_')[0] == 'image':
            img_path = self.content.path

            if content_type == 'image_svg+xml':
                try:
                    from nebula.mediacontent import svg_to_png
                    svg_to_png.convert(img_path, svg_to_png.new_name(img_path))
                    img_path = svg_to_png.new_name(img_path)
                    self.content.name = self.content.name[:
                                                          -3] + self.content.name[
                                                              -3:].replace(
                                                                  'svg', 'png')
                except:
                    pass

            image = Image.open(img_path)
            image = convert_to_rgb(image)
            image = crop_aspect(image, ratio=1.0)

            # hace el thumb
            image_thumb = resize(image.copy(), size=self.get_sizes()['thumb'])
            image_thumb.save(os.path.join(settings.MEDIA_ROOT, thumbnail))
            self.thumbnail = thumbnail

            # guarda la imagen para gallery
            image_gallery = resize(image.copy(),
                                   size=self.get_sizes()['gallery'])
            image_gallery.save(os.path.join(settings.MEDIA_ROOT, gallery))
            self.gallery = gallery

            # guarda la imagen al tamaño máximo
            if crop_original:
                image_normal = resize(image.copy(),
                                      size=self.get_sizes()['normal'])
                image_normal.save(os.path.join(settings.MEDIA_ROOT, orig))

        elif (not self.thumbnail or not self.gallery
              or changed_image) and content_type == 'application_pdf':

            # Crea una imagen de la primer pagina de un PDF
            from subprocess import call

            cmd = "gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \
                    -dMaxBitmap=500000000 -dLastPage=1 -dAlignToPixels=0 -dGridFitTT=0 \
                    -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 \
                    -sOutputFile=%(fileout)s %(filein)s"

            filein = os.path.join(settings.MEDIA_ROOT, self.content.name)
            filejpg = self.content.name[:-3] + self.content.name[-3:].replace(
                'pdf', 'jpg')
            fileout = os.path.join(settings.MEDIA_ROOT, filejpg)

            if not os.access(filein, os.R_OK):
                raise 'not access %s' % filein

            files = {
                'filein': filein.replace(' ', '\ '),
                'fileout': fileout.replace(' ', '\ '),
            }

            # devuelve 0 si esta OK
            if not call(cmd % files, shell=True):

                i = filejpg.rindex('/')

                thumbnail = u'%sthumbnail_%s' % (unicode(
                    filejpg[:i + 1]), unicode(filejpg[i + 1:]))
                gallery = u'%sgallery_%s' % (unicode(
                    filejpg[:i + 1]), unicode(filejpg[i + 1:]))

                image = Image.open(fileout)
                image = convert_to_rgb(image)
                #image = crop_aspect(image, ratio=1.0)

                # hace el thumb
                image_thumb = resize(image.copy(),
                                     size=None,
                                     max_width=self.get_sizes()['gallery'][0])
                image_thumb.save(os.path.join(settings.MEDIA_ROOT, thumbnail))
                self.thumbnail = thumbnail

                # guarda la imagen para gallery
                #image_gallery = image.copy()
                image_gallery = resize(image.copy(),
                                       size=None,
                                       max_width=self.get_sizes()['normal'][0])
                image.save(os.path.join(settings.MEDIA_ROOT, gallery))
                self.gallery = gallery

                # borra la original porque es un PDF
                try:
                    os.remove(fileout)
                except (OSError, ValueError):
                    pass

        super(MediaContent, self).save(*args, **kwargs)
Exemplo n.º 4
0
    def save(self, *args, **kwargs):

        changed_image = self.content != self.__original_image

        if not self.id and not self.pub_date:
            self.pub_date = datetime.datetime.today()
        
        crop_original = kwargs.get('crop_original', False)
        
        super(MediaContent, self).save(*args, **kwargs)
        self.mimetype = mimetypes.guess_type(self.content.path)[0]

        if self.mimetype:
            content_type = self.mimetype.replace('/', '_')
        else:
            # assume everything else is text/plain
            content_type = 'text_plain'
        
        i = self.content.name.rindex('/')
        thumbnail = u'%sthumbnail_%s' % (unicode(self.content.name[:i+1]), unicode(self.content.name[i+1:]))
        gallery = u'%sgallery_%s' % (unicode(self.content.name[:i+1]), unicode(self.content.name[i+1:]))
        orig = self.content.name

        if (not self.thumbnail or not self.gallery or changed_image) and content_type.split('_')[0]=='image':
            img_path = self.content.path

            if content_type == 'image_svg+xml':
                try:
                    from nebula.mediacontent import svg_to_png
                    svg_to_png.convert(img_path, svg_to_png.new_name(img_path))
                    img_path = svg_to_png.new_name(img_path)
                    self.content.name = self.content.name[:-3] + self.content.name[-3:].replace('svg', 'png')
                except:
                    pass

            image = Image.open(img_path)
            image = convert_to_rgb(image)
            image = crop_aspect(image, ratio=1.0)

            # hace el thumb
            image_thumb = resize(image.copy(), size=self.get_sizes()['thumb'])
            image_thumb.save(os.path.join(settings.MEDIA_ROOT, thumbnail))
            self.thumbnail = thumbnail

            # guarda la imagen para gallery
            image_gallery = resize(image.copy(), size=self.get_sizes()['gallery'])
            image_gallery.save(os.path.join(settings.MEDIA_ROOT, gallery))
            self.gallery = gallery

            # guarda la imagen al tamaño máximo
            if crop_original:
                image_normal = resize(image.copy(), size=self.get_sizes()['normal'])
                image_normal.save(os.path.join(settings.MEDIA_ROOT, orig))


        elif (not self.thumbnail or not self.gallery or changed_image) and content_type == 'application_pdf':

            # Crea una imagen de la primer pagina de un PDF
            from subprocess import call

            cmd = "gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \
                    -dMaxBitmap=500000000 -dLastPage=1 -dAlignToPixels=0 -dGridFitTT=0 \
                    -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 \
                    -sOutputFile=%(fileout)s %(filein)s"

            filein = os.path.join(settings.MEDIA_ROOT, self.content.name)
            filejpg = self.content.name[:-3] + self.content.name[-3:].replace('pdf', 'jpg')
            fileout = os.path.join(settings.MEDIA_ROOT, filejpg)

            if not os.access(filein, os.R_OK):
                raise 'not access %s' % filein

            files = { 
                'filein': filein.replace(' ', '\ '),
                'fileout': fileout.replace(' ', '\ '), 
            }

            # devuelve 0 si esta OK
            if not call(cmd % files, shell=True):

                i = filejpg.rindex('/')

                thumbnail = u'%sthumbnail_%s' % (unicode(filejpg[:i+1]), unicode(filejpg[i+1:]))
                gallery = u'%sgallery_%s' % (unicode(filejpg[:i+1]), unicode(filejpg[i+1:]))

                image = Image.open(fileout)
                image = convert_to_rgb(image)
                #image = crop_aspect(image, ratio=1.0)

                # hace el thumb
                image_thumb = resize(image.copy(), size=None, max_width=self.get_sizes()['gallery'][0])
                image_thumb.save(os.path.join(settings.MEDIA_ROOT, thumbnail))
                self.thumbnail = thumbnail

                # guarda la imagen para gallery
                #image_gallery = image.copy()
                image_gallery = resize(image.copy(), size=None, max_width=self.get_sizes()['normal'][0])
                image.save(os.path.join(settings.MEDIA_ROOT, gallery))
                self.gallery = gallery

                # borra la original porque es un PDF
                try:
                    os.remove(fileout)
                except (OSError, ValueError):
                    pass
            
        super(MediaContent, self).save(*args, **kwargs)