- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
在我的一个 django 项目中,我使用了 django 水印,它在我的本地服务器上绝对工作正常。但是在我将它部署到 Linux 服务器后,我遇到了一个类似这样的错误...
'watermark' is not a valid tag library: ImportError raised loading watermarker.templatetags.watermark: No module named Image
我已经安装了所有的依赖项,在遇到这个错误后,我认为它是由于 Pillow 而发生的,所以这就是为什么我卸载了 Pillow 并在我的虚拟环境中重新安装它。但我仍然面临这个错误。
这是我的项目目录...
medicalArt--------
photo---
views.py
models.py
__init__.py
urls.py
admin.py
home----
views.py
models.py
__init__.py
templates----
home-----
index.html
photo----
showphoto.html
watermark----
templatetags---
__init__.py
watermark.py
admin.py
models.py
__init__.py
utils.py
这是我项目的完整目录。home/index.html 中出现错误,它是从 home 应用程序的 View 呈现的。您可以在我的项目目录中找到 home 应用程序上面给出了home应用的views.py如下....
# Create your views here.
from django.shortcuts import render_to_response
from django.template import RequestContext
from photo.models import Photo
def home(request):
latest_images = Photo.objects.order_by('-uploaded_time')[:20]
ctx = {'images':latest_images}
context = RequestContext(request)
return render_to_response('home/index.html',ctx, context)
home/index.html 是..
{% extends 'userena/base_userena.html' %}
{% load watermark %}
{%block content%}
<!-- carousel -->
<div class="container" style="margin-top:50px">
<div class="row">
<h1>Medical Art</h1>
</div>
<!-- PORTFOLIO SECTION -->
<div id="portfolio">
<ul class="grid effect-2" id="grid">
{% for image in images%}
<li><img src={{image.photo.url|watermark:"Medical Art,tile=1,opacity=15"}}></li>
{%endfor%}
</ul>
</div><!-- portfolio -->
<br>
</br>
<!--About -->
{%endblock%}
这是watermark.py
from datetime import datetime
from hashlib import sha1
import Image
import errno
import logging
import os
import traceback
from django.utils import timezone
from django.conf import settings
from django import template
from watermarker import utils
from watermarker.models import Watermark
register = template.Library()
# determine the quality of the image after the watermark is applied
QUALITY = getattr(settings, 'WATERMARKING_QUALITY', 85)
OBSCURE = getattr(settings, 'WATERMARK_OBSCURE_ORIGINAL', True)
RANDOM_POS_ONCE = getattr(settings, 'WATERMARK_RANDOM_POSITION_ONCE', True)
log = logging.getLogger('watermarker')
class Watermarker(object):
def __call__(self, url, name, position=None, opacity=0.5, tile=False,
scale=1.0, greyscale=False, rotation=0, obscure=OBSCURE,
quality=QUALITY, random_position_once=RANDOM_POS_ONCE):
"""
Creates a watermarked copy of an image.
* ``name``: This is the name of the Watermark object that you wish to
apply to the image.
* ``position``: There are several options.
* ``R``: random placement, which is the default behavior.
* ``C``: center the watermark
* ``XxY`` where ``X`` is either a specific pixel position on the
x-axis or a percentage of the total width of the target image and
``Y`` is a specific pixel position on the y-axis of the image or
a percentage of the total height of the target image. These
values represent the location of the top and left edges of the
watermark. If either ``X`` or ``Y`` is a percentage, you must
use a percent sign. This is not used if either one of the
``tiled`` or ``scale`` parameters are true.
Examples:
* ``50%x50%``: positions the watermark at the center of the
image.
* ``50%x100``: positions the watermark at the midpoint of the
total width of the image and 100 pixels from the top of the
image
* ``100x50%``: positions the watermark at the midpoint of the
total height of the image and 100 pixels from the left edge
of the image
* ``100x100``: positions the top-left corner of the watermark
at 100 pixels from the top of the image and 100 pixels from
the left edge of the image.
* ``br``, ``bl``, ``tr``, ``tl`` where ``b`` means "bottom", ``t``
means "top", ``l`` means "left", and ``r`` means "right". This
will position the watermark at the extreme edge of the original
image with just enough room for the watermark to "fully show".
This assumes the watermark is not as big as the original image.
* ``opacity``: an integer from 0 to 100. This value represents the
transparency level of the watermark when it is applied. A value of
100 means the watermark is completely opaque while a value of 0 means
the watermark will be invisible.
* ``tile``: ``True`` or ``False`` to specify whether or not the
watermark shall be tiled across the entire image.
* ``scale``: a floating-point number above 0 to specify the scaling for
the watermark. If you want the watermark to be scaled to its maximum
without falling off the edge of the target image, use ``F``. By
default, scale is set to ``1.0``, or 1:1 scaling, meaning the
watermark will be placed on the target image at its original size.
* ``greyscale``: ``True`` or ``False`` to specify whether or not the
watermark should be converted to a greyscale image before applying it
to the target image. Default is ``False``.
* ``rotation``: 0 to 359 to specify the number of degrees to rotate the
watermark before applying it to the target image. Alternatively, you
may set ``rotation=R`` for a random rotation value.
* ``obscure``: set to ``False`` if you wish to expose the original
image's filename. Defaults to ``True``.
* ``quality``: the quality of the resulting watermarked image. Default
is 85.
"""
# look for the specified watermark by name. If it's not there, go no
# further
try:
watermark = Watermark.objects.get(name=name, is_active=True)
except Watermark.DoesNotExist:
log.error('Watermark "%s" does not exist... Bailing out.' % name)
return url
# make sure URL is a string
url = str(url)
basedir = '%s/watermarked' % os.path.dirname(url)
base, ext = os.path.splitext(os.path.basename(url))
# open the target image file along with the watermark image
target_path = self.get_url_path(url)
target = Image.open(target_path)
mark = Image.open(watermark.image.path)
# determine the actual value that the parameters provided will render
random_position = bool(position is None or str(position).lower() == 'r')
scale = utils.determine_scale(scale, target, mark)
rotation = utils.determine_rotation(rotation, mark)
pos = utils.determine_position(position, target, mark)
# see if we need to create only one randomly positioned watermarked
# image
if not random_position or \
(not random_position_once and random_position):
log.debug('Generating random position for watermark each time')
position = pos
else:
log.debug('Random positioning watermark once')
params = {
'position': position,
'opacity': opacity,
'scale': scale,
'tile': tile,
'greyscale': greyscale,
'rotation': rotation,
'base': base,
'ext': ext,
'quality': quality,
'watermark': watermark.id,
'opacity_int': int(opacity * 100),
'left': pos[0],
'top': pos[1],
}
log.debug('Params: %s' % params)
wm_name = self.watermark_name(mark, **params)
wm_url = self.watermark_path(basedir, base, ext, wm_name, obscure)
wm_path = self.get_url_path(wm_url)
log.debug('Watermark name: %s; URL: %s; Path: %s' % (
wm_name, wm_url, wm_path
))
# see if the image already exists on the filesystem. If it does, use
# it.
if os.access(wm_path, os.R_OK):
# see if the Watermark object was modified since the file was
# created
modified = datetime.fromtimestamp(os.path.getmtime(wm_path))
# only return the old file if things appear to be the same
if timezone.make_aware(modified, timezone.get_default_timezone()) >= watermark.date_updated:
log.info('Watermark exists and has not changed. Bailing out.')
return wm_url
# make sure the position is in our params for the watermark
params['position'] = pos
self.create_watermark(target, mark, wm_path, **params)
# send back the URL to the new, watermarked image
return wm_url
def get_url_path(self, url, root=settings.MEDIA_ROOT,
url_root=settings.MEDIA_URL):
"""Makes a filesystem path from the specified URL"""
if url.startswith(url_root):
url = url[len(url_root):] # strip media root url
return os.path.normpath(os.path.join(root, url))
def watermark_name(self, mark, **kwargs):
"""Comes up with a good filename for the watermarked image"""
params = [
'%(base)s',
'wm',
'w%(watermark)i',
'o%(opacity_int)i',
'gs%(greyscale)i',
'r%(rotation)i',
'_p%(position)s',
]
scale = kwargs.get('scale', None)
if scale and scale != mark.size:
params.append('_s%i' % (float(kwargs['scale'][0]) / mark.size[0] * 100))
if kwargs.get('tile', None):
params.append('_tiled')
# make thumbnail filename
name = '%s%s' % ('_'.join(params), kwargs['ext'])
return name % kwargs
def watermark_path(self, basedir, base, ext, wm_name, obscure=True):
"""Determines an appropriate watermark path"""
hash = sha1(wm_name).hexdigest()
# figure out where the watermark would be saved on the filesystem
if obscure:
log.debug('Obscuring original image name: %s => %s' % (wm_name, hash))
new_file = os.path.join(basedir, hash + ext)
else:
log.debug('Not obscuring original image name.')
new_file = os.path.join(basedir, hash, base + ext)
# make sure the destination directory exists
try:
root = self.get_url_path(new_file)
os.makedirs(os.path.dirname(root))
except OSError, exc:
if exc.errno == errno.EEXIST:
# not to worry, directory exists
pass
else:
log.error('Error creating path: %s' % traceback.format_exc())
raise
else:
log.debug('Created directory: %s' % root)
return new_file
def create_watermark(self, target, mark, path, quality=QUALITY, **kwargs):
"""Create the watermarked image on the filesystem"""
im = utils.watermark(target, mark, **kwargs)
im.save(path, quality=quality)
return im
def watermark(url, args=''):
"""Returns the URL to a watermarked copy of the image specified."""
# initialize some variables
args = args.split(',')
name = args.pop(0)
opacity = 0.5
tile = False
scale = 1.0
greyscale = False
rotation = 0
position = None
obscure = OBSCURE
quality = QUALITY
random_position_once = RANDOM_POS_ONCE
# iterate over all parameters to see what we need to do
for arg in args:
key, value = arg.split('=')
key = key.strip()
value = value.strip()
if key == 'position':
position = value
elif key == 'opacity':
opacity = utils._percent(value)
elif key == 'tile':
tile = bool(int(value))
elif key == 'scale':
scale = value
elif key == 'greyscale':
greyscale = bool(int(value))
elif key == 'rotation':
rotation = value
elif key == 'obscure':
obscure = bool(int(value))
elif key == 'quality':
quality = int(value)
elif key == 'random_position_once':
random_position_once = bool(int(value))
mark = Watermarker()
return mark(url, name, position, opacity, tile, scale, greyscale,
rotation, obscure, quality, random_position_once)
register.filter(watermark)
最佳答案
在watermark.py
替换
import Image
与
from PIL import Image
您可能需要安装枕头
pip install Pillow
关于linux - 水印模板标签导入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23799779/
我正在尝试使用水印并使用复杂过滤器应用 Yadif,但我无法弄清楚如何使用以下语法应用 Yadif ffmpeg -i "source:" -i C:\logo.png -c:v libx264 -p
我正在使用 zubrags PHP 水印脚本(附在下面),它工作得很好,除非我尝试使用 PNG-24 作为我的水印。生成的图像有一个乱码、不透明的水印。我想知道是否有人可以帮助解释我需要在下面的脚本中
基本上,我想拍摄用户从照片库中选择的图像,然后应用水印,即右下角的一个三角形,上面有应用程序名称。我已经在 Photoshop 中使用透明层制作了第二张图像。 我尝试了一个函数,我不记得它的确切名称,
Closed. This question needs to be more focused。它当前不接受答案。 想改善这个问题吗?更新问题,使其仅关注editing this post的一个问题。
这个问题我已经发了很多次了,但还是找不到正确的答案。我的目标是加载 PDF(扫描的调查问卷页),用页码标记每个页面,并将每个页面保存在单独的 JPEG 文件中以供以后使用。除了未绘制 NSString
你好,我的代码有问题 $obj = new stdClass(); $obj->cat_id = !empty($_POST['cat_id']) ? $_POST['cat_id']
SO 上有很多类似的问题/答案,但似乎没有一个能解决我的问题。 我的目标是使用 Paperclip 为图像生成“动态水印”(用户头像覆盖在另一张图像上)。我遇到的问题是我无法获得模型的“user_id
我想在我的图片上添加水印,这是我用来截图的代码。有人可以教我如何在图像中添加水印吗?我想在图片的右上角有一个小 Logo 。 我正在尝试研究是否可以实现我在 Canvas 中保留的内容,以便在截取屏幕
我有以下命令: ffmpeg -ss 00:00:30 -i "$i" -i ../audio.mov -map 0:0 -map 1:0 -to 30 -vf "fade=in:0:24, fade
我正在尝试从一些图片以及现有的 mp3(复制)制作幻灯片。图片尺寸不同,但我希望视频输出为 16:9 纵横比和 3840x2160。我也想要水印。重要的是不要拉伸(stretch)图片。 我试过这个代
我已经可以给任何 PDF 加水印,里面的图像,一切正常,但现在我只需要在打印 PDF 时才显示水印......这可能吗?如何? 我当然需要以编程方式执行此操作。 最佳答案 对于 future 的读者,
有没有办法在整个网页上创建浅色透明水印?一个留在屏幕上,即使它滚动?我的想法是创建一个 .PNG 位图并使用带有样式表的 DIV 标签,该样式表将我的 PNG 设置为背景图像,并设置绝对位置。问题是,
是否可以屏蔽应用程序的屏幕截图(电源 + 菜单按钮)?如果没有,此屏幕截图是否有可能收到水印? 问候,克劳迪奥 最佳答案 创建屏幕截图是一种系统行为,您不能覆盖它。 重复 Notification o
所以我一直在寻找如何为图像添加带有 colorBox 的水印,我在谷歌的第一个结果中找到了一个较旧的 colorBox 组,下一个答案是: Jack Moore 10/3/09 Ok, this sh
我有以下 CSS, #duplicateCopy { -webkit-transform:rotate(-20deg); -moz-transform:rotate(-20deg);
我有一个 pdf在它的背景上有水印。当开始扫描以在背景中突出显示带有水印或注释的任何单词时,它会被选中,因为它首先在触摸区域中找到。 我正在使用 CGPDFScanner 扫描文本。 我的问题是如何检
我正在寻找一种在选定字段上放置水印的方法。 那是行不通的-> [select* c_type class:ic watermark "choose type" "a" "b" "c"] 为了放置验证失
我正在尝试向视频添加各种 Gifs/水印,但我无法让它正常工作。 我们假设视频时长为 60 秒,我正在添加一张 Gif 图片。输出看起来正确,声音打开,gif 动画,视频没有停止。这是代码:
我正在尝试使用 FFmpeg 以编程方式将图像或视频叠加在另一个视频的顶部。似乎 AVFilter 可以做到这一点。 有很多关于如何使用命令行执行此操作或类似操作的示例,但是,除了 doc/examp
我正在尝试实现类似 StackOverflow 的水印功能。 我正在使用 jquery-watermark为了这。我遇到的问题是水印文本随着输入元素获得焦点而消失,这在 SO 中不会发生(我也不希望在
我是一名优秀的程序员,十分优秀!