修改这个 Python 只发送一张彩色图片

问题描述

我有这个 python 脚本与 Telebot 一起工作,在 Telegram 中为图像加水印,然后在机器人聊天中发回带水印的图像。 我从 Github 获得了这个并希望改变它,但不知何故我失败了。

电流

  1. 将图像发送到水印机器人
  2. 水印机器人将下载图像,添加黑白水印
  3. 水印机器人将在聊天中发回两张图片,每种颜色一张

预期流量

  1. 只发回一种颜色(白色)。

代码 1

from PIL import Image,ImageFont,ImageDraw,ImageEnhance
import hashlib
import piexif
import config


def getting_ready(path):
    fname = md5(path) + '.jpg'
    image = Image.open(path).convert('RGB')
    try:
        exif_dict = piexif.load(image.info['exif'])
        orientation = exif_dict['0th'][274]
    except KeyError:
        orientation = None
    rotate_values = {3: 180,6: 270,8: 90}
    if orientation in rotate_values:
        image = image.rotate(rotate_values[orientation],expand=True)
    for color in ['black','white']:
        watermark(image,fname,color)
    return fname


def watermark(img,new_fname,color):
    text = config.WATERMARK
    wm = Image.new('RGBA',img.size,(0,0))
    fontsize = img.size[1] // 100 * config.FONT_SIZE
    font = ImageFont.truetype(f'tools/fonts/{config.FONT_NAME}',fontsize)
    indent = fontsize // 6
    w,h = font.getsize(text)
    text_position = (img.size[0] - w - indent,img.size[1] - h - indent)
    draw = ImageDraw.Draw(wm,'RGBA')
    draw.text(text_position,text,font=font,fill=color)
    alpha = wm.split()[3]
    alpha = ImageEnhance.Brightness(alpha).enhance(config.TRANSPARENCY)
    wm.putalpha(alpha)
    out_path = 'images/out/{}/{}'.format(color,new_fname)
    Image.composite(wm,img,wm).save(out_path,'JPEG',optimize=False,quality=config.QUALITY)


def md5(path):
    with open(path,'rb') as f:
        md5hash = hashlib.md5()
        for chunk in iter(lambda: f.read(4096),b''):
            md5hash.update(chunk)
    return md5hash.hexdigest()

代码

# -*- coding: utf-8 -*-
import telebot
import config
import random
import os
import time
from tools.tools import getting_ready

bot = telebot.TeleBot(config.BOT_TOKEN)


@bot.message_handler(commands=['start','help'])
def send_welcome(message):
    bot.send_message(message.chat.id,'Hi,Send or Forward me a PHOTO!')


@bot.message_handler(func=lambda message: True)
def echo_all(message):
    bot.reply_to(message,'Send /start or /help')


@bot.message_handler(content_types=["photo"])
def send_watermark(message):
    chat_id = message.chat.id
    sent_message = bot.reply_to(message,'Downloading...')
    message_id = sent_message.message_id
    file = bot.get_file(message.photo[0].file_id)
    downloaded_file = bot.download_file(file.file_path)
    bot.edit_message_text(f'Downloaded!\n\nNow,Genarating Watermarks...\n\ncurrent watermark: {config.WATERMARK}',chat_id=chat_id,message_id=message_id)
    __path = 'images/' + str(random.randint(100000,999999)) + '.tmp'
    with open(__path,'wb') as f:
        f.write(downloaded_file)
    fname = getting_ready(__path)
    os.remove(__path)
    time.sleep(2)
    bot.edit_message_text('Now,Uploading...',message_id=message_id)
    for i in ('black','white'):
        __file = 'images/out/{}/{}'.format(i,fname)
        __photo = open(__file,'rb')
        bot.send_photo(message.chat.id,__photo,reply_to_message_id=message.message_id)
        os.remove(__file)
    bot.delete_message(chat_id=chat_id,message_id=message_id)


print('watermark bot started successfully!')
bot.polling()

我尝试过的步骤

  1. ['black','white'] 修改['white'] 导致错误
  2. for i in ('black','white'): 修改for i in ('white') 并导致错误

我想不出还有什么,尝试更改一些我只是不明白的东西,例如 Image.composite(wm,wm).save删除 wm 的实例。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)