呈现不同大小的图像
django-image-renderer的Python项目详细描述
django图像渲染器是一个应用程序,可以帮助您在许多 大小(格式副本)。这对生成图像非常有用 不同屏幕分辨率的大小(特别是在目标定位时 手机)。
功能
- 使用Pillow调整大小 图像
- 使用django的default_storage让您玩任何东西 您需要的存储后端
- 已上载使用uuid命名的图像文件
- 磁盘上缓存的格式副本
- 调整大小以保持原始纵横比
- 根据需要裁剪
- 管理站点的简单小部件
快速启动
安装应用程序。
pip install django-image-renderer
将“渲染器”添加到已安装的应用程序设置中,如下所示:
settings.py
INSTALLED_APPS=(# your apps'renderer',)
在项目中包含呈现器url配置urls.py类似 这个:
urls.py
url(r'^renderer/',include('renderer.urls',namespace='renderer')),
运行python manage.py migrate创建渲染器模型。
启动开发服务器并访问http://localhost:8000/admin/ 创建主映像(需要启用管理应用程序)。
要求
- Python(2.7、3.4、3.5)
- Django(1.7、1.8、1.9)
用法
应用程序中只有一个模型:masterimage。使用masterimage 您可以要求提供格式副本。
m=MasterImage.objects.first()# get the master file's URLm.get_master_url()# orm.get_rendition_url(0,0)# cache and return URL of a renditions that as 200 pixels width# and height computed according to master's aspect ratiourl=m.get_rendition_url(200,0)# cache and return URL of a renditions that as 50 pixels height# and width computed according to master's aspect ratiourl=m.get_rendition_url(0,50)
如果你要求的尺寸不符合主人的长宽比,你会 接收中心裁剪图像。
您还可以在模板中要求格式副本。
models.py
defindex(request):m=MasterImage.objects.first()returnrender(request,'demo/index.html',{'master':m,})
index.html
{%loadrenderer%} ... {%renditionmaster4242%} ... {%rendition_url4242%} ...
这将呈现为:
<imgsrc="/media/img/0fb34de8-9d83-456a-828b-72ab21f8ebab_42x42.png"width="42"height="42"alt=""> ... /media/img/0fb34de8-9d83-456a-828b-72ab21f8ebab_42x42.png ...
在模型中使用masterimage时,可能需要一个小部件 提供图像预览。为了方便起见,提供了一种混音。
models.py
fromdjango.dbimportmodelsclassDemoModel(models.Model):master=models.ForeignKey('renderer.MasterImage')
admin.py
fromdemo.modelsimportDemoModelfromdjango.contribimportadminfromrenderer.widgetsimportMasterImageAdminMixin@admin.register(DemoModel)classDemoModelAdmin(MasterImageAdminMixin,admin.ModelAdmin):fields=('master',)
示例项目
示例项目在 sample 文件夹。像往常一样测试django项目:
virtualenv --no-site-packages venv
source venv/bin/activate
pip install -r requirements.txt
python sample/manage.py migrate
python sample/manage.py createsuperuser
python sample/manage.py runserver