Pinax源代码分析14 - photos, photologue

本文深入剖析了Pinax项目的照片模块,重点介绍了其利用第三方应用photologue实现的照片管理功能。内容涵盖模型定义、URL配置、视图逻辑及模板使用等方面,并详细解释了photologue的核心特性,如图片尺寸调整、特效应用、水印添加等。

Pinax源代码分析14 photos, photologue

url

    (r'^photos/', include('photos.urls')),

Models

photos 利用了 第三方 app photologue

from photologue.models import *

photos.models.Image
继承了 photologue.models.ImageModel

class Image(ImageModel):
    ……

继承了ImageModel之后,Image会自动获得几个域,例如 image view_count。同时也会获得几个方法。


逻辑与模板

urlpatterns = patterns('',    
    #
全部图片
all photos or latest photos
    url(r'^$', 'photos.views.photos', name="photos"),
    #
图片详细信息
a photos details
    url(r'^details/(?P<id>/d+)/$', 'photos.views.details', name="photo_details"),
    #
上传图片
upload photos
    url(r'^upload/$', 'photos.views.upload', name="photo_upload"),
    #
当前用户的图片
your photos
    url(r'^yourphotos/$', 'photos.views.yourphotos', name='photos_yours'),
    #
指定用户的图片
a members photos
    url(r'^member/(?P<username>[/w]+)/$', 'photos.views.memberphotos', name='photos_member'),
    #
删除图片
destory photo
    url(r'^destroy/(/d+)/$', 'photos.views.destroy', name='photo_destroy'),
    #
编辑图片
edit photo
    url(r'^edit/(/d+)/$', 'photos.views.edit', name='photo_edit'),
)

views.details
除了显示图片的信息之外,用户还可以将图片添加到自己参加的小组或项目,同时也可以将图片从小组或者项目中删除。

为了使用projects关联photos,它需要定义如下的域:
class Project(models.Model):
    ……
    photos = generic.GenericRelation(Pool)
    ……


details.html
载入了photos app 自己定义的 photo_tags,不过没有使用。使用了第三方Django_flag定义的flagtags
{% extends "photos/base.html" %}

{% load photo_tags %}
{% load flagtags %}
        
        <div class="form-toggle">
            <p><span id="flag-toggle"><img src="{{MEDIA_URL}}pinax/images/silk/icons/flag_red.png" />{% trans "Flag as inappropriate" %}</span></p>
             <div id="flag-form" style="display: none;">
                {% flag photo request.user.id %}
             </div>
        </div>


photologue

项目地址:http://code.google.com/p/django-photologue/

wikihttp://code.google.com/p/django-photologue/w/list

 

photos.models.Image使用了photologueImageModel 

详细文档如下(摘自http://code.google.com/p/django-photologue/wiki/ImageModel ):

ImageModel  

它是一个抽象类,继承与该类的Django model会增加一些域和行为,以提供图像的改变大小功能、缓存、记录浏览次数、增强和特效、倒影、水印和旋转等等。

Fields

继承ImageModel 后会增加的域,这些域名将成为保留字,且不能被子类覆盖:

image

Type: ImageField

保存着指向原照片文件的路径。Stores the file path of the original image.

date_taken

Type: DateTimeField

拍摄日期,视图从EXIF 信息中摘取,失败则使用创建的时间。

view_count

Type: PositiveIntegerField

图像被浏览的次数。英文没看明白。

The number of times a PhotoSize with increment_count set to true has been requested for this image.

crop_from

Type: CharField

如果该图像需要被切割,那么从哪个方向切割。

The position that this image will be cropped from if required.

 

top

 

left

center

right

 

bottom

 

effect

Type: ForeignKey

给图像应用的PhotoEffect 特效。

Explicitly applies a specific PhotoEffect to this image. This setting will override any effect applied to the PhotoSize requested.

Commonly Used Methods

在下面的方法中,”SIZE”都应该被替换为PhotoSize的“name”。

For the following methods the text "SIZE" should be replaced with the "name" of the desired PhotoSize.

get_SIZE_photosize

返回指定名字的PhotoSize model。例如有一个名为thumbnail的PhotoSize

Returns the PhotoSize model with that name.

    >>> myphoto.get_thumbnail_photosize()
    <PhotoSize: thumbnail>

get_SIZE_size

返回指定名字的PhotoSize 的宽度和高度。如果文件不存在会生成文件并且将它缓存起来。感觉英文原文不对。

Returns a tuple containing the actual width and height of the image file on disk in pixels. The file will be generated and cached if not already available.

    >>> myphoto.get_thumbnail_size()
    (150, 75)

get_SIZE_url

返回指定名字的PhotoSize 的相对URL,如果文件不存在就创建并且缓存。

Returns a relative URL for the size specified. The file will be generated and cached if not already available.

    >>> myphoto.get_thumbnail_url()
    u'/media/photologue/photos/cache/myfile_thumbnail.jpg'

This is also the method you should use to insert sized photos into your templates:

    {% for photo in photos %}
        <img src="{{ photo.get_thumbnail_url }}">
    {% endfor %}

get_SIZE_filename

返回指定名字的PhotoSize 在硬盘上的路径。如果文件不存在也不会创建。

Returns the path to the file on disk. The file will NOT be generated if it does not already exists.

Admin Integration

但你继承了ImageModel 之后,你就可以使用admin缩略图的功能了。只要在ModelAdmin中的"list_display"属性中添加"admin_thumbnail"就可以了。

When you inherit from the ImageModel class you get Photologues admin thumbnails for free. Just add "admin_thumbnail" to the "list_display" property of your ModelAdmin class:

    from myapp.models import MyPhoto
   
    MyPhotoAdmin(admin.ModelAdmin):
        list_display = ['title', 'admin_thumbnail']
       
    admin.site.register(MyPhoto, MyPhotoAdmin)

Example

下面是一个简单但是能够工作的例子,一个继承了ImageModel的自定义Model。

Here is a (very) simple, but real world, example of a custom model that inherits from the ImageModel abstract class.

    from django.contrib.auth.models import User
    from photologue.models import ImageModel
   
    class UserPortrait(ImageModel):
        user = models.OneToOneField(User, primary_key=True)        

下面我们可以在shell或者admin界面创建一个 PhotoSize:

Now we can create a new PhotoSize through the shell or admin interface:

    >>> from photologue.models import PhotoSize
    >>> PhotoSize.objects.create(name='avatar', width=60, height=60, crop=True)

剩下的工作就是在模板中添加新的用户头像

All that's left is to add our new user portraits in a template

    <div id="user_info">
        <h1>{{ user.get_full_name }}</h1>
        <img id="user_avatar" src="{{ user.userportrait.get_avatar_url }}">
    </div>

 

PhotoSize  

PhotoSize model 可以被看做是一些列的参数,Photologue利用它们用来自动处理图片和改变图片大小。这些参数包括输出大小,压缩质量,特效和水印。定义PhotoSize的数量没有限制,由于Photologue只在被显示告知的时候才会处理你的图片,所以你不需要担心硬盘空间的浪费。

The PhotoSize model can be viewed as a named set of parameters that Photologue uses to automatically resize and process your images. These paramters include output dimensions, compression quality, effects and watermarks. There is no limit to the number of PhotoSize models you can define and because Photologue only process your images when explicitly told to, you don't have to worry about your disk space being wasted.

How Photologue Resize Your Images

可以指定最大的宽度、高度或者同时指定两者。也可以让Photologue将图片切割到一个精确的大小。

Photo sizes are very flexible in the way your images are resized. You can resize to a maximum width, height or both. You can also have Photologue crop your images to an exact set of dimensions.

Fit To A Box

你可以让Photologue将你的图片合适地放到一个盒子里,只要同时定义给宽度和高度定义非零值就可以了。如果你定义了一个500 * 500 的PhotoSize,偏高的图片会被等比例改变大小到高度为500;同样,偏宽的图片会等比例改变大小到宽度为500。

You can tell Photologue to resize you images to fit within a "box" by defining (non-zero value) both a width and height. If you define a PhotoSize that is 500 wide and 500 tall (no crop), portrait oriented images (taller than wide) will be resized proportionately to 500 pixels tall and landscape oriented images (wider than tall) will be resized to 500 pixels wide.

Fit To One Dimension

如果你只给PhotoSize定义了一个边的大小,另外一个边位0或者为空,那么图片将会按照定义的边等比例缩小。

If you only define ONE dimension in a PhotoSize, either width or height, and leave the other set to zero your photos will be resized proportionally to the one defined dimension regardless of the size of the image. If you define a PhotoSize that is 700 wide (no crop) and 0 high. An image that is 1800 pixels tall by 1400 pixels wide will be resized to 900 pixels tall by 700 pixels wide. An image that is 400 pixels tall by 1400 pixels wide will be resized to 200 pixels tall by 700 pixels wide.

No Resize (r351)

如果你定义了一个高和宽都为0的PhotoSize,Photologue将不会改变图片的大小。注意,这个方法只是当你想要给一个图片应用特效和水印而不想改变图片大小的时候使用。不要使用这个方法来取得原来的图片,因为在再次存储的时候会有一个小的质量损失。应该使用get_image_url()来取得原图片。

If you define a PhotoSize with both the height and width set to zero Photologue will apply all appropriate effects and watermarks but will not resize the image. Please note that this is provided only so for instances where you need to apply effects or watermarks to an image and do not want it resized. You should not use this as a way of getting the original image as there is a small loss of quality when the image is resaved. The method get_image_url() method will return the original uploaded image file.

Crop To Fit

选择了crop之后,PhotoSize的大小会精确地符合你的定义(注意,你必须同时指定宽和高),会根据crop_from属性的设置来切割不符合指定大小的部分。

By checking the "crop" check box for a PhotoSize your images will be resized to the exact dimensions you specify (note: you must specify both a width and height if "crop" is True), cropping any areas that do not fit as specified by that individual photo's "crop_from" property.

Properties

除了name之外,PhotoSize的其他属性都告诉PhotoLogue如何来处理你的图片。

Apart from it's "name", each of the properties in the PhotoSize model tell Photologue how to process your images.

name

PhotoSize的描述性的名字。该属性用来给Photo model提供一些列的特殊方法,以及一些其他的ImageModel 子类。PhotoSize 的 names 应该只包含字母,数字和下划线。

A descriptive name for this PhotoSize. The "name" property is used to provide special methods to the Photo model and other ImageModel subclasses. PhotoSize names should contain only letters, numbers and underscores. Examples: "thumbnail", "display", "small", "main_page_widget". This is not currently enforced at the model level but will cause problems when the system tries to add the method "get_my awesome size!!!!!111_url" to your photo model objects.

width & height

指定输出文件的宽度和高度。

Specifies the width and height of the output file in pixels. See above to learn how Photologue uses these values to resize your source images.

quality

输出文件的JPEG压缩质量。只对JPEG图像有效。

The JPEG compression quality of the output file. Only applies to JPEG images.

upscale

如果为False,Photologue会将你的源图片放大到满足给定的大小。如果crop为True,你的源图片会无视该属性被放大。

If False, Photologue will not enlarge your source images to fit the supplied dimensions. If crop is True your source images will be enlarged to fit regardless of this property.

crop

如果是True,你的图片会被切割到满足指定的宽度和高度。

If True your images will be cropped to fit the exact width and height supplied.

pre_cache

如果为True,你的图片在save和change的时候会按照该PhotoSize指定的要求,自动被改变大小并且预先缓存起来。为了节省硬盘空间,改属性仅仅在那些确定会非常常用的PhotoSize上设置。

If True, your images will automatically be resized and pre-cached as specified by this PhotoSize upon save or change. To conserve disk space, this should be set only for a PhotoSize you know you will want pre-generated for all images in your project.

increment_count

如果为True,该PhotoSize的url被请求的时候,会更新一个图片的view_count 属性。

If True, this PhotoSize will increment an images view_count property when it's URL is requested.

effect

指定要给PhotoSize添加的PhotoEffect。

Specifies a PhotoEffect to apply to images when processed.

watermark

指定要给PhotoSize添加的Watermark。

Specifies a Watermark to apply to images when processed.

PhotoEffect

图片特效允许你定义指定的特效,并且将它们应用到你的图片和PhotoSizes上。Photologue利用了PIL来提供下面的调整和滤镜:

Photo effects allow you to define specific effects and apply them to your photos and photo sizes. Photologue leverages the Python Imaging Library to provide the following adjustments and filters:

Adjustments

            Color

            Brightness

            Contrast

            Sharpness

Filters

            Blur

            Contour

            Detail

            Edge Enhance

            Edge Enhance More

            Emboss

            Find Edges

            Sharpen

            Smooth

            Smooth More

This list may change depending on the continued development of the Python Imaging Library.

Reflections

给图像添加倒影。你可以指定大小,强度(透明度)和背景色。

Photologue can also add reflections to your images. You specify the size, strength (opacity) and background color

 photologue_reflection

Rotation

旋转,变换方法属性允许你旋转和翻转你的图片。

The transpose_method property allows you to rotate and flip your processed images.

Admin Preview

Photologue会自动在Django admin 中生成示例图片,这样你就可以预览你定义的特效的(点击图片放大)。

Photologue automatically generates a sample image in the Django admin so that you can preview the effects you define (click image to enlarge).

photologue_admin_preview

Photo

Photologue Photo model ImageModel 抽象类的实现。如果和Gallery model 与所包含的模板一起工作,那么就提供了马上就可以使用的相册解决方案。

The Photologue Photo model is a default implementation of the ImageModel abstract class. If work with the Gallery model and included templates to provide an out-of-the-box photo gallery solution.

Methods

Commonly used public methods include:

get_previous_in_gallery

按照日期,返回相册中的上一张照片。

Returns the previous photo in a specific gallery by date.

应用:

    mygallery = Gallery.objects.get(title="My Gallery")
    myphoto.get_previous_in_gallery(mygallery)

参数:

gallery

一个相册对象A gallery object.

get_next_in_gallery

按照日期,返回一个相册中的下一张图片。

Returns the next photo in a specific gallery by date.

应用:

    mygallery = Gallery.objects.get(title="My Gallery")
    myphoto.get_next_in_gallery(mygallery)

参数:

gallery

一个相册对象.

public_galleries

返回一个 queryset ,包含了了所有的公开的,应用到该图片的相册。

Returns a queryset containing all "public" galleries this photo is assigned to.

Usage:

    myphoto.public_galleries()

 

Watermark  

一个上传的文件,根据定义覆盖在其它的图片上。

An uploaded image file to overlay images as defined by the PhotoSize.

Properties
image

要作为水印的图片。推荐使用alpha 透明的PNG图片。

The image to use as the watermark. An alpha transparent PNG is recommended.

style

Photologue应该如何应用到你的图片上。选项有centeredtiled

How Photologue should apply this watermark to your images. Choices are centered and tiled.

opacity

水印的透明度。

The opacity of the watermark overlay.

ManagementCommands  

Photologue ships with a few management commands to help manage your image cache

plcache

默认情况下,该命令将会预先缓存所有设置了 pre_cache为真的 PhotoSize

By default this command pre-caches all photo sizes with pre_cache=True.

    python manage.py plcache

你也可以指定一个PhotoSize的列表来强制预先缓存。

You can also specify a list of photo size names as an argument to force pre-caching.

    python manage.py plcache display, thumbnail

plcreatesize

该命令允许你以命令行的方式,交互地创建新的PhotoSize

This command allows you to generate new photosizes interactively using the command line interface.

    python manage.py plcreatesize my_new_size

plflush

该命令清除所有图片的cache

This command flushes or clears the cache for all images.

 

 

    python manage.py plflush

 

 

你也可以指定一个要flush的PhotoSize的。

You can also specify a list of photo size names to flush.

    python manage.py plflush display, thumbnail

plinit

该命令初始化Photologue的初始化规则,并且提示你创建一些默认的PhotoSize和特效。改命令不接受任何参数。

This command initiates the Photologue initialization routine and prompts you to create a number of default photo sizes and effects. This command takes no arguments.

    pythons manage.py plinit

Settings  

下面的设置可以再你的projectsettings文件中覆盖:

The following settings can be over-ridden in your project's settings file:

PHOTOLOGUE_DIR

Default: "photologue"

相对于MEDIA_ROOT的路径。Photologue使用这个文件夹来存储文件。如果你的MEDIA_ROOT 设置为"/home/justin/media",Photologue会将你的文件上传到"/home/justin/media/photologue"。

The relative path from your MEDIA_ROOT setting where Photologue will save image files. If your MEDIA_ROOT is set to "/home/justin/media", photologue will upload your images to "/home/justin/media/photologue".

PHOTOLOGUE_PATH

 

指定一个接受model实例和原来上传文件的"callable",返回相对于MEDIA_ROOT的相对路径,该路径将用来存储文件。

Specifies a "callable" that takes a model instance and the original uploaded filename and returns a relative path from your MEDIA_ROOT that the file will be saved. This function can be set directly.

    # myapp/utils.py:
    import os
    def get_image_path(instance, filename):
        return os.path.join('path', 'to', 'my', 'files', filename)

    # settings.py:
    from utils import get_image_path
   
    PHOTOLOGUE_PATH = get_image_path

你也可以给函数传递一个路径字符串

You can also pass a string path to the function.

# settings.py:
    PHOTOLOGUE_PATH = 'myapp.utils.get_image_path'

该设置会覆盖PHOTOLOGUE_DIR

This setting will override the PHOTOLOGUE_DIR setting if both are defined.

PHOTOLOGUE_MAXBLOCK

Default: 256 * 2 ** 10

设置ImageFile的MAXBLOCK。

Sets the ImageFile MAXBLOCK setting.

SAMPLE_IMAGE_PATH

Default: "%Photologue App Directory%/res/sample.jpg"

为Django admin中的PhotoEffect设置的样例文件的绝对地址。

The absolute path to the image file you wish to use as the sample image for Photo Effects in the Django admin. Image will not be resized by photologue.

GALLERY_SAMPLE_SIZE

Default: 5

在generic views 中显示多个相册时候显示的样例文件个数。

The number of sample images to display in the generic views when listing multiple galleries.

未翻译部分

相册

http://code.google.com/p/django-photologue/wiki/Gallery

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值