Пример #1
0
 def image_to_pdf(self, img, pdf_path=None, **kwargs):
     """
     Converts an input image file to a PDF file.
     :param img: image file opened with the PIL library.
     :param pdf_path: optional parameter indicating file path of the to-be-generated PDF file.
     A temporary file is created if no value is provided.
     :param kwargs: any parameter accepted by Image.save i.e. quality
     :return:
     """
     processor = ResizeToFit(width=self.max_size_in_pixels[0],
                             height=self.max_size_in_pixels[1])
     img = processor.process(img)
     # Create a white canvas and paste the image
     final_img_width = min(img.size[0], self.max_size_in_pixels[0])
     final_img_height = min(img.size[1], self.max_size_in_pixels[1])
     tmp_image = Image.new("RGB", (final_img_width, final_img_height),
                           "white")
     margin_left = 0
     margin_top = 0
     tmp_image.paste(
         img, (margin_left, margin_top, final_img_width, final_img_height))
     tmp_image = self.compress_img(tmp_image, quality=70)
     # Save the image as .pdf file
     if not pdf_path:
         f = NamedTemporaryFile(delete=False)
         pdf_path = f.name
     tmp_image.save(pdf_path, "PDF", resolution=100.0, **kwargs)
     return pdf_path
Пример #2
0
class Building(Importable, CachedEntity):
    """A physical building withing the campus"""
    #: Full name
    name = djm.CharField(max_length=32, unique=True)
    #: Abbreviated name
    abbreviation = djm.CharField(max_length=16, unique=True, null=True, db_index=True)
    #: Tag in the campus map
    map_tag = djm.CharField(max_length=20, unique=True)
    #: Geographical center
    location = gis.PointField(geography=True, null=True)
    #:  Picture illustrating this building
    picture = djm.ImageField(upload_to=building_pic_path, null=True, blank=True)
    picture_thumbnail = ImageSpecField(
        source='picture',
        processors=[ResizeToFit(*settings.THUMBNAIL_SIZE)],
        format='JPEG',
        options={'quality': settings.MEDIUM_QUALITY})
    picture_cover = ImageSpecField(
        source='picture',
        processors=[ResizeToFit(*settings.COVER_SIZE)],
        format='JPEG',
        options={'quality': settings.HIGH_QUALITY})

    class Meta:
        ordering = ['name']

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('college:building', args=[self.id])
Пример #3
0
class WorkPhoto(models.Model):
    work = models.ForeignKey(Work,
                             on_delete=models.CASCADE,
                             related_name="photo_work",
                             blank=True)
    file = ProcessedImageField(
        format='JPEG',
        options={'quality': 90},
        upload_to="work/",
        processors=[Transpose(),
                    ResizeToFit(width=1024, upscale=False)])
    preview = ProcessedImageField(
        format='JPEG',
        options={'quality': 60},
        upload_to="work/",
        processors=[Transpose(),
                    ResizeToFit(width=102, upscale=False)])
    created = models.DateTimeField(auto_now_add=True,
                                   auto_now=False,
                                   verbose_name="Создано")

    class Meta:
        indexes = (BrinIndex(fields=['created']), )
        verbose_name = 'Фото'
        verbose_name_plural = 'Фото'
        ordering = ["-created"]
Пример #4
0
 def _gen_resized_image_with_width_limited(cls, image, fit_width):
     o_width, o_height = image.size
     if o_width <= fit_width:
         return image
     fit_height = o_height * fit_width / o_width + 1
     processor = ResizeToFit(fit_width, fit_height)
     new_image = processor.process(image)
     return new_image
Пример #5
0
def upload(request):
    """
    이미지를 전송받고 리사이징 및 초보적인 투명화를 진행
    유저에거 컨펌 받기 위해 사진 두 장(원본 리사이즈드, 투명화)의 참조 경로를 리턴함
    """
    if 'image' in request.FILES:
        userfile = request.FILES['image']
        filename = userfile._name

        # 디렉토리가 없으면 생성
        if not os.path.exists(settings.CLOTHES_ROOT):
            os.makedirs(settings.CLOTHES_ROOT)
        if not os.path.exists(settings.CLOTHES_ROOT_TMP):
            os.makedirs(settings.CLOTHES_ROOT_TMP)

        # 임시 파일명 생성
        uuid_list = str(uuid.uuid4()).split('-')
        prefix = uuid_list[0] + '-' + uuid_list[4]
        temp_file = prefix + filename[filename.rindex('.') - 1:]
        temp_file_png = \
            temp_file[0:temp_file.rindex('.')] + '-resized.png'

        # 원본 저장
        fp = open(os.path.join(settings.CLOTHES_ROOT_TMP, temp_file), 'wb')
        for chunk in userfile.chunks():
            fp.write(chunk)
        fp.close()

        # 스마트폰 카메라로 찍은 경우 특정 orientation 에서 이미지가 돌아가는 문제 수정
        source = Image.open(os.path.join(settings.CLOTHES_ROOT_TMP, temp_file))
        if source._getexif() != None:
            exif = dict((ExifTags.TAGS[k], v) \
                for k, v in source._getexif().items() if k in ExifTags.TAGS)
            if 'Orientation' in list(exif.keys()):
                source = source.rotate(-90, expand=True) \
                    if exif['Orientation'] == 6 \
                    else source

        # 임시 리사이즈 및 저장
        processor = ResizeToFit(width=250, height=250)
        target = processor.process(source)
        target.save(os.path.join(settings.CLOTHES_ROOT_TMP, temp_file_png))

        # 초보적 배경 제거
        if source.mode == "RGBA" or "transparency" in source.info:
            mod_file_png = temp_file_png
        else:
            mod_file_png = removebg(settings.CLOTHES_ROOT_TMP, temp_file_png)

        json_data = json.dumps({'org': temp_file_png, 'mod': mod_file_png})

        # processor = Thumbnail(width=150, height=150)
        # source = Image.open(os.path.join(settings.CLOTHES_ROOT_TMP, temp_file))
        # target = processor.process(source)

        return HttpResponse(json_data, content_type="application/json")

    return HttpResponse('Failed to Upload File')
Пример #6
0
class Venue(models.Model):
    owner = models.ForeignKey(User,
                              null=True,
                              blank=True,
                              verbose_name='Responsable',
                              on_delete=models.SET_NULL)
    name = models.CharField(null=False, verbose_name='Nombre', max_length=240)
    description = models.TextField(null=False, blank=True)
    latitude = models.FloatField(null=False, verbose_name='Latitud')
    longitude = models.FloatField(null=False, verbose_name='Longitud')
    image = ProcessedImageField(
        null=True,
        blank=True,
        upload_to=RandomFileName('venue/'),
        verbose_name='Imagen de cabecera',
        processors=[ResizeToFit(900, 900, upscale=False)],
        format='JPEG')
    profile_image = ProcessedImageField(
        null=True,
        blank=True,
        upload_to=RandomFileName('venue/'),
        verbose_name='Imagen de perfil',
        processors=[ResizeToFit(512, 512, upscale=False)],
        format='JPEG')
    profile_thumbnail = ImageSpecField(
        source='profile_image',
        processors=[ResizeToFill(150, 150, upscale=False)],
        format='JPEG',
        options={'quality': 70})
    address = models.TextField(null=True, blank=True)
    public_space = models.BooleanField(
        default=False, verbose_name='Espacio en la vía pública')

    facebook_link = models.CharField(null=True,
                                     blank=True,
                                     verbose_name='Página de Facebook',
                                     max_length=250)
    twitter_link = models.CharField(null=True,
                                    blank=True,
                                    verbose_name='Perfil de Twitter',
                                    max_length=250)
    webpage_link = models.CharField(null=True,
                                    blank=True,
                                    verbose_name='Página web',
                                    max_length=250)

    class Meta:
        verbose_name = 'Escenario'
        verbose_name_plural = 'Escenarios'
        ordering = ['name']
        permissions = (("manage_venue", "Puede gestionar un espacio"), )

    def __str__(self):
        return self.name

    def __unicode__(self):
        return self.name
Пример #7
0
def generate_image_thumbnail(source, width, height, image_format='JPEG'):
    """
    Generates a thumbnail of the provided image that has the specified maximum dimensions.
    """
    image = Image.open(source)
    processor = ResizeToFit(width=width, height=height)
    resized = processor.process(image).convert('RGB')
    resized_image = io.BytesIO()
    resized.save(resized_image, format=image_format)
    return resized_image
Пример #8
0
class PostImage(models.Model):
    post = models.OneToOneField(Post,
                                on_delete=models.CASCADE,
                                related_name='image',
                                null=True)
    image = ProcessedImageField(
        verbose_name=_('image'),
        storage=post_image_storage,
        upload_to=upload_to_post_image_directory,
        width_field='width',
        height_field='height',
        blank=False,
        null=True,
        format='JPEG',
        options={'quality': 80},
        processors=[ResizeToFit(width=1024, upscale=False)])
    width = models.PositiveIntegerField(editable=False,
                                        null=False,
                                        blank=False)
    height = models.PositiveIntegerField(editable=False,
                                         null=False,
                                         blank=False)
    hash = models.CharField(_('hash'), max_length=64, blank=False, null=True)
    thumbnail = ProcessedImageField(
        verbose_name=_('thumbnail'),
        storage=post_image_storage,
        upload_to=upload_to_post_image_directory,
        blank=False,
        null=True,
        format='JPEG',
        options={'quality': 30},
        processors=[ResizeToFit(width=1024, upscale=False)])

    media = GenericRelation(PostMedia)

    @classmethod
    def create_post_image(cls, image, post_id):
        hash = sha256sum(file=image.file)
        return cls.objects.create(image=image, post_id=post_id, hash=hash)

    @classmethod
    def create_post_media_image(cls, image, post_id, order):
        hash = sha256sum(file=image.file)
        post_image = cls.objects.create(image=image,
                                        post_id=post_id,
                                        hash=hash,
                                        thumbnail=image)
        PostMedia.create_post_media(type=PostMedia.MEDIA_TYPE_IMAGE,
                                    content_object=post_image,
                                    post_id=post_id,
                                    order=order)
        return post_image
Пример #9
0
def add_artwork(image_uri, file_path, processor='SmartResize'):
    size = (300, 300)
    try:
        if 'http' in image_uri:
            # Remote image file
            h = requests.head(image_uri)
            content_type = h.headers.get('content-type')
            r = requests.get(image_uri)
            image_data = r.content
            print(content_type)
        else:
            # Local image file
            mime = MimeTypes()
            content_type, a = mime.guess_type(filename)
            with open(image_uri, 'rb') as file:
                image_data = file.read()
    except Exception as e:
        print("Coult not open {0}".format(image_uri))
        return False

    # Try to embed picture
    try:
        fd = mutagen.File(file_path)
        image = Image.open(BytesIO(image_data))
        if 'resizetofit' in processor.lower():
            color_thief = ColorThief(BytesIO(image_data))
            # get the dominant color
            # dominant_color = color_thief.get_color(quality=10)
            dominant_color = color_thief.get_palette()[0]
            processor = ResizeToFit(size[0], size[1])
        else:
            processor = SmartResize(size[0], size[1])
            dominant_color = (255, 255, 255)
        print(dominant_color)
        new_img = processor.process(image)
        background = Image.new("RGB", size, dominant_color)
        background.paste(new_img,
                         mask=new_img.split()[3])  # 3 is the alpha channel
        temp = BytesIO()
        background.save(temp, format="JPEG")
        fd.tags.add(
            APIC(encoding=3,
                 mime=content_type,
                 type=3,
                 desc=u'Album',
                 data=temp.getvalue()))
        fd.save()
        return True
    except Exception as e:
        print(e)
        print('Could not set album art')
        return False
Пример #10
0
class Band(models.Model):
    name = models.CharField(null=False, verbose_name='Nombre', max_length=240)
    tag = models.ForeignKey(Tag, null=True, related_name="band_tag", on_delete=models.SET_NULL)
    genre = models.CharField(null=True, blank=True, verbose_name='etiqueta', max_length=240)
    profile_image = ProcessedImageField(null=True, blank=True, upload_to=RandomFileName('band/'),
                                 processors=[ResizeToFit(512, 512, upscale=False)], format='JPEG', verbose_name='Imagen principal')
    band_image = ProcessedImageField(null=True, blank=True, upload_to=RandomFileName('band/'),
                                        processors=[ResizeToFit(1200, 600, upscale=False)], format='JPEG',
                                        verbose_name='Imagen de cabecera')
    profile_thumbnail = ImageSpecField(source='profile_image',
                                      processors=[ResizeToFill(150, 150, upscale=False)],
                                      format='JPEG',
                                      options={'quality': 70})

    profile_thumb = ImageRatioField('profile_image', '200x200')

    city = models.CharField(null=True, blank=True, verbose_name='Ciudad', max_length=140)
    num_members = models.IntegerField(null=True, blank=True, default=1)
    description = models.TextField(null=True, blank=True, verbose_name='Descripción')
    embed_code = models.TextField(null=True, blank=True, verbose_name='Códido embed para escucha (Bandcamp, Soundcloud, Spotify...')
    embed_media = models.TextField(null=True, blank=True, verbose_name='Códido embed de vídeo (Youtube, Vimeo...')

    facebook_link  = models.CharField(null=True, blank=True, max_length=250, verbose_name='Página de Facebook')
    youtube_link   = models.CharField(null=True, blank=True, max_length=250, verbose_name='Canal de Youtube')
    twitter_link   = models.CharField(null=True, blank=True, max_length=250, verbose_name='Perfil de Twitter')
    instagram_link = models.CharField(null=True, blank=True, max_length=250, verbose_name='Perfil de Instagram')
    bandcamp_link  = models.CharField(null=True, blank=True, max_length=250, verbose_name='Página de BandCamp')
    webpage_link   = models.CharField(null=True, blank=True, max_length=250, verbose_name='Página web')
    presskit_link  = models.CharField(null=True, blank=True, max_length=250, verbose_name='Presskit')
    spotify_link   = models.CharField(null=True, blank=True, max_length=250, verbose_name='Perfil de Spotify')

    owner = models.ForeignKey(User, null=True, blank=True, verbose_name="Responsable", on_delete=models.SET_NULL)
    hidden_in_catalog = models.BooleanField(default=False, verbose_name="Oculto en el listado principal",
                                            help_text="Ocultar el perfil del listado, para bandas que no son de Alcala pero se crea su perfil para ciclos y festivales")

    class Meta:
        verbose_name = 'Banda'
        verbose_name_plural = 'Bandas'
        ordering = ['name']
        permissions = (
            ("manage_band", "Puede gestionar bandas"),
        )

    def __str__(self):
        return self.name

    def __unicode__(self):
        return self.name
Пример #11
0
class Event(models.Model):
    subject = models.CharField(choices=SUBJECT_TYPES, null=True, max_length=20, default=SUBJECT_TYPES[0][0])
    name = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, blank=True, editable=False, null=True)
    ingress = models.TextField(blank=True, null=True)
    description = RichTextField()

    image = models.ImageField(null=True, blank=True)
    image_wide = ImageSpecField(source='image',
                                processors=[ResizeToFit(width=1280, height=800, upscale=True)],
                                options={'quality': 80},
                                autoconvert=True)
    image_medium = ImageSpecField(source='image',
                                  processors=[ResizeToFit(width=750, height=800, upscale=True)],
                                  options={'quality': 80},
                                  autoconvert=True)


    start_time = models.DateTimeField(null=False)
    end_time = models.DateTimeField(blank=True, null=True)

    street_address = models.CharField(max_length=255)
    city = models.CharField(max_length=255, blank=True, null=True)
    lat = models.DecimalField(max_digits=19, decimal_places=16, null=True, default=None, blank=True)
    lng = models.DecimalField(max_digits=19, decimal_places=16, null=True, default=None, blank=True)

    publication_date = models.DateTimeField(default=timezone.now, blank=True)
    visible = models.BooleanField(default=True)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def save(self, *args, **kwargs):
        if (not self.slug) or (slugify(self.name) not in self.slug):
            self.slug = self.__get_unique_slug()
        super().save()

    def __str__(self):
        return f"{self.name}"

    def __get_unique_slug(self):
        slug = slugify(self.name)
        unique_slug = slug
        num = 1
        while Event.objects.filter(slug=unique_slug).exists():
            unique_slug = '{}-{}'.format(slug, num)
            num += 1
        return unique_slug
Пример #12
0
class PostImage(models.Model):
    post = models.OneToOneField(Post,
                                on_delete=models.CASCADE,
                                related_name='image')
    image = ProcessedImageField(
        verbose_name=_('image'),
        storage=post_image_storage,
        upload_to=upload_to_post_image_directory,
        width_field='width',
        height_field='height',
        blank=False,
        null=True,
        format='JPEG',
        options={'quality': 100},
        processors=[ResizeToFit(width=1024, upscale=False)])
    width = models.PositiveIntegerField(editable=False,
                                        null=False,
                                        blank=False)
    height = models.PositiveIntegerField(editable=False,
                                         null=False,
                                         blank=False)
    hash = models.CharField(_('hash'), max_length=64, blank=False, null=True)

    @classmethod
    def create_post_image(cls, image, post_id):
        hash = sha256sum(file=image.file)
        return cls.objects.create(image=image, post_id=post_id, hash=hash)
Пример #13
0
class Thumbnail(ImageSpec):
    processors = [
        ResizeToFit(settings.VCMS_SHARE_THUMBNAIL_WEIGHT,
                    settings.VCMS_SHARE_THUMBNAIL_HEIGHT, False)
    ]
    format = 'JPEG'
    options = {'quality': 80}
Пример #14
0
class Category(models.Model):

    name = models.CharField(null=True,
                            blank=True,
                            verbose_name=_('Nombre'),
                            max_length=250)
    description = models.TextField(null=True,
                                   blank=True,
                                   verbose_name=_('Descripción'))
    color = models.CharField(
        null=True,
        blank=True,
        verbose_name=_('Color de etiqueta (código hexadecimal)'),
        max_length=30)
    photo = ProcessedImageField(
        null=True,
        blank=True,
        upload_to=RandomFileName('momenti/'),
        verbose_name=_('Imagen principal'),
        processors=[ResizeToFit(1024, 1024, upscale=False)],
        format='JPEG')
    photo_thumbnail = ImageSpecField(
        source='photo',
        processors=[ResizeToFill(150, 150, upscale=False)],
        format='JPEG',
        options={'quality': 70})

    class Meta:
        verbose_name = _('Categoría')
        verbose_name_plural = _('Categorías')
        ordering = ['name']

    def __unicode__(self):
        return self.name if self.name else ''
Пример #15
0
class PostventaEventoEquipoDocumento(models.Model):
    evento = models.ForeignKey(PostventaEventoEquipo,
                               related_name='documentos',
                               on_delete=models.PROTECT,
                               db_column='equ')
    nombre_archivo = models.CharField(max_length=120, db_column='nombre')
    archivo = models.FileField(
        upload_to=postventa_evento_equipo_documento_upload_to,
        db_column='file',
        null=True)
    imagen = ProcessedImageField(
        processors=[ResizeToFit(1080, 720)],
        format='JPEG',
        options={'quality': 70},
        upload_to=postventa_evento_equipo_documento_upload_to,
        db_column='img',
        null=True)
    creado_por = models.ForeignKey(User,
                                   on_delete=models.PROTECT,
                                   blank=True,
                                   null=True,
                                   db_column='crt_by')

    class Meta:
        db_table = 'postventa_even_equip_docs'
        permissions = [
            ("list_postventaeventoequipodocumento",
             "Can list documentos evento postventa equipo"),
        ]
Пример #16
0
def faviconGenerator(originalImage, directory):
    index = 0

    sizes = [
        #
        #	FileName		LogoSize		BoxSize
        #
        ["favicon-32", [32, 32], [32, 32]],
        ["favicon-57", [57, 57], [57, 57]],
        ["favicon-76", [76, 76], [76, 76]],
        ["favicon-96", [96, 96], [96, 96]],
        ["favicon-120", [120, 120], [120, 120]],
        ["favicon-128", [128, 128], [128, 128]],
        ["smalltile", [128, 128], [128, 128]],
        ["favicon-144", [144, 144], [144, 144]],
        ["favicon-152", [152, 152], [152, 152]],
        ["favicon-180", [180, 180], [180, 180]],
        ["favicon-196", [196, 196], [196, 196]],
        ["favicon-228", [228, 228], [228, 228]],
        ["mediumtile", [270, 270], [270, 270]],
        ["widetile", [270, 270], [558, 270]],
        ["largetile", [558, 558], [558, 558]],
    ]

    outfile = os.path.splitext(originalImage)[0] + ".png"

    for size in sizes:
        im = Image.open(originalImage)
        processor = ProcessorPipeline([ResizeToFit(size[1][0], size[1][1])])
        result = processor.process(im)
        background = Image.new('RGBA', size[2], (255, 255, 255, 0))
        background.paste(result, (int((size[2][0] - result.size[0]) / 2),
                                  int((size[2][1] - result.size[1]) / 2)))
        background.save(directory + "/" + size[0] + ".png")
        print("{}.png generated".format(size[0]))
Пример #17
0
class Toy(models.Model):
    title = models.CharField(max_length=100)
    toy_image = models.ImageField(upload_to='toy/%Y/%m/%d',
                                  null=True,
                                  blank=True)
    image_thumb = ImageSpecField(
        source='toy_image',
        processors=[ResizeToFit(400, 400)],  # 처리할 작업목록
        format='JPEG',
        options={'quality': 80},
    )
    tech_stack = models.ManyToManyField('TechStack',
                                        related_name='toy_techstack_set',
                                        null=True,
                                        blank=True)
    start_date = models.DateField()
    end_date = models.DateField(null=True, blank=True)
    desc = models.TextField()
    url = models.CharField(max_length=200)
    idate = models.DateTimeField(auto_now_add=True)
    mdate = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "toy"
        ordering = ["-idate"]

    def __str__(self):
        return self.title
Пример #18
0
def create_resizes_of_image(image):
    """ Create the web and thumb, and return a list of (source, dest) images to be transferred to
    the fileserver, including the original.
    """
    event = image.event
    year = event.startdate.split('-')[0]
    dest_media_folder = os.path.join('archive', year, slugify(event.name))

    # Add original to files to be transferred
    files_to_transfer = [(image.original.path,
                          os.path.join(dest_media_folder,
                                       '%d-original.jpg' % image.id))]

    # Do the actual conversion
    pil_img = PILImage.open(image.original)
    thumb = ImageOps.fit(pil_img, (75, 75), PILImage.ANTIALIAS)
    #thumb = ResizeToFit(75, 75).process(pil_img)
    websize = ResizeToFit(1500, 800, upscale=False).process(pil_img)
    for size, appendix in [(thumb, 'thumb'), (websize, 'web')]:
        filename = '%s-%s.jpg' % (image.id, appendix)
        local_path = os.path.join(settings.MEDIA_ROOT, 'local',
                                  'raw-archive-images', filename)
        if not os.path.exists(os.path.dirname(local_path)):
            os.mkdir(os.path.dirname(local_path))
        save_image(size, local_path, 'jpeg')
        files_to_transfer.append(
            (local_path, os.path.join(dest_media_folder, filename)))

    # Set the new URL to the original image
    image.original = None
    image.original = dest_media_folder + '/%d-original.jpg' % image.id

    return files_to_transfer
Пример #19
0
class WebSpec(ImageSpec):
    format = 'JPEG'
    options = {'quality': 90}
    processors = [
        Transpose(Transpose.AUTO),
        ResizeToFit(1600, 1600, upscale=False)
    ]
Пример #20
0
class IntercoopEntity(models.Model):

    name = models.CharField(null=True, blank=True, max_length=250, verbose_name=_('Nombre'))
    expiration = models.IntegerField(default=INVITE_DURATION_YEARS, verbose_name=_('Años de validez'))
    include_code = models.BooleanField(default=True, verbose_name=_('Incluir identificador de socia externa para validación'))
    code_label = models.CharField(null=True, blank=True, max_length=200, verbose_name=_('Etiqueta del identificador'))

    logo = ProcessedImageField(null=True, blank=True, upload_to=RandomFileName('intercoop/'),
                               verbose_name='Logo en alta resolución',
                               processors=[ResizeToFit(1024, 1024, upscale=False)], format='JPEG',
                               options={'quality': 80})

    description = models.TextField(null=True, blank=True, verbose_name='Descripción')
    slug = models.CharField(null=True, blank=True, max_length=200,verbose_name='Enlace permanente', help_text='Identificador para el enlace de alta')

    class Meta:
        verbose_name = _('Entidad de intercooperación')
        verbose_name_plural = _('Entidades de intercooperación')
        ordering = ('name',)
        permissions = (
            ("mespermission_can_manage_entity", _("Puede gestionar entidades de intercooperación")),
            ("mespermission_can_add_entity", _("Puede añadir entidades de intercooperación")),
        )

    def __str__(self):
        return self.name

    def __unicode__(self):
        return self.name
Пример #21
0
class Image(models.Model):
    uuid = models.CharField(_("image uuid"),
                            max_length=36,
                            null=True,
                            blank=True,
                            unique=True)
    photo = ProcessedImageField(
        verbose_name=_("photo"),
        upload_to="uploads/gallery/images",
        processors=[ResizeToFit(3200, 1800)],
        format="PNG",
    )
    photo_preview = ImageSpecField(source="photo",
                                   processors=[ResizeToCover(400, 400)],
                                   format="PNG")
    name = models.CharField(_("name"), max_length=80, blank=False)
    description = models.TextField(_("description"),
                                   max_length=8000,
                                   blank=True)
    show_later = models.BooleanField(_("latest picture"), blank=False)
    date = models.DateTimeField(_("picture date"), blank=False)
    date_created = models.DateTimeField(_("date created"),
                                        auto_created=True,
                                        auto_now_add=True)
    date_updated = models.DateTimeField(_("date updated"), auto_now=True)

    def __str__(self):
        return self.name

    def admin_image_tag(self):
        return mark_safe('<img style="width: 150px;" src="{}" />'.format(
            self.photo_preview.url))

    admin_image_tag.short_desription = _("image short desc")
Пример #22
0
class GalleryPhoto(models.Model):

    gallery = models.ForeignKey(Gallery,
                                null=True,
                                related_name='photos',
                                on_delete=models.CASCADE)
    order = models.IntegerField(verbose_name=_('Orden'), default=0)
    title = models.CharField(null=True,
                             blank=True,
                             verbose_name=_('Título'),
                             max_length=250)
    image = ProcessedImageField(
        null=True,
        blank=True,
        upload_to=RandomFileName('photos/'),
        processors=[ResizeToFit(512, 512, upscale=False)],
        format='JPEG')

    image_thumbnail = ImageSpecField(
        source='image',
        processors=[ResizeToFill(150, 150, upscale=False)],
        format='JPEG',
        options={'quality': 70})

    uploaded = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = _('Foto')
        verbose_name_plural = _('Fotos')
        ordering = ['order']
Пример #23
0
class User(SignatureModel, AbstractUser):
    """Extends the standard django user model with additional fields"""

    default_approver = models.ForeignKey(
        'User',
        on_delete=models.PROTECT,
        related_name='+',
        to_field='username',
        db_column='default_approver',
        blank=True,
        null=True,
    )
    role = models.CharField(max_length=512, blank=True, null=True)
    image = ProcessedImageField(
        upload_to=get_profile_image_filename,
        null=True,
        blank=True,
        processors=[ResizeToFit(1000, 1000)],
        format='JPEG',
        options={'quality': 70},
    )
    phone = PhoneField(max_length=512, blank=True, null=True)
    room = models.CharField(max_length=512, blank=True, null=True)
    on_facewall = models.BooleanField(default=True)
    division = models.ForeignKey('Division', on_delete=models.CASCADE, db_column='division', default=1)

    def get_absolute_url(self):
        return reverse('staff_list:profile', args=[self.pk])

    def phone_number(self):
        if self.phone:
            return self.phone.replace('+44 (0)1865 2', '')
Пример #24
0
def faviconGenerator(imageLocation):
    originalImage = imageLocation
    directory = '/opt/osp/static'

    index = 0

    sizes = [
	#
	#	FileName		LogoSize		BoxSize
	#
		["favicon-16x16",		[16,16],		[16,16]],
		["favicon-32x32",		[32,32],		[32,32]],
		["apple-touch-icon",	[180,180],		[180,180]],
        ["android-chrome-192x192", [192, 192], [192, 192]],
        ["android-chrome-512x512", [512, 512], [512, 512]],

	]

    outfile = os.path.splitext(originalImage)[0] + ".png"

    for size in sizes:
        im = Image.open(originalImage)
        processor = ProcessorPipeline([ResizeToFit(size[1][0], size[1][1])])
        result = processor.process(im)
        background = Image.new('RGBA', size[2], (255, 255, 255, 0))
        background.paste(
			result, (int((size[2][0] - result.size[0]) / 2), int((size[2][1] - result.size[1]) / 2))
		)
        background.save(directory + "/" + size[0] + ".png")
    im = Image.open(originalImage)
    processor = im.resize((16,16), Image.LANCZOS)
    processor.save(directory + "/favicon.ico")
    return 'OK'
Пример #25
0
class Codelab(CommonInfo):
    title = models.CharField(max_length=100)
    image = models.ImageField(upload_to='codelab/%Y/%m/%d',
                              help_text='대표이미지를 선택해주세요.')
    image_thumb = ImageSpecField(
        source='image',
        processors=[ResizeToFit(400, 400)],  # 처리할 작업목록
        format='JPEG',
        options={'quality': 80},
    )
    desc = models.CharField(max_length=200)
    favorite = models.IntegerField(default=0)
    isview = models.BooleanField(default=True)
    category = models.ForeignKey('CodelabCategory',
                                 null=True,
                                 on_delete=models.SET_NULL)

    class Meta:
        db_table = 'codelab'
        ordering = ['-idate']

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('codelab:codelab', args=[self.id])
Пример #26
0
class MyUser(UserMixin,AbstractUser):
    ROLES = (('A', 'Admin'),
             ('SA','Super Admin'),
             ('E','Enumerator'),
             ('V', 'View Only'),
    )
    SEX = (('MALE', 'Male'), ('FEMALE', 'Female'), ('NS', 'Not Set'))
    # TYPE=(('AT','Attendee'),('OG','Organizer'))
    role=models.CharField(max_length=45,default="A",choices=ROLES)
    phone = models.CharField(max_length=50, null=True, blank=True)
    google_profile_image = models.URLField(max_length=200, blank=True, null=True)
    dob = models.DateField(null=True, blank=True)
    bio = models.CharField(max_length=100, null=True, blank=True)
    image = models.ImageField("uploads", upload_to=scramble, null=True, blank=True)
    gender = models.CharField(max_length=5, choices=SEX, default='NS')
    allow_notification = models.BooleanField(default=True, )
    main_image = ImageSpecField(source='image', processors=[ResizeToFit(height=400)], format='JPEG',
                                      options={'quality': 80})
    confirm_code = models.IntegerField(null=True, blank=True)
    reset_code = models.IntegerField(null=True, blank=True)
    old_password = models.CharField(null=True, blank=True,max_length=55)
    changed_password=models.BooleanField(default=False)
    verified=models.BooleanField(default=False)
    dummy=models.BooleanField(default=False)

    class Meta:
        ordering=('id',)
Пример #27
0
class Profile(models.Model):
    user = models.OneToOneField(User,
                                related_name='profile',
                                on_delete=models.CASCADE)

    image = models.ImageField(verbose_name='Image',
                              validators=[validate_image],
                              upload_to=make_upload_path,
                              blank=True,
                              null=True)

    created_at = models.DateTimeField(verbose_name='Publication date',
                                      auto_now_add=True,
                                      null=True)
    updated_at = models.DateTimeField(verbose_name='Updated',
                                      auto_now=True,
                                      null=True)

    thumbnail = ImageSpecField(
        [ResizeToFit(height=60, width=60, upscale=True)], source='image')
    middle = ImageSpecField([ResizeToFit(height=180, width=180, upscale=True)],
                            source='image')

    def __str__(self):
        return self.user.username

    @property
    def upload_dir(self):
        return 'profile/images'

    class Meta:
        ordering = ('-pk', )
        verbose_name = 'Profile'
        verbose_name_plural = 'Profiles'

    def admin_thumbnail(self):
        if self.image:
            return mark_safe('<img src="{}" />'.format(self.thumbnail.url))
        else:
            return ''

    admin_thumbnail.short_description = 'Image'
    admin_thumbnail.allow_tags = True

    @property
    def username(self):
        return self.user.username
Пример #28
0
def create_image_grid(items,
                      thumb_width=500,
                      thumb_height=500,
                      padding=0,
                      background=(255, 255, 255),
                      resize_to_fill=False):
    """ Greate a grid of images.

   :param items:  iterable of [(row, col, image), ...]
   """

    # adjust so that the top left is (0, 0)
    min_row = min(t[0] for t in items)
    min_col = min(t[1] for t in items)
    items = [(row - min_row, col - min_col, image)
             for (row, col, image) in items]

    # find bottom-right
    nrows = 1 + max(t[0] for t in items)
    ncols = 1 + max(t[1] for t in items)

    # output canvas
    cell_width = thumb_width + padding
    cell_height = thumb_height + padding
    size = (ncols * cell_width, nrows * cell_height)
    print 'Creating image grid...'
    print 'nrows:', nrows
    print 'ncols:', ncols
    print 'size:', size
    out = Image.new(mode='RGB', size=size, color=background)

    # splat images
    filled = np.zeros((nrows, ncols), dtype=np.bool)
    for (row, col, image) in items:
        if filled[row, col]:
            continue
        filled[row, col] = True

        try:
            if isinstance(image, basestring):
                thumb = Image.open(image)
            else:
                thumb = open_image(image)
        except Exception as e:
            print e
            continue

        if resize_to_fill:
            thumb = ResizeToFill(thumb_width, thumb_height).process(thumb)
        else:
            thumb = ResizeToFit(thumb_width, thumb_height).process(thumb)
            thumb = ResizeCanvas(thumb_width, thumb_height,
                                 color=background).process(thumb)

        x = col * cell_width
        y = row * cell_height
        out.paste(thumb, box=(x, y, x + thumb_width, y + thumb_height))

    return out
Пример #29
0
class IndexConfiguration(SingletonModel):
    def header_imagen_upload_to(instance, filename):
        new_filename = get_image_name(clase='Header', filename=filename)
        return "web/img/index/%s" % new_filename

    def overlay_publicidad_imagen_upload_to(instance, filename):
        new_filename = get_image_name(clase='Overlay', filename=filename)
        return "web/img/index/%s" % new_filename

    header_titulo = models.CharField(max_length=150, default='Aqui el titulo')
    header_text = models.TextField(max_length=150,
                                   default='Aqui la descripción',
                                   null=True,
                                   blank=True)
    header_text_en = models.TextField(max_length=150,
                                      default='Aqui la descripción Ingles',
                                      null=True,
                                      blank=True)
    header_imagen = ProcessedImageField(
        processors=[SmartResize(width=2560, height=1500, upscale=False)],
        format='JPEG',
        options={'quality': 50},
        upload_to=header_imagen_upload_to,
        verbose_name='Imagen Cabezote (2560 x 1500)',
        null=True,
        blank=True)
    header_imagen_normal = ImageSpecField(
        processors=[SmartResize(width=1280, height=750, upscale=False)],
        options={'quality': 50},
        source='header_imagen',
        format='JPEG')
    header_imagen_webp = ImageSpecField(
        processors=[SmartResize(width=1280, height=750, upscale=False)],
        options={'quality': 50},
        source='header_imagen',
        format='WEBP')
    header_imagen_cell = ImageSpecField(
        source='header_imagen',
        processors=[SmartResize(width=412, height=660, upscale=False)],
        format='JPEG')
    header_imagen_cell_webp = ImageSpecField(
        source='header_imagen',
        processors=[SmartResize(width=412, height=660, upscale=False)],
        format='WEBP')
    overlay_publicidad = ProcessedImageField(
        processors=[ResizeToFit(width=1024, height=768, upscale=False)],
        format='JPEG',
        options={'quality': 70},
        upload_to=overlay_publicidad_imagen_upload_to,
        verbose_name='Imagen Overlay Publicidad (1024 x 768)',
        null=True,
        blank=True)
    overlay_url = models.URLField(blank=True, null=True)

    def __unicode__(self):
        return "Index"

    class Meta:
        verbose_name = "Index"
Пример #30
0
class New(models.Model):

    id = models.BigIntegerField(unique=True, primary_key=True)
    uuid = models.UUIDField(default=uuid.uuid4,
                            editable=False,
                            unique=True,
                            verbose_name="uuid")
    title = models.CharField(max_length=200, verbose_name="Название")
    description = models.TextField(max_length=1000,
                                   verbose_name="Описание новости")
    creator = models.ForeignKey(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE,
                                verbose_name="Пользователь")
    image = ProcessedImageField(
        format='JPEG',
        options={'quality': 90},
        upload_to=upload_to_user_directory,
        processors=[ResizeToFit(width=1024, upscale=False)])
    is_active = models.BooleanField(default=False, verbose_name='Пост активен')
    is_deleted = models.BooleanField(default=False, verbose_name='Пост удален')
    is_private = models.BooleanField(default=False,
                                     verbose_name='Пост приватный')
    content = RichTextUploadingField(
        config_name='default',
        external_plugin_resources=[(
            'youtube',
            '/static/ckeditor_plugins/youtube/youtube/',
            'plugin.js',
        )],
    )

    created = models.DateTimeField(auto_now_add=True,
                                   auto_now=False,
                                   verbose_name="Время публикации")
    votes_off = models.BooleanField(default=False,
                                    verbose_name='Лайки-дизлайки отключены')

    def __str__(self):
        return self.title

    class Meta:
        indexes = (BrinIndex(fields=['created']), )
        verbose_name = "пост"
        verbose_name_plural = "посты"

    def all_visits_count(self):
        from stst.models import NewNumbers

        return NewNumbers.objects.filter(new=self.pk).values('pk').count()

    def likes(self):
        from common.model.votes import NewVotes
        likes = NewVotes.objects.filter(parent=self, vote__gt=0)
        return likes

    def dislikes(self):
        from common.model.votes import NewVotes
        dislikes = NewVotes.objects.filter(parent=self, vote__lt=0)
        return dislikes
Пример #31
0
class Image(SyncableFileModel):
    image = ProcessedImageField(
        upload_to='images',
        format='JPEG',
        options={'quality': 60},
        processors=[ResizeToFit(width=2000, height=2000, upscale=False)])

    syncable_file_fields = ['image']
Пример #32
0
def load_data(num=2000, resize=256, crop=(224, 224),
              folder='catdog_data/train'):
    files = os.listdir(folder)
    chosen = np.random.choice(files, num)
    data = []

    # processors
    w, h = crop
    cropper = SmartCrop(width=w, height=h)

    def get_new_dimensions(im):
        w, h = im.size
        if w < h:
            orientation = 'v'
            small, big = w, h
        else:
            orientation = 'h'
            small, big = h, w
        small_size = resize
        big_size = int(big * float(small_size) / small)
        if orientation == 'v':
            return small_size, big_size
        else:
            return big_size, small_size
    labels = []
    for i, fname in enumerate(chosen):
        print i
        path = os.path.join(folder, fname)
        im = Image.open(path)
        # first resize
        w, h = get_new_dimensions(im)
        resizer = ResizeToFit(width=w, height=h, upscale=True)
        im = resizer.process(im)
        # then crop
        im = cropper.process(im)
        # then to numpy and rescale to [0, 1]
        im = np.float32(np.mean(np.asarray(im), axis=-1)) / 255.
        data.append(im.ravel())
        # don't forget labels
        if 'cat' in fname:
            labels.append(0)
        else:
            labels.append(1)
    return np.vstack(data), np.hstack(labels)
def process(image_url,  processor = None, width=None, height=None, resolution=None, quality=100):
    conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
    bucket = conn.get_bucket(settings.AWS_STORAGE_BUCKET_NAME) 
    if image_url[0] =='/': image_url = image_url[1:] 
    r = requests.get(image_url.replace('https', 'http'))
    img = Image.open(StringIO(r.content))
    processor = ResizeToFit(width, height)
    new_img = processor.process(img)
    new_file = StringIO()
    save_image(new_img, new_file, 'JPEG')
    new_k = Key(bucket)
    parts = urlparse(image_url)
    img_name = os.path.splitext(os.path.basename(parts.path))[0]
    new_k.key = 'il/{}x{}/{}.jpeg'.format(width, height, img_name)
    new_k.content_type = 'image/jpeg'
    new_k.set_contents_from_file(new_file, policy='public-read')
    new_image_url = new_k.generate_url(0, query_auth=False, force_http=True)
    processed_image,_ = ProcessedImage.objects.update_or_create(source_image = image_url, processed_image = new_image_url)
    return processed_image
    
    
Пример #34
0
def generate_image(inpath, outpath, width=None, height=None, format=JPEG,
                   fill=False, upscale=True, anchor=None, quality=80,
                   bgcolor=None, progressive=True, force_cache=False,
                   placeholder_reason=None, placeholder_image_path=None):
    """Generate an image with the passed in settings
    This is used by :func:`resize` and is run outside of the Flask context.

    Args:
        inpath (str):
            Path to the image to generate a new image out of.
        outpath (str):
            Where the new image will end up.
        width (Optional[:class:`int`]):
            The width to use for the generated image.
        height (Optional[:class:`str`]):
            The height to use for the generated image.
        format (str):
            Format to convert into. Defaults to "JPEG".
        fill (bool):
            Fill the entire width and height that was specified if True,
            otherwise keep the original image dimensions. Defaults to False.
        upscale (bool):
            Whether or not to allow the image to become bigger than the
            original if the request width and/or height is bigger than its
            dimensions. Defaults to True.
        anchor (str):
            Deprecated since Flask-Resize 0.6.
        quality (int):
            Quality of the output image, if the format is JPEG. Defaults to 80.
        bgcolor (Optional[:class:`str`]):
            If specified this color will be used as background.
        progressive (bool):
            Whether to use progressive encoding or not when JPEG is the
            output format.
        force_cache (bool):
            Whether to force the function to always use the image cache. If
            false, will reaise a :class:`exc.StopImageGeneration` if the
            generated image would be the same as the original. Defaults to
            False.
        placeholder_reason (Optional[:class:`str`]):
            A text to show the user if the image path could not be found.
        placeholder_image_path (Optional[:class:`str`]):
            The path to the image to use as the background of the placeholder.

    Raises:
        :class:`exc.ImageNotFoundError`:
            If the source image cannot be found or is not a file.
        :class:`exc.StopImageGeneration`:
            If force_cache is False and if the image transformation would
            result in the same image as the original.

    Returns:
        PIL.Image:
            The generated image.
    """
    if anchor:
        warnings.warn(
            "anchor has been deprecated in Flask-Resize 0.6 and doesn't do anything to the image. Will be removed in 1.0.",
            DeprecationWarning
        )

    if not os.path.isfile(inpath):
        if placeholder_reason:
            img = create_placeholder_img(width, height, placeholder_reason,
                                         placeholder_image_path)
        else:
            raise exc.ImageNotFoundError(inpath)
    else:
        img = Image.open(inpath)

    original_width, original_height = img.size
    w = width or original_width
    h = height or original_height
    if not force_cache and format == _parse_format(inpath) and fill is False:
        if (w == original_width and h == original_height) or \
           (upscale is False and \
           (w >= original_width or h >= original_height)):
            if not placeholder_reason:
                raise exc.StopImageGeneration()

    processor_kwargs = dict(width=width, height=height, upscale=upscale)
    _mkdir_p(outpath.replace('\\','/').rpartition('/')[0])

    if fill:
        if bgcolor:
            mat_color = ImageColor.getrgb(parse_rgb(bgcolor))
        elif format == JPEG:
            mat_color = (255, 255, 255, 255)  # White
        else:
            mat_color = (0, 0, 0, 0)  # Transparent
        processor_kwargs['mat_color'] = mat_color  # Transparent

    processor = ResizeToFit(**processor_kwargs)
    img = processor.process(img)

    assert (not os.path.exists(outpath)), 'Path to save to already exists'

    options = {}
    if format == JPEG:
        options.update({'quality': int(quality), 'progressive': progressive})

    if bgcolor is not None:
        img = make_opaque(img, bgcolor)

    with open(outpath, 'wb') as outfile:
        save_image(img, outfile, format=format, options=options)
    return img
Пример #35
0
def resize(image, *size):
    """
    size is a pair like 600, 600
    """
    processor = ResizeToFit(*size)
    return processor.process(image)