Example #1
0
 def as_json(self):
   return {
     'name': self.name,
     'url': self.src.url,
     'url_medium': get_thumbnail(self.src,"300x300").url,
     'url_small': get_thumbnail(self.src,"128x128", crop='center').url,
   }
Example #2
0
 def dehydrate(self, bundle):
     album_cover = bundle.obj.get_album_cover()
     cover_image_thumb = get_thumbnail(album_cover.image, "240x165")
     cover_image_large = get_thumbnail(album_cover.image, "1024x768")
     bundle.data['cover_image_thumb'] = cover_image_thumb.url
     bundle.data['cover_image_large'] = cover_image_large.url
     return bundle 
Example #3
0
    def save(self, *args, **kwargs):

        basewidth = 500

        self.collection = get_object_or_404(Coll, slug=self.slugi)

        super(Picture, self).save()

        self.thumb = get_thumbnail(self.filename,'98x98', crop='center', quality=99).url
        self.medium = get_thumbnail(self.filename,'230x270', crop='center', quality=99).url

        super(Picture, self).save()



        # super(Picture, self).save()
        if not self.filename:
            return



        image = Image.open(self.filename)
        #(width, height) = image.size
        wpercent = (basewidth/float(image.size[0]))
        hsize = int((float(image.size[1])*float(wpercent)))
        image = image.resize((basewidth, hsize), Image.ANTIALIAS)
        image.save(self.filename.path)
Example #4
0
 def _get_thumbnail(self, *args, **kwargs):
     try:
         return get_thumbnail(*args, **kwargs)
     except (IOError, IndexError, TypeError):
         i = Picture.objects.get(id=2072)
         self.file = i.file
         return get_thumbnail(self, "400")
Example #5
0
    def preview(self, user):
        from django.core.files.storage import default_storage as storage

        fh = storage.open(self.file.name, "w")

        # file_path = self.file.url

        result = {
            "id": self.pk,
            "type": self.type,
            "xLit": get_thumbnail(fh, "80x80", crop='center', quality=90).url,
            "xBig": get_thumbnail(fh, "1080x1080", crop='center').url,
            "xFull": self.file.url,
            "uploader_id": self.uploader.id
        }

        # from django.core.files import File
        # img_file = self.file
        # if self.type == Media.TYPE_IMAGE:
        #     img_file = File(open(self.file.path))
        # else:
        #     img_file = File(open(self.file.path.replace(".webm", ".png")))

        # result["x128"] = get_thumbnail(img_file, "128x128", crop='center', quality=80).url

        return result
Example #6
0
    def to_dict(self):
        dict = {
            'title': self.title,
            'date_created': str(self.date_created),
            'date_saved': str(self.date_saved),
            'market': unicode(self.reference.market),
            'filter_solution': unicode(self.reference.filter_solution),
            'application': self.application,
            'machine': self.machine,
            'machine_type': self.machine_type,
            'filter': self.filter,
            'filter_element': self.filter_element,
            'manufacturer': str(self.reference.manufacturer),
            'problem': self.problem,
            'solution': self.solution,
            'url': reverse('view_reference', args=[self.reference.slug]),
        }

        if self.reference.illustration1:
            dict['list_image'] = get_thumbnail(self.reference.illustration1, "200x200", crop='center').url
        elif self.reference.illustration2:
            dict['list_image'] = get_thumbnail(self.reference.illustration2, "200x200", crop='center').url

        if self.reference.is_customer_public:
            dict['customer'] = self.reference.customer.to_dict()
        return dict
Example #7
0
    def test_retina(self):
        get_thumbnail(self.im, '50x50')

        actions = [
            # save regular resolution, same as in StorageTestCase
            'open: retina.jpg',
            'save: test/cache/19/10/1910dc350bbe9ee55fd9d8d3d5e38e19.jpg',
            'get_available_name: test/cache/19/10/1910dc350bbe9ee55fd9d8d3d5e38e19.jpg',
            'exists: test/cache/19/10/1910dc350bbe9ee55fd9d8d3d5e38e19.jpg',

            # save the 1.5x resolution version
            'save: test/cache/19/10/[email protected]',
            'get_available_name: test/cache/19/10/[email protected]',
            'exists: test/cache/19/10/[email protected]',

            # save the 2x resolution version
            'save: test/cache/19/10/[email protected]',
            'get_available_name: test/cache/19/10/[email protected]',
            'exists: test/cache/19/10/[email protected]'
        ]
        self.assertEqual(self.log, actions)

        with open(pjoin(settings.MEDIA_ROOT, 'test/cache/19/10/[email protected]')) as fp:
            engine = PILEngine()
            self.assertEqual(engine.get_image_size(engine.get_image(ImageFile(file_=fp))), (75, 75))
Example #8
0
 def test_a_new(self):
     slog.start_log()
     get_thumbnail(self.im, '50x50')
     log = slog.stop_log()
     actions = [
         # first see if the file exists
         'exists: test/cache/cc/33/cc33e9e8b2355e7e2a9437319c046ad4.jpg',
         # open the original for thumbnailing
         'open: org.jpg',
         # save the file
         'save: test/cache/cc/33/cc33e9e8b2355e7e2a9437319c046ad4.jpg',
         # check for filename
         'get_available_name: test/cache/cc/33/cc33e9e8b2355e7e2a9437319c046ad4.jpg',
         # called by get_available_name
         'exists: test/cache/cc/33/cc33e9e8b2355e7e2a9437319c046ad4.jpg',
         # save the 1.5 resolution version
         'save: test/cache/cc/33/[email protected]',
         'get_available_name: test/cache/cc/33/[email protected]',
         'exists: test/cache/cc/33/[email protected]',
         # save the 2 resolution version
         'save: test/cache/cc/33/[email protected]',
         'get_available_name: test/cache/cc/33/[email protected]',
         'exists: test/cache/cc/33/[email protected]'
     ]
     self.assertEqual(log, actions)
Example #9
0
def thumbnail(source, *args, **kwargs):
    """
    Wraps sorl thumbnail with an additional 'default' keyword
    https://github.com/mozilla/mozillians/blob/master/apps/common/helpers.py
    """

    # Templates should never return an exception
    try:
        # We set path either from the filesystem or from a url
        if hasattr(source, 'path'):
            if not source.path:
                source = kwargs.get('default')
            path = source.path
        elif hasattr(source, 'url'):
            path = urlparse(source.url).path
        else:
            raise NotImplementedError('Unknown storage backend')

        # Handle PNG images a little more gracefully
        # Make sure thumbnail call doesn't specifically set format
        if not 'format' in kwargs:
            filetype = path.split('.')[-1]
            # If we have a PNG, don't default convert to JPG
            if filetype.lower() == 'png':
                kwargs['format'] = 'PNG'

        return get_thumbnail(source, *args, **kwargs).url
    except Exception as e:
        logger.error('Thumbnail had Exception: %s' % (e,))
        source = getattr(settings, 'DEFAULT_IMAGE_SRC')
        return get_thumbnail(source, *args, **kwargs).url
Example #10
0
def image_rotator(request):
    logger.info('Rotate image called by user='******', ip='+str(request.META['REMOTE_ADDR']))
    if request.method=='POST':
        try:
            direction = request.POST["direction"]
            pk = request.POST["pk"]
        except KeyError:
            logger.error('Rotator: No image PK or direction of rotation given!')
            return HttpResponseBadRequest('No image PK or direction given!')
        else: pass
        image = get_object_or_404(Image, pk=pk)
        if (request.user.is_superuser) or (image.user==request.user):
            im = PilImage.open(image.image)
            if direction=='right':
                rotated_image = im.rotate(270)
            elif direction=='left':
                rotated_image = im.rotate(90)
            else: return HttpResponseBadRequest('Incorrect direction!')
            thumbnails_delete(image.image, delete_file=False)
            rotated_image.save(image.image.file.name, owerwrite=True)
            new_image_width=rotated_image.size[0]
            new_image_height=rotated_image.size[1]
            if (new_image_width >= new_image_height):
                thumbnail=get_thumbnail(image.image.file.name, "795x594", crop="10px 10px")
            else:
                thumbnail=get_thumbnail(image.image.file.name, "795x1094", crop="10px 10px")
            return HttpResponse(thumbnail.url)
            
        else: return HttpResponseBadRequest('You have no permission to rotate images!')
    else: return HttpResponseBadRequest('Only POST accepted!')
Example #11
0
    def create_image(self, options):
        attr_map = {
            "alt": "alt_text",
            "width": "width",
            "height": "height",
        }
        img = etree.Element('img')
        img_obj = models.Image.objects.get(
                slug=unicode(options['url'])) 

        thumb = get_thumbnail(
                img_obj.image, 
                "{0}x{1}".format(options['width'], options['height']), 
                crop=options['crop'])

        larger = get_thumbnail(
                img_obj.image,
                options['width'],
                crop="center")

        for attr, src in attr_map.iteritems():
            img.set(attr, options[src])

        img.set('src', thumb.url)
        a = etree.Element('a')
        a.set('href', larger.url)
        a.append(img)
        el = etree.Element('div')
        el.set('class', 
                'post-image {0}'.format(
                    options['extra_class'])
                ) 
        el.append(a)
        return html.tostring(el)
Example #12
0
def photo(request, photo_pk):
    """
    Displays a map for the specified photo along with its details.
    """
    photo = get_object_or_404(Photo, pk=photo_pk)
    # Get the EXIF tags that belongs to the current photo
    displayed_exif_tags = [tag.strip() for tag in config.DISPLAYED_EXIF_TAGS.split('\n')]
    exif_tags = photo.exiftag_set.filter(key__in=displayed_exif_tags)
    sorted_exif_tags = [{'key': tag.key, 'value': tag.substituted_value} for tag in (exif_tags.filter(key=tag)[0] for tag in displayed_exif_tags if exif_tags.filter(key=tag).count() > 0)]
    context = RequestContext(request)
    context.update({
                    'accuracy': photo.get_location_accuracy_display(),
                    'accuracy_value': Photo.LOCATION_ACCURACY_IN_METERS[photo.location_accuracy],
                    'date_taken': photo.date_taken,
                    'elevation': photo.get_elevation(),
                    'exif_tags': json.dumps(sorted_exif_tags),
                    'latitude': photo.latitude,
                    'large_thumbnail_url': get_thumbnail(photo.file, settings.PHOTO_LARGE_SIZE, crop='noop').url,
                    'location': photo.get_location(),
                    'longitude': photo.longitude,
                    'map_url': reverse('robinson_app.views.map'),
                    'name': unicode(photo),
                    'search_url': urllib.urlencode({ 'q': photo.get_location() }),
                    'small_thumbnail_url':  get_thumbnail(photo.file, settings.PHOTO_SMALL_SIZE, crop='noop').url,
                    'GA_ID': config.GA_ID
    })
    return render_to_response('photo.html', context)
Example #13
0
 def get_thumbnails(self):
     mb = self.image.file.size / (1024*1024)
     print(f'Main image {self.image.name} with size {mb}')
     get_thumbnail(self.image, '1920x1164', crop='center')
     get_thumbnail(self.image, '1024', crop='center')
     for image in self.images.all():
         image.get_thumbnails()
Example #14
0
 def get_small_thumbnail(self):
     if self.position == "s_bloque":
         return get_thumbnail(self.imagen, "272x100", upscale=False).url
     elif self.position == "p_bloque":
         return get_thumbnail(self.imagen, "272x140", upscale=False).url
     else:
         return get_thumbnail(self.imagen, "594x61", upscale=False).url
Example #15
0
    def get_user_json(user, picture_size='32x32'):
        """
        Return a user in JSON
        
        Args:
        user: The user to serialize in JSON
        picture_size: Profile picture size
        """
        im = None

        # Workaround for the moment : inactive with website url = partner
        if not user.is_active and user.get_profile().website_url:
            profile_link = user.get_profile().website_url
            if user.get_profile().image:
                try:
                    im = get_thumbnail(user.get_profile().image, '90x90', quality=99)
                except IOError:
                    logging.warn('Profile image not found for user {0}'.format(user.id))
        else:
            profile_link = reverse('website.views.profile', kwargs={'user_id': user.username})
            if user.get_profile().image:
                try:
                    im = get_thumbnail(user.get_profile().image, picture_size, crop='center', quality=99)
                except IOError:
                    logging.warn('Profile image not found for user {0}'.format(user.id))
        user_json = { "id" : user.id, "username": user.username, "first_name": user.first_name, "facebook_id" : user.get_profile().facebook_id, "profile_link" : profile_link}
        if 'im' in locals() and im and im.url:
            user_json.update({"picture": im.url})

        return user_json
Example #16
0
def _get_carousel_data(project, updates):
    photos = []
    if project.current_image:
        try:
            im = get_thumbnail(project.current_image, '750x400', quality=99)
            photos.append({
                "url": im.url,
                "caption": project.current_image_caption,
                "credit": project.current_image_credit,
                "direct_to_url": '',
            })
        except IOError:
            pass
    for update in updates:
        if update.photo:
            direct_to = reverse('update-main', kwargs={
                'project_id': project.pk,
                'update_id': update.pk
            })
            try:
                im = get_thumbnail(update.photo, '750x400', quality=99)
                photos.append({
                    "url": im.url,
                    "caption": update.photo_caption,
                    "credit": update.photo_credit,
                    "direct_to_url": direct_to,
                })
            except IOError:
                continue
    return {"photos": photos}
    def test_retina(self):
        get_thumbnail(self.image, '50x50')

        actions = [
            'exists: test/cache/91/bb/91bb06cf9169e4c52132bb113f2d4c0d.jpg',

            # save regular resolution, same as in StorageTestCase
            'open: retina.jpg',
            'save: test/cache/91/bb/91bb06cf9169e4c52132bb113f2d4c0d.jpg',
            'get_available_name: test/cache/91/bb/91bb06cf9169e4c52132bb113f2d4c0d.jpg',
            'exists: test/cache/91/bb/91bb06cf9169e4c52132bb113f2d4c0d.jpg',

            # save the 1.5x resolution version
            'save: test/cache/91/bb/[email protected]',
            'get_available_name: test/cache/91/bb/[email protected]',
            'exists: test/cache/91/bb/[email protected]',

            # save the 2x resolution version
            'save: test/cache/91/bb/[email protected]',
            'get_available_name: test/cache/91/bb/[email protected]',
            'exists: test/cache/91/bb/[email protected]'
        ]
        self.assertEqual(self.log, actions)

        path = os.path.join(settings.MEDIA_ROOT,
                            'test/cache/91/bb/[email protected]')

        with open(path) as fp:
            engine = PILEngine()
            self.assertEqual(engine.get_image_size(engine.get_image(ImageFile(file_=fp))), (75, 75))
 def handle(self, **options):
     for leaflet_image in tqdm(LeafletImage.objects.all().exclude(image="").order_by('?')):
         try:
             get_thumbnail(leaflet_image.image, '350').url
             get_thumbnail(leaflet_image.image, '100x100', crop='center').url
         except:
             pass
Example #19
0
    def render_column(self, row, column):

        if column == "id":
            return {'id': row.id,
                    'display': reverse_lazy('parte:detalle', args=[row.id])
            }
        elif column == "fecha":
            return  row.fecha.strftime("%d/%m/%Y")
        elif column == 'grupo':
            return row.get_nombre_grupo_alumno()
        elif column == "fotoalu":
            if row.grupoalumno.cursoalumno.alumno.foto:
                return get_thumbnail(row.grupoalumno.cursoalumno.alumno.foto, '50x40').url
            else:
                return u''
        elif column == "alumno":
            return row.get_nombre_completo_alumno()
        elif column == "fotoprofe":
            if row.cursoprofesor.profesor.foto:
                return get_thumbnail(row.cursoprofesor.profesor.foto, '50x40').url
            else:
                return u''
        elif column == "profesor":
            return row.get_nombre_completo_profesor()
        elif column == "urls":
            return {
                'detalle': reverse_lazy('parte:detalle', args=[row.id]),
                'editar': reverse_lazy('parte:editar', args=[row.id]),
                'eliminar': reverse_lazy('parte:eliminar', args=[row.id])
            }
        else:
            return super(ParteResponsableBaseDatatableView, self).render_column(row, column)
Example #20
0
    def tag(self):
        klasses = [
            'img-thumbnail',
            'inline-image-base',
            'inline-image-%s' % self.size,
        ]

        if self.size == 'headline':
            thumbnail = get_thumbnail(self.image.image.file,
                                      '960x200',
                                      crop='center')
        else:
            klasses.append('inline-image-align-%s' % self.align)

            if self.size == 'medium':
                thumbnail = get_thumbnail(self.image.image.file, '260x260')
            elif self.size == 'small':
                thumbnail = get_thumbnail(self.image.image.file, '174x174')
            elif self.size == 'full':
                thumbnail = self.image.image

        return ('<img src="%s" alt="%s" class="%s" '
                'height="%spx" width="%spx" />' % (
                    thumbnail.url,
                    self.alt,
                    ' '.join(klasses),
                    thumbnail.height,
                    thumbnail.width,
                ))
Example #21
0
def prepare_json_list(pins):
	"""
	Return list of dictionaries describing pins. This should be used when returning pins in JSON.
	"""
	pin_list = []
	for p in pins:
		if hasattr(p, 'is_advertisment'):
			data = {'content': p.get_advertisment()}
		else:
			try:
				image = get_thumbnail(p.get_image(), '266', crop='center')
				im = {'url': image.url, 'width': image.width, 'height': image.height}
			except ThumbnailError:
				continue
			comments = []
			for c in p.comments:
				if c.user:
					try:
						c_image = get_thumbnail(c.user.get_profile().image, '30x30', crop='center')
						c_im = {'url': c_image.url, 'width': c_image.width, 'height': c_image.height}
					except ThumbnailError:
						continue
				comments.append({'im': c_im,'comment': truncate_words(c.comment, 5)})
			data = {'pk': p.pk, 'absolute_url': p.get_absolute_url(),'popup_url': p.get_popup_url(), 'number_of_repins': p.get_number_of_repins(), 
			'number_of_likes': p.get_number_of_likes(), 'thumbnail': im ,
				'description': truncate_words(p.description, 15), 'comments': comments}
		pin_list.append(data)

	return pin_list
Example #22
0
 def test_a_new(self):
     slog.start_log()
     get_thumbnail(self.im, '50x50')
     log = slog.stop_log()
     actions = [
         # first see if the file exists
         'exists: test/cache/ff/3d/ff3d0f5fa6e8da5924298ce7354a9d02.jpg',
         # open the original for thumbnailing
         'open: org.jpg',
         # save the file
         'save: test/cache/ff/3d/ff3d0f5fa6e8da5924298ce7354a9d02.jpg',
         # check for filename
         'get_available_name: test/cache/ff/3d/ff3d0f5fa6e8da5924298ce7354a9d02.jpg',
         # called by get_available_name
         'exists: test/cache/ff/3d/ff3d0f5fa6e8da5924298ce7354a9d02.jpg',
         # save the 1.5 resolution version
         'save: test/cache/ff/3d/[email protected]',
         'get_available_name: test/cache/ff/3d/[email protected]',
         'exists: test/cache/ff/3d/[email protected]',
         # save the 2 resolution version
         'save: test/cache/ff/3d/[email protected]',
         'get_available_name: test/cache/ff/3d/[email protected]',
         'exists: test/cache/ff/3d/[email protected]'
     ]
     self.assertEqual(log, actions)
Example #23
0
def create_thumbnails(image_field):
    errors = False
    for size_name, size in settings.IMAGE_SIZES.items():
        try:
            get_thumbnail(image_field, size, **settings.IMAGE_OPTIONS[size_name])
        except (IOError, ThumbnailError):
            errors = True
            logger.exception("Failed to create thumbnail")
    return not errors
Example #24
0
 def make_thumbnails(self):
     # Current Thumb list
     # 240x165 (streams)
     # 75x75 for map (Other location photos)
     # 1024x768 for photo.html
     
     im = get_thumbnail(self.image, '75x75', crop="center")
     im2 = get_thumbnail(self.image, '1024x768')
     im3 = get_thumbnail(self.image, '240x165')
    def handle(self, **options):
        try:
            ct = CachedCategoryTree()
            for e in Event.objects.all():
                image = e.image_chain(ct)
                get_thumbnail(image, **settings.IPHONE_THUMB_OPTIONS)

        except Exception, e:
            raise CommandError(e)
    def handle(self, *args, **options):
        from brouwers.albums.models import Photo

        for photo in Photo.objects.all():
            for size in self.sizes:
                try:
                    get_thumbnail(photo.image, size, upscale=False)
                except Exception as e:
                    logger.exception(e)
Example #27
0
 def view_all_pictures(self):
     all_pictures = self.get_all_pictures()
     all_pictures.append(self.get_picture())
     thumbs = '<ul>'
     for pic in all_pictures:
         print(get_thumbnail(pic, '240x143', crop='center', quality=99))
         thumbs += '<li><img src="'
         thumbs +=  get_thumbnail(pic, '240x143', crop='center', quality=99).url
         thumbs +=  '"/></li>'
     return thumbs
Example #28
0
def download_resized(request, logo_id):
    logo = get_or_404_by_account(Logo, request.account, logo_id)
    width = int(request.GET['width'])
    height = int(request.GET['height'])
    w_by_h = "%sx%s" %(width,height)
    if "crop" in request.GET:
        im = get_thumbnail(logo.image, w_by_h, crop='center')
    else:
        im = get_thumbnail(logo.image, w_by_h, )
    return HttpResponseRedirect(im.url)
Example #29
0
 def resize_image(self, img, dimension, crop):
     try:
         if crop == 'center':
             img = get_thumbnail(img, dimension, crop='center')
         else:
             img = get_thumbnail(img, dimension)
         img = "%s/%s" % (settings.MEDIA_ROOT, img.name)
     except:
         img = "%s/image_moderator/img-not-found.jpg" % settings.MEDIA_ROOT
     return img
Example #30
0
def get_images(request, type, id):
    sizes = settings.ARMSTRONG_PRESETS
    imgs = Image.objects.all().order_by('-pub_date')[:100]
    json_list = []
    for img in imgs:
        json_list.append({
            'image': get_thumbnail(img.image, str(sizes['article_body']['width'])).url,
            'thumb': get_thumbnail(img.image, str(sizes['article_small']['width'])).url,
        })
    return HttpResponse(json.dumps(json_list), content_type='application/json')
Example #31
0
 def get_thumb(self,
               size=config['thumb_size'],
               crop=config['thumb_crop'],
               **kwargs):
     if bool(self.file):
         thumb = get_thumbnail(self.file, size, crop=crop)
         attrs = {
             'class': 'img-thumbnail hastip',
             'title': thumb.url,
             'src': thumb.url,
             'width': thumb.width,
             'height': thumb.height,
         }
         attrs.update(kwargs)
         attrs = format_html_join(' ', '{}="{}"',
                                  ((key, attrs[key]) for key in attrs))
         return format_html('<img {}>', attrs)
     return '--'
Example #32
0
 def content_with_img(self, size=None):
     import re
     if size is None:
         size = settings.POST_THUMBNAIL_SIZE
     format_re = '(<!\-\- ?img ?([0-9]+) ?\-\->)'
     content = self.content
     pat = re.compile(format_re)
     embed_tags = pat.findall(self.content)
     if not embed_tags:
         return content
     try:
         embed_imgs = PostImage.objects.filter(
             pk__in=[int(img[1]) for img in embed_tags])
     except:
         import sys
         print "Unexpected error:", sys.exc_info()[0]
         return content
     exsists_imgs = {}
     for exsists in embed_imgs:
         exsists_imgs[exsists.pk] = exsists
     for img in embed_tags:
         try:
             tag = img[0]
             pk = int(img[1])
             img = exsists_imgs[pk]
             thumb = get_thumbnail(img.img_file, size)
             img_tag = (
                 """<a href="%s" target="_blank" class="post-thumbnail">"""
                 """<img src="%s" alt="%s" width="%s" height="%s">"""
                 """</a>""") % (
                     img.img_file.url,
                     thumb.url,
                     self.title,
                     thumb.width,
                     thumb.height,
                 )
         except:
             content = content.replace(tag,
                                       '<!-- img error ' + str(pk) + ' -->')
             import sys
             print "Unexpected error:", sys.exc_info()[0]
         else:
             content = content.replace(tag, img_tag)
     return content
Example #33
0
def get_bookmarked_movies(user_id, page):
    """
    Returns the bookmarks of the user for the bookmarks modal.
        user_id: primary key of the user (integer)
        page: page number (integer)
    """
    friends = get_friends(user_id)
    my_bookmarks = get_bookmarked_items(user_id)
    last_checked = (cacheAPI._get_bookmarks_last_checked(user_id)
                    or dt.datetime.min)

    recent_bookmarks = Movie.objects.filter(
        item__pk__in=my_bookmarks,
        item__bookmark__created_at__gte=last_checked,
        item__bookmark__user__in=friends)
    print recent_bookmarks
    print last_checked
    recent_item_ids = recent_bookmarks.values_list('item', flat=True)
    not_recent = list(set(my_bookmarks) - set(recent_item_ids))
    other_bookmarks = Movie.objects.filter(item__pk__in=not_recent) \
                                   .values('item_id', 'url', 'image')
    annotated = recent_bookmarks.values('item_id', 'url', 'image') \
            .annotate(new_bookmarks=Count('item__bookmark__user')) \
            .order_by('-new_bookmarks')
    combined = QuerySetChain(annotated, other_bookmarks)
    paginator = Paginator(combined, 12)

    previous_page, next_page = "", ""
    current_page = paginator.page(page)
    if current_page.has_previous():
        previous_page = current_page.previous_page_number()
    if current_page.has_next():
        next_page = current_page.next_page_number()

    response = [{
        'item_id': movie['item_id'],
        'url': movie['url'],
        'image_url': get_thumbnail(movie['image'], 'x285').url,
        'new_bookmarks': movie.get('new_bookmarks', 0),
        'previous': previous_page,
        'next': next_page
    } for movie in paginator.page(page)]

    return simplejson.dumps(response)
Example #34
0
 def line_format(mat):
     """
     Format: https://www.webtoffee.com/setting-up-product-import-export-plugin-for-woocommerce/
     :param Material mat:
     :return:
     """
     return OrderedDict(
         {
             "sku": mat.sku,
             "tax:product_type": "simple",
             "post_title": mat.name,
             "post_name": mat.name,
             "post_status": "publish" if mat.lendable else "private",
             "tax:product_visibility": "visible"
             if mat.lendable
             else "exclude-from-catalog|exclude-from-search",
             "stock": mat.stock_value,  # Stock
             "post_content": post_content(mat),
             "regular_price": mat.rate_class.rate.amount
             if mat.rate_class is not None
             else 0.00,
             "tax:product_cat": "|".join(  # join multiple categories
                 [
                     " > ".join(  # add hierarchical categories
                         [
                             str(cat)
                             for cat in category.get_ancestors(include_self=True)
                         ]
                     )
                     for category in mat.categories.all()
                 ]
             ),
             # @see https://www.webtoffee.com/woocommerce-import-products-with-images/
             "images": "|".join(
                 [
                     request.build_absolute_uri(
                         get_thumbnail(img.image, "1280").url
                     )  # At max return HD image (1280x720)
                     for img in mat.images.all()
                 ]
             ),
             "meta:stock_unit": mat.stock_unit,
         }
     )
Example #35
0
def get_parks(request):
    """ Returns parks as JSON based search parameters
    """

    querydict = request.GET
    kwargs = querydict.dict()
    user = request.user

    try:
        parks = Park.objects.filter(
            **kwargs).select_related('parkowner').prefetch_related('images')
        parks_json = dict()
        for p in parks:
            # embed all images
            images = []
            for i in p.images.all():
                try:
                    tn = get_thumbnail(i.image,
                                       '250x250',
                                       crop='center',
                                       quality=80)
                    image = dict(
                        src=tn.url,
                        caption=strip_tags(i.caption),
                    )
                    images.append(image)
                except IOError, e:
                    logger.error(e)

            parks_json[p.pk] = dict(
                url=p.get_absolute_url(),
                name=p.name,
                description=p.description,
                images=images,
                access=p.get_access_display(),
                address=p.address,
                owner=p.parkowner.name,
            )

            if user.has_perm('parks.change_park'):
                parks_json[p.pk]['change_url'] = urlresolvers.reverse(
                    'admin:parks_park_change', args=(p.id, ))
        return HttpResponse(json.dumps(parks_json),
                            mimetype='application/json')
Example #36
0
    def retrieve(self, request, pk=None):
        profile_id = request.GET.get('user_id', None)
        social_backend = request.GET.get('social_backend', None)
        social_code = request.GET.get('social_code', None)
        if profile_id:
            user = get_object_or_404(self.queryset, pk=int(profile_id))
        elif request.user.id:
            user = get_object_or_404(self.queryset, pk=request.user.id)
        elif social_backend and social_code:
            code = Code.get_code(social_code)
            account = KnackUser.objects.get(email=code.email)
            backend_class = self.SOCIAL_BACKENDS.get(social_backend)
            account.backend = '{0}.{1}'.format(backend_class.__module__,
                                               backend_class.__name__)

            token, created = Token.objects.get_or_create(user=account)
            avatar = get_thumbnail(account.picture, '40x40', crop='center')
            avatar_url = None
            if avatar:
                avatar_url = avatar.url
            return Response({
                'token': token.key,
                'id': account.id,
                'full_name': account.full_name,
                'college': account.college,
                'age': account.age,
                'picture': account.picture
            })
        else:
            return Response({'detail': 'User not found.'},
                            status=status.HTTP_400_BAD_REQUEST)

        if not hasattr(user, 'sociallink'):
            sociallink = SocialLink(user=user,
                                    twitter='',
                                    facebook='',
                                    instagram='',
                                    googleplus='')
            sociallink.save()
            user.sociallink = sociallink

        serializer = ProfileSerializer(user)
        return Response(serializer.data)
Example #37
0
def test_sorlthumbnail_replace(settings, picture):
    # https://github.com/mariocesar/sorl-thumbnail
    models = pytest.importorskip("django_cleanup.testapp.models.integration")
    ProductIntegration = models.ProductIntegration
    sorl_delete = models.sorl_delete
    cleanup_pre_delete.connect(sorl_delete)
    from sorl.thumbnail import get_thumbnail
    product = ProductIntegration.objects.create(sorl_image=picture['filename'])
    assert os.path.exists(picture['path'])
    im = get_thumbnail(
        product.sorl_image, '100x100', crop='center', quality=50)
    thumbnail_path = os.path.join(settings.MEDIA_ROOT, im.name)
    assert os.path.exists(thumbnail_path)
    product.sorl_image = 'new.png'
    with transaction.atomic(get_using(product)):
        product.save()
    assert not os.path.exists(picture['path'])
    assert not os.path.exists(thumbnail_path)
    cleanup_pre_delete.disconnect(sorl_delete)
Example #38
0
def upload_image_profile(request):
    if request.method == 'POST':
        if request.FILES.get('image'):
            request.user.profile.image = request.FILES.get('image')
            request.user.profile.save()

            return Response(
                {
                    'status':
                    'Ok request',
                    'message':
                    'Set data ok.',
                    'image_url':
                    get_thumbnail(request.user.profile.image,
                                  '400x400',
                                  crop='center',
                                  quality=99).url
                },
                status=status.HTTP_200_OK)
def product_thumbnail(request, id_product):
    """
    물품 상세페이지의 썸네일을 리스트로 주는 API

    ---
    # 내용
        - s : 사진픽셀 크기 ex)500x500
        - q : 사진품질 0~100 ex)82 당근마켓 기본값
    """
    if request.method == 'GET':
        s = request.GET['s']
        q = int(request.GET['q'])
        Data = ProductImage.objects.filter(id_product=id_product)
        imageList = []
        for i in range(Data.count()):
            imageList.append(
                request.META['HTTP_HOST'] + '/image' +
                get_thumbnail(Data[i].image, s, crop='center', quality=q).url)
        return Response(imageList, status=status.HTTP_200_OK)
 def test_person_photo_shown(self):
     self.create_memberships(self.ballot, self.parties)
     person = self.ballot.membership_set.first().person
     im = PersonImage.objects.update_or_create_from_file(
         EXAMPLE_IMAGE_FILENAME,
         "images/imported.jpg",
         person=person,
         defaults={
             "md5sum": "md5sum",
             "copyright": "example-license",
             "uploading_user": self.user,
             "user_notes": "Here's an image...",
             "is_primary": True,
             "source": "Found on the candidate's Flickr feed",
         },
     )
     expected_url = get_thumbnail(im.image, "x64").url
     response = self.app.get(self.ballot.get_absolute_url())
     response.mustcontain(expected_url)
Example #41
0
 def render(self, name, value, attrs=None):
     output = []
     if value and hasattr(value, "path"):
         if value.path.startswith(settings.MEDIA_ROOT):
             image = value.path[len(settings.MEDIA_ROOT):]
         else:
             image = value.path
         # Generate 120px wide thumbnail for the admin interface
         # TODO: replace manual thumbnail generation with a template tag
         thumb = get_thumbnail(image,
                               '120',
                               quality=config_value('THUMBNAIL',
                                                    'IMAGE_QUALITY'))
         output.append('<img src="%s" /><br/>%s<br/> %s ' % \
             (thumb.url, value.url, _('Change:')))
     output.append(
         super(AdminImageWithThumbnailWidget,
               self).render(name, value, attrs))
     return mark_safe(u''.join(output))
Example #42
0
 def get_image(self, obj):
     """Generates a thumbnail of the image."""
     image = getattr(obj, self.image_field)
     if not image:
         return ''
     try:
         thumbnail = get_thumbnail(image.file, '100x66', quality=99)
         return mark_safe(
             '<img src="{}" width="{}" height="{}" alt=""/>'.format(
                 thumbnail.url,
                 thumbnail.width,
                 thumbnail.height,
             ))
     except:  # pylint:disable=bare-except
         # ^^ We allow bare exceptions above because of the vast number
         # of exceptions that can occur; it could be IOError for bad
         # permissions, ValueError or ZeroDivisionError with invalid files,
         # etc.
         return '(corrupt image?)'
Example #43
0
 def test_person_photo_shown(self):
     person = Person.objects.get(id=2009)
     im = PersonImage.objects.update_or_create_from_file(
         EXAMPLE_IMAGE_FILENAME,
         "images/imported.jpg",
         person=person,
         defaults={
             "md5sum": "md5sum",
             "copyright": "example-license",
             "uploading_user": self.user,
             "user_notes": "Here's an image...",
             "is_primary": True,
             "source": "Found on the candidate's Flickr feed",
         },
     )
     expected_url = get_thumbnail(im.image, "x64").url
     response = self.app.get(
         "/election/2015/post/65808/dulwich-and-west-norwood")
     response.mustcontain(expected_url)
Example #44
0
 def get_html(self):
     html_class = 'annonse ' + self.extra_classes
     img_template = ('<a href="{this.link}" '
                     'alt="{this.alt_text}" >'
                     '<img src="{src}">'
                     '</a>')
     div_template = ('<div class="{html_class}">{content}</div>')
     if self.ad_type == self.CODE_AD:
         content = self.html_source
     elif self.ad_type == self.IMAGE_AD:
         thumb = get_thumbnail(self.imagefile,
                               '%sx%s' % (self.width, self.height))
         content = img_template.format(this=self, src=thumb.url)
     elif self.ad_type == self.DUMMY_AD:
         content = str(self)
     html_source = div_template.format(html_class=html_class,
                                       this=self,
                                       content=content)
     return mark_safe(html_source)
Example #45
0
def get_user_boxes(my_id, user_ids, page):
    """
    Returns a list of user details required for following and follower
    boxes.
        my_id: user id of the current user (integer)
        user_ids: list of user ids (integers)
        page: page for the paginator (integer)
    """
    my_following = get_following(my_id)
    profiles = UserProfile.objects.select_related('user') \
                                  .filter(pk__in=user_ids)
    paginator = Paginator(profiles, 12)
    current_page_user_ids = [profile.pk for profile in paginator.page(page)]
    are_following = list(set(my_following) & set(current_page_user_ids))

    previous_page, next_page = "", ""
    current_page = paginator.page(page)
    if current_page.has_previous():
        previous_page = current_page.previous_page_number()
    if current_page.has_next():
        next_page = current_page.next_page_number()

    response = [{
        'id':
        profile.pk,
        'full_name':
        profile.user.get_full_name(),
        'about_me':
        escape(profile.about_me),
        'image_url':
        get_thumbnail(profile.avatar, '100x100', crop='center').url,
        'url':
        reverse('user-profile', args=[profile.pk]),
        'is_following':
        True if profile.pk in are_following else False,
        'previous':
        previous_page,
        'next':
        next_page
    } for profile in paginator.page(page)]

    return simplejson.dumps(response)
Example #46
0
    def test_image_from_hash(self):
        storage = S3Boto3Storage(bucket=self.bucket)
        s3_file = S3Boto3StorageFile(name=self.s3_image_key,
                                     mode='r',
                                     storage=storage)

        # Mock model Image field
        # S3Boto3StorageFile store storage information in ._storage wich is not checked by
        # ImageFile during storage identification
        s3_file.storage = storage

        image_s3 = ImageFile(s3_file)

        # Test local part
        options = {}
        thumbnail = get_thumbnail(s3_file, self.geometry_string, **options)
        print('Generated thumbnail url: {}'.format(thumbnail.url))
        print('Thumbnail cache key: {}'.format(thumbnail.name))

        # Now, test shrinkmeister server (should be up and running)
        resp = requests.get(thumbnail.url)
        image = Image(blob=resp.content)
        self.assertEqual(image.width, 50)
        self.assertEqual(image.height, 38)

        thumbnail_from_cache = self.cache.get(thumbnail.name)
        self.assertNotEqual(thumbnail_from_cache,
                            None,
                            msg="No image in cache detected :(")
        image = Image(blob=resp.content)
        self.assertEqual(image.width, 50)
        self.assertEqual(image.height, 38)

        resp = requests.get(thumbnail_from_cache.url)

        url, ext = thumbnail_from_cache.url.rsplit('.', 1)
        x2_url = '{}@2x.{}'.format(url, ext)
        print('x2 url {}'.format(x2_url))
        resp = requests.get(x2_url)
        image = Image(blob=resp.content)
        self.assertEqual(image.width, 100)
        self.assertEqual(image.height, 75)
Example #47
0
def link_status(request, guid):
    """
    A service that provides the state of a perma.
    TODO: this should obviously become part of an API, we probably also want to evaluate some long polling
    approach?
    """
    target_link = get_object_or_404(Link, guid=guid)
    target_asset = get_object_or_404(Asset, link=target_link)


    # Create a thumbnail for new archives.
    # this logic should be temporary. When we refactor the asset/link model
    # relationship we should wrap this thumbnailing work into a func in utils
    # or maybe even a standaole service
    thumbnail_url = ''
    if target_asset.image_capture != 'pending' and target_asset.pdf_capture != 'pending':
        if target_asset.image_capture:
            capture_name = target_asset.image_capture
        else:
            capture_name = target_asset.pdf_capture

        try:
            image_path = os.path.join(settings.MEDIA_ROOT, target_asset.base_storage_path, capture_name)
            thumbnail = get_thumbnail(image_path, '456')
            thumbnail_url = direct_media_url(thumbnail.url)
        except IOError:
            logger.info("Thumnail creation failed. Unable to find capture image")

    
    response_object = {"path": target_asset.base_storage_path, "text_capture": target_asset.text_capture,
            "source_capture": target_asset.warc_capture, "image_capture": target_asset.image_capture,
            "thumbnail": thumbnail_url,
            "pdf_capture": target_asset.pdf_capture,
            "vested": target_link.vested,
            "dark_archived": target_link.dark_archived,
            "submitted_title":target_link.submitted_title}

    data = json.dumps(response_object)
    if 'callback' in request.REQUEST:
        # jsonp response
        data = '%s(%s);' % (request.REQUEST['callback'], data)
    return HttpResponse(data, content_type="application/json", status=200)
Example #48
0
    def convert(self, value):
        if value is None or not hasattr(value, 'url'):
            return None

        try:
            options = self.thumb_options.copy()
            geometry = options.pop('geometry', '200x200')
            thumbnail = get_thumbnail(value, geometry, **options)

            dict_thumbnail = dict(url=thumbnail.url,
                                  width=thumbnail.width,
                                  height=thumbnail.height,
                                  style={
                                      True: 'portrait',
                                      False: 'landscape'
                                  }[thumbnail.is_portrait()])
        except:
            dict_thumbnail = None

        return dict_thumbnail
Example #49
0
def show_image(request, repository, mucua, uuid, width, height, format_type):
    
    try:
        media = Media.objects.get(uuid=uuid)
    except Media.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    
    if (width != '') & (height == '0'):
        size = str(width)
    elif (width == '0') & (height != ''):
        size = 'x' + str(height)
    elif (width != '') & (height != ''):
        size = str(width) + 'x' + str(height)
    
    image = get_thumbnail(media.media_file, size,
                          crop='center', quality=99)
    
    return Response({'url': image.url,
                     'height': image.height,
                     'width': image.width})
Example #50
0
def api_album_thumb(request, album_id, thumb_size=250):
    a = get_object_or_404(Album, id=album_id)
    random_image = a.photos.order_by('?').first()
    if not random_image:
        for sa in a.subalbums.exclude(atype=Album.AUTO):
            random_image = sa.photos.order_by('?').first()
            if random_image:
                break
    size_str = str(thumb_size)
    thumb_str = size_str + 'x' + size_str
    try:
        im = get_thumbnail(random_image.image, thumb_str, upscale=False)
    except AttributeError:
        im = urllib2.urlopen(
            'http://rlv.zcache.com/doge_sticker-raf4b2dbd11ec4a7992e8bf94601ace75_v9wth_8byvr_512.jpg'
        )
    content = im.read()
    response = HttpResponse(content, content_type='image/jpg')

    return response
Example #51
0
    def render_to_response(self, context, **response_kwargs):
        """
        Returns a JSON response, transforming 'context' to make the payload.
        """

        pages = {
            "page":
            context['object_list'].number,
            "data": [{
                "id":
                player.id,
                "name":
                player.name,
                "photo":
                get_thumbnail(player.photo, '40x40', crop='center').url
            } for player in context['object_list']]
        }

        response_kwargs['content_type'] = 'application/json'
        return HttpResponse(json.dumps(pages), **response_kwargs)
Example #52
0
def thumbnail(imagefile, geometry, **options):
    if not options.get('format'):
        # then let's try to do it by the file name
        filename = imagefile
        if hasattr(imagefile, 'name'):
            # it's an ImageFile object
            filename = imagefile.name
        if filename.lower().endswith('.png'):
            options['format'] = 'PNG'
        else:
            options['format'] = 'JPEG'
    try:
        return get_thumbnail(imagefile, geometry, **options)
    except IntegrityError:
        # annoyingly, this happens sometimes because kvstore in sorl
        # doesn't check before writing properly
        # see https://bugzilla.mozilla.org/show_bug.cgi?id=817765
        # try again
        time.sleep(1)
        return thumbnail(imagefile, geometry, **options)
Example #53
0
def ff_sample(request):
    ffs = [
        x for x in Firefighter.objects.all()
        if x.is_active() and x.profile_picture and x.number
    ][:24]
    data = []
    for ff in ffs:
        im = get_thumbnail(ff.profile_picture,
                           '70x70',
                           crop='center',
                           format='PNG')
        data.append({
            "name": str(ff),
            "im": {
                "url": im.url,
                "width": im.width,
                "height": im.height
            }
        })
    return HttpResponse(json.dumps(data))
Example #54
0
    def post(self, request, *args, **kwargs):
        if request.FILES:
            new_img = request.FILES[u'files[]']
            if new_img.size > settings.SALE_IMG_UPLOAD_MAX_SIZE:
                content = {'status': 'max_limit_error'}
                return HttpResponse(json.dumps(content),
                                    mimetype='application/json')

            new_media = NotifTemplateImage(image=request.FILES[u'files[]'])
            new_media.save()
            thumb = get_thumbnail(new_media.image, '40x43')
            to_ret = {
                'status': 'ok',
                'pk': new_media.pk,
                'url': new_media.image.url,
                'thumb_url': thumb.url,
            }
            return HttpResponse(json.dumps(to_ret),
                                mimetype="application/json")
        raise HttpResponseBadRequest(_("Please upload a picture."))
Example #55
0
    def admin_thumbnail(self, obj):
        """
        Build a tiny clickable thumb for image source
        """
        tag = ("""<a href="{source}" target="_blank">"""
               """<img src="{thumb}" alt="">"""
               """</a>""")

        try:
            return mark_safe(
                tag.format(source=obj.image.url,
                           thumb=get_thumbnail(obj.image,
                                               "80x80",
                                               crop="center").url))
        except IOError:
            logger = logging.getLogger("cmsplugin_blocks.admin.albumitem")
            logger.exception("IOError for image {}".format(obj.image))
            return "IOError"
        except ThumbnailError as ex:
            return "ThumbnailError, {}".format(ex.message)
Example #56
0
    def transform_image(self, imageurl, **options):
        width = options.get('width', None)
        height = options.get('height', None)
        quality = options.get('quality', 100)
        crop = options.get('crop', 'limit')

        if not width and not height:
            raise ValueError(
                'At least one of width and height must be specified')
        width = width or ''
        height = height or ''
        size = '{}x{}'.format(width, height)

        if crop == 'limit':
            upscale = False
            sorl_crop = None
        else:
            upscale = True
            sorl_crop = 'center'

        mimetype = mimetypes.guess_type(imageurl)[0]
        if mimetype == 'image/jpeg':
            imageformat = 'JPEG'
        elif mimetype == 'image/png':
            imageformat = 'PNG'
        elif mimetype == 'image/gif':
            imageformat = 'GIF'
        else:
            imageformat = 'JPEG'

        try:
            thumbnail = get_thumbnail(imageurl,
                                      size,
                                      upscale=upscale,
                                      quality=quality,
                                      crop=sorl_crop,
                                      format=imageformat)
            return thumbnail.url
        except Exception as e:
            logger.exception(e)
            return ''
Example #57
0
def sentences_list(request):
    import json
    if request.method == "POST" and request.is_ajax():
        #create new element
        json_data = simplejson.loads(request.raw_post_data)
        try:
            post_txt = json_data['text']
        except KeyError:
            HttpResponseServerError("Malformed data!")

        if post_txt:
            # protocollo:
            # http://www.areasx.com/files/articoli/8195/Protocollo%20MEDIA-LINK%201.1.pdf
            if is_polite(post_txt):
                LedString(sentence=post_txt,
                          coded_sentence="<ID00><FD>" + post_txt,
                          user=request.user.get_profile()).save()
            else:
                raise ValidationError('Ti perdono, ma non lo posso scrivere!')

        return HttpResponse(str(request.raw_post_data))
    else:
        qs = LedString.objects.all().order_by("-created_on")[:5]
        mlist = []
        for q in reversed(qs):
            im_url = ""
            if q.user.photo:
                im_url = get_thumbnail(q.user.photo,
                                       '50x50',
                                       crop='center',
                                       quality=99).url
            else:
                im_url = settings.STATIC_URL + "images/fusolab_unnamed_avatar.jpg"
            mlist.append({
                "id": q.id,
                "sender": q.user.user.username,
                "text": q.sentence,
                "image": im_url,
                "date": timesince.timesince(q.created_on)
            })
        return HttpResponse(json.dumps(mlist), content_type="application/json")
Example #58
0
    def to_representation(self, value):
        """
        Perform the actual serialization.
        Args:
            value: the image to transform
        Returns:
            a url pointing at a scaled and cached image
        """
        if not value:
            return None

        image = get_thumbnail(value, self.geometry_string, **self.options)

        try:
            request = self.context.get('request', None)
            return request.build_absolute_uri(image.url)
        except:
            try:
                return super(SorlImageField, self).to_representation(image.url)
            except AttributeError:  # NOQA
                return super(SorlImageField, self).to_native(image.url)  # NOQA
Example #59
0
def _get_mp_some_activity(request, offset):
    q = Update.objects.filter(feed__in=MemberSocialFeed.objects.all())
    some_query = q.select_related('feed__membersocialfeed')[offset:offset + 5]
    some_updates = []
    for upd in some_query:
        d = {}
        feed = upd.feed.membersocialfeed
        mp = feed.member
        d['time'] = upd.created_time
        d['text'] = upd.text
        d['html'] = upd.render_html()
        d['mp_name'] = mp.get_print_name()
        tn = get_thumbnail(mp.photo, '32x48')
        d['mp_portrait'] = tn.url
        d['mp_link'] = mp.get_absolute_url()
        d['mp_party'] = mp.party.abbreviation
        some_updates.append(d)
    some_html = render_to_string('parliament/_some_update_list.html',
                                 {'some_updates': some_updates},
                                 context=RequestContext(request))
    return {'offset': offset + 5, 'html': some_html}
Example #60
0
def post_thumbnail(request, stream, id, size='560x560'):
    post = get_object_or_404(
        Post,
        stream__part_of__slug=stream,
        stream__part_of__network__parent=request.network.parent,
        pk=id)

    try:
        img = post.media.image()
    except Media.DoesNotExist:
        raise Http404()

    media_url = getattr(settings, 'MEDIA_URL')
    img = get_thumbnail(img.content, size, crop='center', quality=99)
    url = img.url
    q = url.find('?')

    if q > 01:
        url = url[:q]

    return HttpResponseRedirect(url)