我正在制作一个chrome扩展程序,它会生成一个meme,给定一个选定的文本。预期的功能是选择一些文本字符串,打开上下文菜单,然后单击“Generate Meme”按钮,该按钮将下载生成的模因或提供图像链接。
我的困境是我使用Python的成像库(PIL)创建了meme生成器脚本,但是,我不知道如何将该脚本实现到我的Chrome扩展程序(Javascript)中。
这是Python脚本:
import PIL
from convert import convert
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
topString = input("Enter Top Message: ")
bottomString = input("Enter Top Message: ")
topString = convert(topString)
bottomString = convert(bottomString)
print(topString + " " + bottomString)
img = Image.open("base.jpg")
font = ImageFont.truetype("Krabby Patty.ttf", fontSize)
imageSize = img.size
fontSize = int(imageSize[1] / 5)
topTextSize = font.getsize(topString)
bottomTextSize = font.getsize(bottomString)
while topTextSize[0] > imageSize[0] - 20 or bottomTextSize[0] > imageSize[0] - 20:
fontSize = fontSize - 1
font = ImageFont.truetype("Krabby Patty.ttf", fontSize)
topTextSize = font.getsize(topString)
bottomTextSize = font.getsize(bottomString)
topTextPosition = ((imageSize[0] / 2) - (topTextSize[0] / 2), 0)
bottomTextPosition = ((imageSize[0] / 2) - (bottomTextSize[0] / 2), imageSize[1] - bottomTextSize[1])
draw = ImageDraw.Draw(img)
#Outline text
outlineRange = int(fontSize / 15)
for x in range(-outlineRange, outlineRange + 1):
for y in range(-outlineRange, outlineRange + 1):
draw.text(
(topTextPosition[0] + x, topTextPosition[1] + y), topString, (0, 0, 0), font=font)
draw.text(
(bottomTextPosition[0] + x, bottomTextPosition[1] + y), bottomString, (0, 0, 0), font=font)
draw.text(topTextPosition, topString, (255, 255, 255), font=font)
draw.text(bottomTextPosition, bottomString, (255, 255, 255), font=font)
img.save("meme.png")
这是Chrome扩展程序的Javascript:
var genMSM = function(info) {
message = convert(info.selectionText)
}
chrome.contextMenus.create({
title: "Generate Meme",
contexts: ["selection"],
onclick: genMSM
});
function convert(message) {
output = ""
for(var i = 0; i < message.length; i++){
output += i % 2 == 0 ? message.charAt(i).toLowerCase():message.charAt(i).toUpperCase();
}
return output
}
非常感谢有关如何实现这一点的任何帮助或建议!