def create_image_char(image_width, image_height, char, count, background,
                      save_file_path):
    '''
    This function is create char  captcha image
    :param image_width:image width
    :param image_height:   image height
    :param char:Str char
    :param count:Int count
    :param background:Str (White)(Black)(Red)...colors
    :param save_file_path:save image file path
    :return:file path list
    '''
    if image_width == 0 and image_height == 0:
        img = ImageCaptcha(width=120, height=60)
    else:
        img = ImageCaptcha(width=image_width, height=image_height)
    print('Image Create Char is start!')
    _path = []
    for i in range(0, count):
        file_path = save_file_path + '{}_{}_{}.png'.format(
            str(char), str(time.strftime('%Z%Y%m%d%H%M%S', time.localtime())),
            str(random.randint(0, 100)))
        img.create_captcha_image(chars=str(char),
                                 color=random_color(),
                                 background=background).save(file_path)

        _path.append(file_path)
        time.sleep(0.1)
        print('Save {}'.format(file_path))
    return _path
Beispiel #2
0
def gen_captcha_text_and_image(is_save, image_path=None, char_set=None, file_name=None, suffix="png"):
    """生成字符对应的验证码

    :param image_path: 生成后的验证码路径
    :type image_path str

    :param is_save: 是否保存图片
    :type is_save bool

    :param char_set: 字符列表
    :type char_set list

    :param file_name: 验证码文件名
    :type file_name str

    :param suffix: 图片后缀,默认值位 png
    :type suffix str

    :rtype captcha_text str
    :return captcha_text 验证码内容

    :rtype file_path str
    :return file_path 验证码路径

    :rtype captcha_image PIL.Image.Image
    :return captcha_image Image对象
    """
    image_captcha = ImageCaptcha(width=160, height=60, fonts=None, font_sizes=(56,))

    # 获得验证码内容
    captcha_text = random_captcha_text(char_set)
    captcha_text = ''.join(captcha_text)

    if is_save:
        # 图片路径
        file_name_ = file_name if file_name else captcha_text
        file_name = "{}.{}".format(file_name_, suffix)
        file_path = os.path.join(image_path, file_name)

        # 设置颜色
        background = (255, 255, 255)  # 白色
        color = (220, 0, 0)  # 红色

        # 在write中会随机字体大小颜色和背景色
        # image_captcha.write(captcha_text, file_path)
        img = image_captcha.create_captcha_image(captcha_text, color, background)

        # 保存图片
        img.save(file_path)
        return captcha_text, file_path
    else:
        # 进一步处理图片
        captcha = image_captcha.generate(captcha_text)
        captcha_image = Image.open(captcha)
        captcha_image = np.array(captcha_image)
        return captcha_text, captcha_image
Beispiel #3
0
def recapp():
    letters = string.ascii_lowercase + string.digits + string.ascii_uppercase
    result_str = ''.join(random.choice(letters) for i in range(9))
    image = ImageCaptcha(width=250, height=100)
    text = random

    image = image.create_captcha_image("{}".format(result_str),
                                       color="white",
                                       background="black")

    # image.show()
    return image.save("gen1.jpg")
Beispiel #4
0
def make_pic(number, height, width):
    #  验证按图片的一个对象
    image = ImageCaptcha(width=width, height=height, font_sizes=[30, 30])
    #  利用上文的make_char函数返回随机数序列[a b c d]
    context = make_char(number)
    #  调用库生成验证码图片

    final_image = image.create_captcha_image(context,
                                             color="#F7F7F7",
                                             background="#000000")
    #final_image.show()
    #  返回验证码图片的内容和图片矩阵 final_image
    return context, final_image
Beispiel #5
0
def captcha():
    c_str = ''.join(random.sample(CHARS, 4))
    img = ImageCaptcha(width=100, height=60, fonts=[FONT_PATH])
    image = img.create_captcha_image(c_str,
                                     color='#dc3545',
                                     background='#20c997')
    buf = BytesIO()
    image.save(buf, 'JPEG')
    buf_str = buf.getvalue()
    response = make_response(buf_str)
    response.headers['Content-Type'] = 'image/jpeg'
    session['captcha'] = c_str
    return response
Beispiel #6
0
def gen_captcha():
    #定义图片对象
    generator = ImageCaptcha(width=90, height=35, font_sizes=[fontsize])
    #获取字符串
    captcha_text = random_captcha()
    #生成图像
    # captcha_img = Image.open(image.generate(captcha_text))
    # return captcha_text,captcha_img
    img = generator.create_captcha_image(captcha_text, getRandomColor(),
                                         (255, 255, 255))
    for i in range(0):
        img = generator.create_noise_curve(img, getRandomColor())
    captcha_img = generator.create_noise_dots(img, getRandomColor(), 0, 0)
    return captcha_text, captcha_img
def create_image(random_data, image_file_path, image_width, image_height):
    '''
    This function is to create a image
    :param random_data:4 int str data
    :param image_file_path: save image path
    :param image_height image height
    :param image_width image_width
    :return:data length to creates
    '''
    # default
    if image_width == 0 and image_height == 0:
        img = ImageCaptcha(width=120, height=60)
    else:
        img = ImageCaptcha(width=image_width, height=image_height)
    print('Image Create is start!')
    for data in range(len(random_data)):
        img.create_captcha_image(
            random_data[data], color=random_color(),
            background='white').save(image_file_path + '{}_{}.png'.format(
                random_data[data],
                time.strftime('%Z%Y%m%d%H%M%S', time.localtime())))
        time.sleep(0.1)
        print('No.{}->{}.png'.format(data + 1, random_data[data]))
    return print('+Complete to create {} images+'.format(len(random_data)))
Beispiel #8
0
def generate_save_captcha(characters,
                          length,
                          amount,
                          folder_name,
                          width=130,
                          height=70):
    generator = ImageCaptcha(width=width, height=height)
    img_path = os.path.join(os.getcwd(), "img", folder_name)
    if not os.path.exists(img_path):
        os.makedirs(img_path)
    for _ in range(amount):
        captcha_str = "".join(
            [random.choice(characters) for j in range(length)])
        img = generator.create_captcha_image(captcha_str, (65, 105, 225),
                                             (255, 255, 255))
        img.save(os.path.join(img_path, "%s.png" % captcha_str))
Beispiel #9
0
def gen_img_and_text(width=120, height=60, char_set=None):
    image = ImageCaptcha(width=width, height=height)
    captha_text = random_captcha_text(char_set)  # 生成验证码的文本
    captha_text = "".join(captha_text)  # 拼接文本
    # 随机字符和背景的颜色
    w1, w2, w3 = random.randint(0, 255), random.randint(0,
                                                        255), random.randint(
                                                            0, 255)
    g1, g2, g3 = random.randint(0, 255), random.randint(0,
                                                        255), random.randint(
                                                            0, 255)
    # 生成验证码
    captha_image = image.create_captcha_image(captha_text, (w1, w2, w3),
                                              (g1, g2, g3))
    captha_image = np.array(captha_image)
    return captha_image, captha_text
def generate_img(char_num):
    global img_dir
    the_chars = gen_char(char_num)
    # 选择验证码的字体,图片大小,字体大小
    captcha = ImageCaptcha(fonts=['./font/simhei.ttf'])
    # 设置背景,颜色
    backgroud = random_color(238, 255)
    color = random_color(0, 200, opacity=None)
    # 创建图片
    img = captcha.create_captcha_image(the_chars, color, backgroud)
    captcha.create_noise_curve(img, color)
    captcha.create_noise_dots(img, color, number=None)
    from PIL import ImageFilter
    img.filter(ImageFilter.SMOOTH)
    # 保存生成的验证码,按照:序号_结果.png 保存
    img_name = the_chars + '.png'
    img_path = img_dir + '/' + img_name
    captcha.write(the_chars, img_path)
Beispiel #11
0
def get_image_code(req:Request):
    """
    获取图片验证码
    : params image_code_id:  图片验证码编号
    :return:  正常:验证码图片  异常:返回json
    """
    # 业务逻辑处理
    # 生成验证码图片
    # 名字,真实文本, 图片数据
    characters = string.digits + string.ascii_lowercase
    width, height, n_len, n_class = 170, 80, 4, len(characters)
    generator = ImageCaptcha(width=width, height=height)
    random_str = ''.join([random.choice(characters) for j in range(4)])
    img = generator.create_captcha_image(random_str, (0, 0, 153), (255, 255, 255))
    # 将验证码真实值与编号保存到redis中, 设置有效期
    # redis:  字符串   列表  哈希   set
    # "key": xxx
    # 使用哈希维护有效期的时候只能整体设置
    # "image_codes": {"id1":"abc", "":"", "":""} 哈希  hset("image_codes", "id1", "abc")  hget("image_codes", "id1")
    # 单条维护记录,选用字符串
    # "image_code_编号1": "真实值"
    # "image_code_编号2": "真实值"

    # redis_store.set("image_code_%s" % image_code_id, text)
    # redis_store.expire("image_code_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES)
    #                   记录名字                          有效期                              记录值
    try:
        ip = req.get("client")[0]
        redis_cli.setex(ip+"verify_code",600, random_str)
    except Exception as e:
        # 记录日志
        logger.error(e)
        # return jsonify(errno=RET.DBERR,  errmsg="save image code id failed")
        return JSONResponse(content="保存验证码失败", status_code=status.HTTP_406_NOT_ACCEPTABLE)
    # 返回图片
    out = BytesIO()
    img.save(out, format="JPEG")
    resp = Response(out.getvalue())
    resp.headers["Content-Type"] = "image/jpg"
    return resp
def gen_captcha(img_dir, num_per_image, number, choices):
    if os.path.exists(img_dir):
        shutil.rmtree(img_dir, ignore_errors=True)
    if not os.path.exists(img_dir):
        os.makedirs(img_dir)
    count = 0
    random_widths = list(range(64, 100, 1))
    for _ in range(number):
        for i in itertools.permutations(choices, num_per_image):
            if count >= number:
                break
            else:
                captcha = ''.join(i)
                fn = os.path.join(img_dir, '%s_%s.jpg' % (captcha, count))
                ima = ImageCaptcha(width=random_widths[int(random.random() *
                                                           36)],
                                   height=32,
                                   font_sizes=(26, 28, 30))
                ima = ima.create_captcha_image(chars=captcha,
                                               color='white',
                                               background='black')
                ima.save(fn)
                count += 1
Beispiel #13
0
def gen_captcha_text_and_image():
    """
    生成字符对应的验证码
    :return:
    """
    image = ImageCaptcha(IMAGE_WIDTH, IMAGE_HEIGHT)

    captcha_text = random_captcha_text()
    captcha_text = ''.join(captcha_text)

    #captcha = image.generate(captcha_text)

    #background = random_color(238, 255)
    #color = random_color(0, 200, random.randint(220, 255))
    captcha = image.create_captcha_image(captcha_text, (0, 124, 255),
                                         (255, 255, 255))
    #image.create_noise_dots(im, color)
    #image.create_noise_curve(im, color)
    #captcha = captcha.filter(ImageFilter.SMOOTH)

    #captcha_image = Image.open(captcha)
    captcha_image = np.array(captcha)
    return captcha_text, captcha_image
Beispiel #14
0
def generate_captcha(characters, length, width=130, height=70):
    generator = ImageCaptcha(width=width, height=height)
    captcha_str = "".join([random.choice(characters) for j in range(length)])
    img = generator.create_captcha_image(captcha_str, (65, 105, 225),
                                         (255, 255, 255))
    return img, captcha_str
Beispiel #15
0
def get_captcha(num, path):
    font_sizes = [x for x in range(40, 45)]
    for i in range(num):
        print(i)
        imc = ImageCaptcha(get_width(), get_height(), font_sizes=font_sizes)
        name = get_string()
        def random_color(start, end, opacity=None):
            red = random.randint(start, end)
            green = random.randint(start, end)
            blue = random.randint(start, end)
            if opacity is None:
                return (red, green, blue)
            return (red, green, blue, opacity)
        background = random_color(255, 255)
        color = random_color(190, 190, random.randint(255, 255))
        image = Image.new('RGB', (get_width(), get_height()), background)
        draw = Draw(image)

        def _draw_character(c):
            font = random.choice(imc.truefonts)
            w, h = draw.textsize(c, font=font)

            dx = random.randint(0, 0)
            dy = random.randint(0, 0)
            im = Image.new('RGBA', (w + dx, h + dy))
            Draw(im).text((dx, dy), c, font=font, fill=color)

            # rotate
            im = im.crop(im.getbbox())
            im = im.rotate(random.uniform(-1, 1), Image.BILINEAR, expand=1)

            # warp
            dx = w * random.uniform(0.1, 0.3)
            dy = h * random.uniform(0.2, 0.3)
            x1 = int(random.uniform(-dx, dx))
            y1 = int(random.uniform(-dy, dy))
            x2 = int(random.uniform(-dx, dx))
            y2 = int(random.uniform(-dy, dy))
            w2 = w + abs(x1) + abs(x2)
            h2 = h + abs(y1) + abs(y2)
            data = (
                x1, y1,
                -x1, h2 - y2,
                w2 + x2, h2 + y2,
                w2 - x2, -y1,
            )
            im = im.resize((w2, h2))
            im = im.transform((w, h), Image.QUAD, data)
            return im

        images = []
        for c in name:
            # if random.random() > 0.5:
            #     images.append(_draw_character(" "))
            images.append(_draw_character(c))

        text_width = sum([im.size[0] for im in images])

        width = max(text_width, imc._width)
        image = image.resize((width, imc._height))

        average = int(text_width / len(name))
        rand = int(0.25 * average / 100)
        offset = int(average * 0.1)
        table  =  []
        for  i  in  range( 256 ):
            table.append( i * 100.97 )
        for im in images:
            w, h = im.size
            mask = im.convert('L').point(table)
            image.paste(im, (offset, int((imc._height - h) / 2)), mask)
            offset = offset + w + random.randint(-rand, 0)

        if width > imc._width:
            image = image.resize((imc._width, imc._height))

        image = imc.create_captcha_image(name, color, background)
        image = image.filter(ImageFilter.SMOOTH)
        image.save(path + name + '_' + str(int(time.time())) + ".jpg")
    num = [str(i) for i in range(10)] + [chr(i) for i in range(65, 91)
                                         ] + [chr(i) for i in range(97, 123)]
    # num = [str(i) for i in range(9)] + [chr(i) for i in range(97, 122)]
    print(num)
    num_create = 2000  #总的图片数
    num_txt = 4  #单个验证码数量

    # image = ImageCaptcha(width=120, height=40, font_sizes=(25,28))
    img = ImageCaptcha(
        height=70,
        fonts=['data/Deng.ttf', 'data/simfang.ttf', 'data/simhei.ttf'],
        font_sizes=(30, 43))
    img = ImageCaptcha(height=70, fonts=['data/Deng.ttf'], font_sizes=(40, 43))
    img = ImageCaptcha(height=70, font_sizes=(30, 38))
    for i in list(range(num_create)):
        txt = ''.join(random.sample(num, num_txt))  #验证码内容
        # image.generate(txt)
        # image.write(txt,os.path.join(dst_folder, txt+'.jpg'))
        # continue
        background = random_color(238, 255)
        color = random_color(10, 200, random.randint(220, 255))
        background = (255, 255, 255)
        background_noise = (241, 241, 215)
        color = (95, 137, 180)
        im = img.create_captcha_image(txt, color, background)
        img.create_noise_dots(im, background_noise, width=5)
        # imag.create_noise_curve(im, color)
        im = create_noise_curve(im, color)
        # print(txt)
        # im = im.filter(ImageFilter.SMOOTH)
        im.save(os.path.join(dst_folder, txt + '.jpg'))