class Captcha: def __init__(self, n_characters = 4, output_dir = "./"): self.n_characters = n_characters self.output_dir = output_dir self.image = ImageCaptcha() self.available_characters = self.generate_available_characters() self.data = self.generate_random_data() def generate_available_characters(self): ''' Devuelve una cadena con todas las letras mayúsculas y números del 1 al 9. ''' return string.ascii_uppercase + string.digits def generate_random_data(self): try: return "".join([random.choice(self.available_characters) for i in range(self.n_characters)]) except Exception as e: print(f"Problema generando caracteres aleatorios: {e}") def generate_filename(self): return self.output_dir + self.data + ".png" def save(self): try: self.image.generate(self.data) self.image.write(self.data, self.generate_filename()) except Exception as e: print(f"Problema guardando la imagen: {e}")
async def auth(ctx): Image_captcha = ImageCaptcha() a = "" for i in range(5): a += str(random.randint(0, 9)) name = str(ctx.author.id) + ".png" Image_captcha.write(a, name) await ctx.channel.send(file=discord.File(name)) def check(msg): return msg.author == ctx.author and msg.channel == ctx.channel try: msg = await client.wait_for("message", timeout=60, check=check) except: await ctx.channel.send("Time Out!") return if msg.content == a: await ctx.channel.send("Welcome To Debian!") member = msg.author role = get(member.guild.roles, name=UserConfig["AuthRole"]) rolen = UserConfig["AuthRole"] await ctx.author.add_roles(role) print(f"{member} was given {rolen}") else: await ctx.channel.send("Wrong answer")
def do_image(): # image = ImageCaptcha(fonts=['./comic.ttf', './comicbd.ttf']) image = ImageCaptcha() # data = image.generate('1234') # assert isinstance(data, BytesIO) image.write("1234", "out.jpeg", format="jpeg")
def image_gen(digits_num, output): image = ImageCaptcha() captcha_text = text_gen(digits_num=digits_num) captcha_text = ''.join(captcha_text) captcha = image.generate(captcha_text) image.write(captcha_text, output + captcha_text + '.png') return captcha_text
async def verify(self, ctx): role = ctx.guild.get_role(728488298062020609) if role is not None and role not in ctx.author.roles: await ctx.message.delete() img = ImageCaptcha() a = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] random.shuffle(a) code = "".join(a)[:6] img.write(code, f"temp/{ctx.author.id}.png") m = await ctx.send(f":stopwatch: {ctx.author.mention} - 60초 안에 보안 코드를 입력해주세요.", file=discord.File(f"temp/{ctx.author.id}.png")) def check(msg): return msg.channel == ctx.channel and msg.author == ctx.author try: msg = await self.bot.wait_for("message", timeout=60, check=check) except asyncio.TimeoutError: await m.edit(content=f"<:cs_no:659355468816187405> {ctx.author.mention} - 인증 시간이 초과되었어요.") await asyncio.sleep(3) await m.delete() else: await msg.delete() await m.delete() if msg.content == code: m2 = await ctx.send(content=f"<:cs_yes:659355468715786262> {ctx.author.mention} - 인증이 완료되셨어요. 곧 역할이 자동으로 지급되실 거에요.") await ctx.author.add_roles(role) await asyncio.sleep(3) await m2.delete() else: m2 = await ctx.send(f"<:cs_protect:659355468891947008> {ctx.author.mention} - 코드가 잘못되었어요.\n잠시 후 인증을 다시 시도해주세요.") await asyncio.sleep(3) await m2.delete() else: await ctx.send(f"<:cs_id:659355469034422282> {ctx.author.mention} - 이미 역할을 가지고 계셔서 취소되었어요.")
async def on_member_join(self, member): log = self.configcol.find( {"$and": [{"guild": member.guild.id}, {"cfg_type": "captcha"}]} ) capStat = 'off' for i in log: capStat = i['status'] if capStat == 'off': return msg = await member.send(f"Hey there {member}, we just need to do one little thing to make sure you're a human and not anything malicious... Please complete this captcha (rejoin to regenerate a captcha):") image = ImageCaptcha() captchaAMT = ''.join(random.choices(string.ascii_uppercase + string.digits, k=4)) data = image.generate(captchaAMT) image.write(captchaAMT, f"{captchaAMT}CAPTCHA.png") await member.send(file=discord.File(f"{captchaAMT}CAPTCHA.png")) def check(m): return m.content == captchaAMT and m.guild is None await self.bot.wait_for('message', check=check) role = discord.utils.get(member.guild.roles, name="Captcha Verified") await member.add_roles(role) await member.send("Captcha verified. Giving you access...")
def gen_captcha_text_and_image(): image = ImageCaptcha() captcha_text = random_captcha_text() # 列表 captcha_text = ''.join(captcha_text) # 转为字符串 captcha = image.generate(captcha_text) # 生成图片 image.write(captcha_text, 'TensorFlow/images/' + captcha_text + '.jpg') # 写入文件
async def certification(self, ctx): Image_captcha = ImageCaptcha() a = "" for i in range(6): a += str(random.randint(0, 9)) name = str(ctx.author.id) + ".png" Image_captcha.write(a, name) await ctx.send(file=discord.File(name)) def check(msg): return msg.author == ctx.author and msg.channel == ctx.channel try: msg = await self.client.wait_for("message", timeout=60, check=check) except: await ctx.send("시간초과입니다.") return if msg.content == a: await ctx.send("정답입니다.") else: await ctx.send("오답입니다.")
def generateCaptchaText(width=CAPTCHA_WIDTH, height=CAPTCHA_HEIGHT, saveDir="./img/", save=False): """ 生成随机验证码 :param width: 验证码图片宽度 :param height: 验证码图片高度 :param save: 是否保存(None) :return: 验证码字符串,验证码图像np数组 """ image = ImageCaptcha(width=width, height=height) # 验证码文本 captchaText = randomCaptchaText(char_set=CAPTCHA_LIST, captcha_size=CAPTCHA_LENGTH) captcha = image.generate(captchaText) # 保存 if save: image.write(captchaText, './img/' + captchaText + '.jpg') # captcha_image = Image.open(captcha) # 转化为np数组 # captcha_image = np.array(captcha_image) return captchaText
def generate_first_image(): img = ImageCaptcha() s = generate_captcha() #print(s) value = img.generate(s) img.write(s, "c1.png")
async def captcha_test(self, ctx): image = ImageCaptcha(width=280, height=90) rand_word = random.choice(self.bag_of_words) user_id = f'{ctx.author.id}' image.generate(rand_word) image.write(chars=rand_word, output=f'./captchapictures/{user_id}.png', format='png') file_path = project_path + f'/captchapictures/{user_id}.png' img = File(fp=file_path) await ctx.channel.send( file=img, content='You have 60 seconds time to resolve captcha') try: msg_usr = await self.bot.wait_for('message', check=check(ctx.message.author), timeout=60.0) if msg_usr.content == rand_word: await ctx.author.send(content='Great you are not a robot') else: await ctx.author.send( content= "Captcha Verification Failed. Please try again by starting all over with" " @VirtualMarshal again") except asyncio.TimeoutError: await ctx.author.send( content= 'Your time has run out please request captcha again with command recaptcha' )
def gen_captcha_text_and_image(): image = ImageCaptcha() captcha_text = random_captcha_text() # change captcha array into string captcha_text = ''.join(captcha_text) captcha = image.generate(captcha_text) image.write(captcha_text, 'captcha/image/' + captcha_text + ".jpg")
def generateCaptcha(): # First we generate a random string to use // Changed to only use lowercase letters, as by user requests chars = string.ascii_lowercase + string.digits text = ''.join(random.choice(chars) for x in range(5)) # And generate the captcha captchaimage = ImageCaptcha() image = captchaimage.generate_image(text) # Now to add some noise captchaimage.create_noise_curve(image, image.getcolors()) captchaimage.create_noise_dots(image, image.getcolors()) # Now to write the file filenumber = 0 while True: if os.path.exists("./img/captcha_" + str(filenumber) + ".png"): filenumber += 1 else: break imagefile = "./img/captcha_" + str(filenumber) + ".png" captchaimage.write(text, imagefile) return imagefile, text
def captcha_food() -> dict: # Food CAPTCHA result = {} try: question = choice(glovar.chinese_words["food"]) answer = question candidates = [answer] for _ in range(2): candidate = choice(glovar.chinese_words["food"]) while candidate in candidates: candidate = choice(glovar.chinese_words["food"]) candidates.append(candidate) shuffle(candidates) image = ImageCaptcha(width=300, height=150, fonts=[glovar.font_chinese]) image_path = f"{get_new_path('.png')}" image.write(question, image_path) result = { "image": image_path, "question": lang("question_food"), "answer": answer, "candidates": candidates, "limit": glovar.limit_try } except Exception as e: logger.warning(f"Captcha food error: {e}", exc_info=True) return result
async def captcha(self, ctx, *, text): languageserver = await settings.collectionlanguage.find_one( {"guild_id": ctx.guild.id}) if languageserver is None: message = await ctx.send( embed=languageEmbed.languageembed(self, ctx)) await message.add_reaction('👍') else: server_language = languageserver["Language"] if server_language == "Thai": image = ImageCaptcha() image.write(text, 'image/captcha.png') file = nextcord.File("image/captcha.png", filename="captcha.png") embed = nextcord.Embed(colour=0x00FFFF, title="Captcha") embed.set_image(url="attachment://captcha.png") embed.set_footer(text=f"┗Requested by {ctx.author}") await ctx.send(embed=embed, file=file) if server_language == "English": image = ImageCaptcha() image.write(text, 'image/captcha.png') file = nextcord.File("image/captcha.png", filename="captcha.png") embed = nextcord.Embed(colour=0x00FFFF, title="Captcha") embed.set_image(url="attachment://captcha.png") embed.set_footer(text=f"┗Requested by {ctx.author}") await ctx.send(embed=embed, file=file)
def GenerateImageCaptcha(text, out_path, font_paths=["Data/Fonts/Sans.ttf"]): image = ImageCaptcha(fonts=font_paths) # data = image.generate(text) image.write(text, out_path) # Driver Code
def imagecaptcha(name,font='/Users/niklasinde/Library/Fonts/billy.ttf'): image = ImageCaptcha(fonts=[font]) data = image.generate(name) assert isinstance(data, BytesIO) image.write(string, "capache/"+name) print("hej")
def _gen_captcha(img_dir_train, img_dir_test, num_per_image, n, width, height, choices): if os.path.exists(img_dir_train): shutil.rmtree(img_dir_train) if not os.path.exists(img_dir_train): os.makedirs(img_dir_train) if os.path.exists(img_dir_test): shutil.rmtree(img_dir_test) if not os.path.exists(img_dir_test): os.makedirs(img_dir_test) image = ImageCaptcha(width=width, height=height) print('generating %s epoches of captchas in %s' % (n, img_dir_train)) for _ in range(n): check = 0 for captcha in [ ''.join(i) for i in itertools.permutations(choices, num_per_image) if random.random() >= 0.985 ]: if random.random() < 0.8: fn = os.path.join(img_dir_train, '%s_.png' % (captcha)) else: fn = os.path.join(img_dir_test, '%s_.png' % (captcha)) image.write(captcha, fn) check = check + 1 if check % 1000 == 0: print(check)
def gen_captcha_text_and_image(): image = ImageCaptcha() captcha_text = random_captcha_text() captcha_text = ''.join(captcha_text) #生成验证码 captcha = image.generate(captcha_text) image.write(captcha_text,'captcha/images/'+captcha_text+'.jpg')
def gen_captcha_text_image(): image = ImageCaptcha() captcha_text = random_captcha_text() captcha_text = ''.join(captcha_text) captcha = image.generate(captcha_text) image.write(captcha_text, 'captcha/images/' + captcha_text + '.jpg') # writes to the file
def login(): if COOKIE_SECURITY == True: cookie_id = request.get_cookie('cookie_id', secret='key') else: cookie_id = request.get_cookie('cookie_id') if cookie_id != None: try: user = Users.get(Users.cookie_id == cookie_id) username = user.username except Users.DoesNotExist: # There is not any user. error_message("User Does Not Exist") redirect('/error') else: username = "******" import random import string if CAPTCHA == True: captcha_text = ''.join( [str(random.choice(list(range(0, 10)))) for i in range(4)]) if COOKIE_SECURITY == True: response.set_cookie('captcha', captcha_text, secret='key') else: response.set_cookie('captcha', captcha_text) from captcha.image import ImageCaptcha captcha_image = ImageCaptcha() captcha_image.write(captcha_text, './static/img/captcha.png') return template('login', username=username, is_captcha=CAPTCHA)
def get_pic(): image = ImageCaptcha() for _ in range(NUMBER_OF_PIC): captcha_text = random_captcha_text() captcha_text = ''.join(captcha_text) captcha = image.generate(captcha_text) image.write(captcha_text, "pic/" + captcha_text + '.jpg') # 写到文件
def gen_img_captcha(captcha_string_size=6): image_captcha = ImageCaptcha(width=1250, height=800, font_sizes=[350, 210, 300]) text = gen_captcha(captcha_string_size) image_file = "./" + "captcha.png" image_captcha.write(text, image_file)
def gen_captcha_text_and_image(width=CAPTCHA_WIDTH, height=CAPTCHA_HEIGHT, save=None, fileName=None): """ 生成随机验证码 :param width: 验证码图片宽度 :param height: 验证码图片高度 :param save: 是否保存(None) :return: 验证码字符串,验证码图像np数组 """ image = ImageCaptcha(width=width, height=height) # 验证码文本 captcha_text = random_captcha_text() captcha = image.generate(captcha_text) # 保存 if save: image.write(captcha_text, './train/' + str(fileName) + '.jpg') #先将图片名和标注分别写入两个list中 picname.append(str(fileName) + '.jpg') picTab.append(str(captcha_text)) # print(picTab) captcha_image = Image.open(captcha) # 转化为np数组 captcha_image = np.array(captcha_image) return captcha_text, captcha_image
def get_captcha_text_and_image(): image = ImageCaptcha() captcha_text = random_captcha_text() # 返回的是一个列表,如['3', '4', '5', '6'] captcha_text = ''.join(captcha_text) # 将列表拼接成一个字符串 # 生成验证码 captcha = image.generate(captcha_text) image.write(captcha_text, 'captcha/images/'+captcha_text+'.jpg')
def process_file(self): logging.debug("Reading data of the csv file.") self.data = pd.read_csv(self.filePath, header=0) assertionMessage = "The columns should equal the number of \{ \} in the message + 1" if len(self.toCaptcha) > 0: assertionMessage = "+ number of captchable columns." else: assertionMessage += "." assert self.body.count('{') == self.data.shape[1] - len( self.toCaptcha) - 1, assertionMessage logging.debug("Starting iteration over emails to be sent.") for _, row in self.data.iterrows(): files = [] textParts = [] for element in self.data.columns[1:]: if element in self.toCaptcha: try: logging.debug( f"Creating captcha for {row[0]}. {element} field.") filename = '{}.png'.format(element) image = ImageCaptcha(width=len(row[element] * 30)) image.write(row[element], filename) files.append(filename) except: print( "The column {} you wanna captcha is not a column of the .csv" .format(element)) else: textParts.append(row[element]) logging.info(f"Sending email to {row[0]}") self.send_mail(send_to=row[0], text=self.body.format(*textParts), files=files)
def main(): parser = argparse.ArgumentParser() parser.add_argument("-p", "--path", required=False, help="path to store generated images") parser.add_argument("-n", "--number", required=True, help="number of images generated") producer = ImageCaptcha(width=config['image_width'], height=config['image_height'], font_sizes=[40]) args = vars(parser.parse_args()) if "path" not in args: path = config['images_path'] else: path = args['path'] if not os.path.exists(path): os.makedirs(path) print("Starting generating %d images in %s" % (int(args['number']), path)) for i in range(int(args['number'])): number_to_write = "".join( [random.choice(string.digits) for _ in range(4)]) producer.write( number_to_write, os.path.join(path, str(i) + "_" + number_to_write + ".png")) print("images generated!") print("-" * 30) print("Staring convert tfrecords of these generated images!") generate_tfrecords(path) print("tfrecords generated!")
def ask_captcha(bot, update, callback=False): global mainBot if callback: chatID = update.callback_query.message.chat_id else: chatID = update.message.chat_id if (not callback): if mainBot.get_captcha_solution(chatID) == update.message.text: bot.send_message(chat_id=chatID, text="please wait, be calm, this may take 3 min") find_seat(update.message.from_user.username, chatID) return image = ImageCaptcha( fonts=['fonts/Inconsolata-g.ttf', 'fonts/RobotoSlab-Regular.ttf']) randStr = ''.join( random.choice(string.ascii_lowercase + string.digits) for _ in range(6)) data = image.generate(randStr) print('hehshe') assert isinstance(data, BytesIO) image.write(randStr, 'curCaptcha.png') print('afeois') mainBot.set_phase(chatID, ask_captcha) print('sfle') bot.send_photo(chat_id=chatID, photo=open('curCaptcha.png', 'rb')) bot.send_message(chat_id=chatID, text="please write the captcha") print("alsdkfa") mainBot.set_captcha_solution(chatID, randStr)
def creat_image(): image = ImageCaptcha(width=160, height=60, font_sizes=[35]) # 获取随机生成的字符串 text = __gen_random_captcha_text(size=config.MAX_CAPTCHA) # 将字符串加入图片 image.write(text, "../1.png")
def generate(num=1, path='./', low=3, high=10, char_set=number+alphabet+ALPHABET): if not os.path.exists(path): os.mkdir(path) for i in range(num): captcha_text = get_text(low, high, char_set) image = ImageCaptcha(30*len(captcha_text), 64) image.write(captcha_text, path+str(i)+'_'+captcha_text+'.png')
def generate_captcha_image(charSet=CHAR_SET, charSetLen=CHAR_SET_LEN, captchaImgPath=CAPTCHA_IMAGE_PATH): k = 0 total = 1 for i in range(CAPTCHA_LEN): total *= charSetLen for i in range(charSetLen): for j in range(charSetLen): for m in range(charSetLen): for n in range(charSetLen): captcha_text = charSet[i] + charSet[j] + charSet[ m] + charSet[n] image = ImageCaptcha() image.write(captcha_text, captchaImgPath + captcha_text + '.jpg') img = Image.open(captchaImgPath) print("image = ", image) #转为灰度图 img = image.convert("L") print("img") plt.figure("img") plt.imshow(img) plt.show() k += 1 sys.stdout.write("\rCreating %d/%d" % (k, total)) sys.stdout.flush()
def do_image(): # image = ImageCaptcha(fonts=['./comic.ttf', './comicbd.ttf']) image = ImageCaptcha(width=100, height=50) # data = image.generate('1234') # assert isinstance(data, BytesIO) image.write('1234', 'out.%s' % fmt_suffix.get(fmt, fmt), fmt=fmt)
def stress_image(i): image = ImageCaptcha(width=100, height=50, fonts=['./Mirvoshar.ttf'], font_sizes=[50, 54, 57, 64]) d = str(i) if os.path.exists(d): shutil.rmtree(d) os.makedirs(d) for t in texts: image.write(t, os.path.join(d, '%s.%s' % (t, fmt_suffix.get(fmt, fmt))), fmt=fmt)
def gen_captcha(length=None): length = length if length else LENGTH image = ImageCaptcha(width=130, height=60) # fonts=FONTS) text = random_text(length) image.generate(text) code_signature = sign(text) fpath = os.path.join(OUTDIR, code_signature + ".png") image.write(text, fpath) return fpath, code_signature
def gen_captcha_text_and_image(): image = ImageCaptcha() #获得随机生成的验证码 captcha_text = random_captcha_text() #把验证码列表转为字符串 captcha_text = ''.join(captcha_text) #生成验证码 captcha = image.generate(captcha_text) image.write(captcha_text, 'captcha/images/' + captcha_text + '.jpg') # 写到文件
def gen_captcha_text_and_image(): image = ImageCaptcha() captcha_text = random_captcha_text() captcha_text = ''.join(captcha_text) captcha = image.generate(captcha_text) image.write(captcha_text, captcha_text + '.jpg') # 写到文件 captcha_image = Image.open(captcha) captcha_image = np.array(captcha_image) return captcha_text, captcha_image
def generate_verification_code(request): ''' ''' code = random_code_generator(5) image = ImageCaptcha() image.write(code, 'captcha/{0}.png'.format(code)) verification_code = { 'verification_image': '{0}.png'.format(code), 'code': code} return HttpResponse(json.dumps(verification_code), status=200, content_type='application/json')
def appear(self): # Make captcha row = str(uuid.uuid4())[:4] img = ImageCaptcha() data = img.generate("1") assert isinstance(data, BytesIO) img.write(row, "captcha.png") pixmap = QtGui.QPixmap("captcha.png") self.ui.captcha_lb.setPixmap(pixmap) os.remove("captcha.png") # Appear win self.show() self.animation_appear.start()
def myCaptchaLoader(request): to_json_response = dict() image = None try: print "IN CAPTCHA METHOD....." to_json_response['status'] = 1 image = ImageCaptcha(fonts=['Ubuntu-B.ttf', 'UbuntuMono-R.ttf']) image.write('1234','out.png') print "CAPTCHA CREATED..." except: print "\nException OCCURED",sys.exc_info()[0] return StreamingHttpResponse(json.dumps(to_json_response),content_type="application/json")
def newcaptcha(text, fontspath='captcha/fonts/'): cherrypy.session['capt_code'] = text fonts = [] for x in os.listdir(fontspath): if x.split('.')[-1] == 'ttf':#if font file fonts.append(fontspath+x) img = StringIO.StringIO() image = ImageCaptcha(fonts=fonts) data = image.generate(text) image.write(text, img) contents = img.getvalue() img.close() return contents
from io import BytesIO from captcha.image import ImageCaptcha import base64 image = ImageCaptcha() captcha_text = "humble" data = image.generate(captcha_text) assert isinstance(data, BytesIO) image.write(captcha_text, "out.png") # print('data') # print(type(data)) # print(type(data.getvalue())) # print(str(data.getvalue())) encoded = base64.b64encode(data.getvalue()) print(encoded) # with open('out.png', 'r') as f: # c = f.read() # print(c)
__author__ = 'wenjusun' from io import BytesIO from captcha.image import ImageCaptcha import random image = ImageCaptcha(fonts=['/var/shijing/Abyssinica_SIL.ttf', '/usr/share/fonts/vlgothic/VL-Gothic-Regular.ttf']) data = image.generate('1234') #assert isinstance(data, BytesIO) image.write('1234', 'out.png') class CaptchImage(): def get_path(self): return "" def generate_captch(self): return "" ch_az=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', '0','1','2','3','4','5','6','7','8','9'] def get_random_characters(width=4): return random.sample(ch_az,width)
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from captcha.image import ImageCaptcha import os import random length = 4 width = 160 height = 60 IMAGE_DIR = "images" def random_text(): return ''.join(str(random.randint(0, 9)) for _ in range(length)) if __name__ == '__main__': image = ImageCaptcha(width=width, height=height) captcha_text = random_text() if not os.path.exists(IMAGE_DIR): os.makedirs(IMAGE_DIR) image.write(captcha_text, os.path.join(IMAGE_DIR, captcha_text + ".png"))
from captcha.image import ImageCaptcha import os import random hash = SHA256.new() semilla="" r=0 image = ImageCaptcha(fonts=['./fon/A.ttf', './fon/B.ttf']) for i in range(5): r=random.randrange(100) semilla=semilla+chr(r) print str(i)+" "+str(r)+" "+chr(r)+" "+semilla print semilla+"\n" data = image.generate(semilla) image.write(semilla, '/tmp/out.png') image.write(semilla, 'out.png') os.remove("/tmp/out.png") hash.update(semilla) otra=hash.digest() llave = "" print otra for i in range(16): llave=llave+otra[i] print str(i)+" "+otra[i]+" "+llave print "\n" print llave archy=open('llave.txt','w')
from captcha.image import ImageCaptcha import string import random path = "images/" def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) image = ImageCaptcha(fonts=['OpenSans-Regular.ttf'], width=250) for x in range(0, 10000): randString = id_generator() image.write(randString, path + randString + "-" + str(x) + ".png")
def write_captcha_file(text, output_file, width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT, font=None): fonts = None if font is not None: fonts = [font] image = ImageCaptcha(width=width, fonts=fonts, height=height) image.write(text, output_file)
from captcha.image import ImageCaptcha image = ImageCaptcha(fonts=['C:\\Users\\user\\Desktop\\RandomCodes\\CaptchaGenerator\\A.ttf']) data = image.generate('I am Pragyaditya Das') image.write('I am Pragyaditya Das', 'out.png')