tengke 发表于 2023-6-13 10:44:59

图片验证码问题

from app.cs import check_code
from io import BytesIO
def yzm(request):
    img,code_staing = check_code()
    print(code_staing)

    stream = BytesIO()
    img.save(stream, 'png')
    stream.getvalue()
    returnHttpResponse(stream.getvalue())


这个代码 可以在前台 正常显示内容 不过是在内存里面的


如果我要把 code_staing这个图片验证码 写在指的的文件里面要怎么做呢

不是cs.py文件里面 是调用cs 里面

isdkz 发表于 2023-6-13 10:45:00

您的代码显示了如何生成一个验证码,并且在内存中创建了一个图像流,然后将这个图像流返回给HttpResponse。但是如果你想把验证码图片保存到一个特定的文件,你可以在Python的 PIL 库的 Image 对象上调用 save() 方法,像这样:

from app.cs import check_code
from io import BytesIO
def yzm(request):
    img,code_string = check_code()
    print(code_string)

    # Save the image to a file
    img.save('/path/to/your/file.png')

    stream = BytesIO()
    img.save(stream, 'png')
    stream.getvalue()
    return HttpResponse(stream.getvalue())


在上面的代码中, /path/to/your/file.png是你想要保存图像的文件的路径。请确保你有写入该文件的权限,且文件路径的目录存在。你也可以将 code_string (验证码)一同写入文件,但它需要被写入一个文本文件,这将涉及到一个不同的处理方式。

如果你想将验证码一同写入,可以考虑以下代码:

from app.cs import check_code
from io import BytesIO
def yzm(request):
    img,code_string = check_code()
    print(code_string)

    # Save the image to a file
    img.save('/path/to/your/file.png')

    # Save the code_string to a text file
    with open('/path/to/your/textfile.txt', 'w') as f:
      f.write(code_string)

    stream = BytesIO()
    img.save(stream, 'png')
    stream.getvalue()
    return HttpResponse(stream.getvalue())


在这里, /path/to/your/textfile.txt是你想要保存验证码的文本文件的路径。这段代码将把验证码写入一个文本文件中。
页: [1]
查看完整版本: 图片验证码问题