我是python和django的新手。我使用django开发了一个项目。这里所有图像都有水印。我使用以下代码为所有图像加水印......
from PIL import Image
def image_watermark(request,image_id):
photo = Photo.objects.get(pk=image_id)
watermark = Image.open('{0}/{1}'.format(settings.MEDIA_ROOT,'wmark.png'))
img = Image.open(photo.photo.file)
img.paste(watermark,(img.size[0]-watermark.size[0],img.size[1]- watermark.size[1]),watermark)
img.save('{0}/{1}'.format(settings.MEDIA_ROOT,photo.photo.name), quality=80)
wrapper = FileWrapper(open(photo.photo.url, 'rb'))
response = StreamingHttpResponse(wrapper, 'image/jpeg')
response['Content-Length'] = os.path.getsize(photo.photo.url)
response['Content-Disposition'] = 'attachment; filename=photo.jpg'
return response
我的所有图像都已加水印了。但问题是,作为用户,如果我下载这些图像,我发现下载的图像也有水印,但我想下载实际图像,而不是水印图像,我该如何解决这个问题?
答案 0 :(得分:3)
您需要将带水印的图像存储到其他文件中。 首先,您需要创建另一列来存储水印图像。
class Photo(models.Model):
...
watermarked_photo = ImageField()
然后将水印图像保存到该列中。
from PIL import Image
def image_watermark(request,image_id):
photo = Photo.objects.get(pk=image_id)
# Only need to watermark when there's no watermark
if not photo.watermarked_photo.name:
photo.watermarked_photo.name = 'watermarked_' + photo.photo.name
watermark = Image.open('{0}/{1}'.format(settings.MEDIA_ROOT,'wmark.png'))
img = Image.open(photo.photo.file)
img.paste(watermark,(img.size[0]-watermark.size[0],img.size[1]- watermark.size[1]),watermark)
img.save('{0}/{1}'.format(settings.MEDIA_ROOT, photo.watermarked_photo.name), quality=80)
photo.save()
wrapper = FileWrapper(open(photo.watermarked_photo.url, 'rb'))
response = StreamingHttpResponse(wrapper, 'image/jpeg')
response['Content-Disposition'] = 'attachment; filename=photo.jpg'
return response
我的Django技能有点生疏,所以如果没有一些修改,这些代码可能无法正常工作。但这个想法应该是可靠的。
如果您只想使用临时文件,请尝试使用
from PIL import Image
import tempfile
def image_watermark(request,image_id):
photo = Photo.objects.get(pk=image_id)
watermark = Image.open('{0}/{1}'.format(settings.MEDIA_ROOT,'wmark.png'))
img = Image.open(photo.photo.file)
img.paste(watermark,(img.size[0]-watermark.size[0],img.size[1]- watermark.size[1]),watermark)
tmpfile = tempfile.TemporaryFile()
img.save(tmpfile, img.format, quality=80)
tmpfile.seek(0)
wrapper = FileWrapper(tmpfile)
response = StreamingHttpResponse(wrapper, 'image/jpeg')
response['Content-Disposition'] = 'attachment; filename=photo.jpg'
return response