简体   繁体   English

Django将图像保存在文件夹中

[英]Django save image in folder

I´ve got a piece of code that creates an image using matplotlib in Django and saves it to the root directory. 我有一段代码可以在Django中使用matplotlib创建图像并将其保存到根目录中。 I need to change the folder where matplotlib saves the image to /static/img folder. 我需要更改matplotlib将图像保存到/ static / img文件夹的文件夹。

    if (len(funcion) == 2):
        plotter = plot_regions([
            [(lambda x: (matrizRestricciones[0][2]-matrizRestricciones[0]
            [0]*x)/matrizRestricciones[0][1],True),
            (lambda x: (matrizRestricciones[1][2]-matrizRestricciones[1]
            [0]*x)/matrizRestricciones[1][1],True)]], xlim=(0, 10), ylim=(0,10))
        plt.grid()
        plt.savefig("/static/img/imagen.png")
        plt.close()

Any idea how to save them there? 知道如何将它们保存在那里吗?

Thanks in advance. 提前致谢。

Try this: 尝试这个:

import os
from django.conf import settings

# ... your code ...
# ...
 plt.savefig(os.path.join(settings.BASE_DIR, 'static/img/imagen.png'))

Note: From your code, it appears that while you're saving the image you're not giving it a unique name. 注意:从您的代码看来,在保存图像时,您并没有为其赋予唯一的名称。 So, if you create a new image, it will replace the older image. 因此,如果创建新图像,它将替换旧图像。 If that is the desired behaviour, ignore this. 如果这是所需的行为,请忽略此。 If not, you can use uuid.uuid4 to generate unique names for your images. 如果没有,则可以使用uuid.uuid4为图像生成唯一的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM