def image_resize(context, image, size=None, max_width=None, max_height=None, *args, **kwargs):
    """
    {% image_resize image[url] size=75x75 or max_width=70 or max_height=75 %}
    """

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

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

    image = resize(image, size, max_width, max_height)
    print image.size

    imgid = uuid.uuid1().hex
    imgid = imgid + '.jpg'
    fpath = MEDIACONTENT_STATIC_PATH
    filename = os.path.join(fpath, imgid)

    print 'save on', filename
    image.save(filename, 'JPEG', quality=70) # guarda la iamgen resized

    filename = os.path.basename(image.filename)
    image.url = STATIC_URL + filename

    return image
def image_resize(context,
                 image,
                 size=None,
                 max_width=None,
                 max_height=None,
                 *args,
                 **kwargs):
    """
    {% image_resize image[url] size=75x75 or max_width=70 or max_height=75 %}
    """

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

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

    image = resize(image, size, max_width, max_height)
    print image.size

    imgid = uuid.uuid1().hex
    imgid = imgid + '.jpg'
    fpath = MEDIACONTENT_STATIC_PATH
    filename = os.path.join(fpath, imgid)

    print 'save on', filename
    image.save(filename, 'JPEG', quality=70)  # guarda la iamgen resized

    filename = os.path.basename(image.filename)
    image.url = STATIC_URL + filename

    return image
示例#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)
示例#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)