码迷,mamicode.com
首页 > 其他好文 > 详细

ckeditor

时间:2020-04-07 00:05:02      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:from   files   memory   max   ima   obj   png   editor   rgba   

from io import BytesIO

from django.core.files.storage import FileSystemStorage
from django.core.files.uploadedfile import InMemoryUploadedFile

from PIL import Image, ImageDraw, ImageFont


class WatermarkStorage(FileSystemStorage):
    def save(self, name, content, max_length=None):
        # 处理逻辑
        if ‘image‘ in content.content_type:
            # 加水印
            image = self.watermark_with_text(content, ‘the5fire.com‘, ‘red‘)
            content = self.convert_image_to_file(image, name)

        return super().save(name, content, max_length=max_length)

    def convert_image_to_file(self, image, name):
        temp = BytesIO()
        image.save(temp, format=‘PNG‘)
        file_size = temp.tell()
        return InMemoryUploadedFile(temp, None, name, ‘image/png‘, file_size, None)

    def watermark_with_text(self, file_obj, text, color, fontfamily=None):
        image = Image.open(file_obj).convert(‘RGBA‘)
        draw = ImageDraw.Draw(image)
        width, height = image.size
        margin = 10
        if fontfamily:
            font = ImageFont.truetype(fontfamily, int(height / 20))
        else:
            font = None
        textWidth, textHeight = draw.textsize(text, font)
        x = (width - textWidth - margin) / 2  # 计算横轴位置
        y = height - textHeight - margin  # 计算纵轴位置
        draw.text((x, y), text, color, font)

        return image

  

ckeditor

标签:from   files   memory   max   ima   obj   png   editor   rgba   

原文地址:https://www.cnblogs.com/realadmin/p/12650402.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!