python - `PIL.Image.Show()`临时存储图片在哪里,之后会被删除吗?

标签 python python-imaging-library

我正在用 Python 编写一个命令行日记应用程序,我希望能够将图像作为字节数组存储在加密的 SQLite 数据库中(使用解决方案 here )。

然后,为了显示图像,我将使用 PIL.Image.fromarray(...) 加载字节数组,并使用 PIL.Image.show(...) 显示它,但在阅读 documation 后我很担心正如它所说,它临时存储图像:

PIL.Image.Show documentation

显然这是不可取的,因为该应用程序的目的是以加密形式存储元素,我担心应用程序退出后它会将这些图像存储在磁盘上。但为了解决这个问题,我似乎无法找到它临时存储图像的位置以及之后是否将其删除。我已经检查了 /tmp/ 目录。

所以我的问题是 PIL.Image.show(...) 在哪里临时存储图像,之后它们会以未加密的格式留在我的计算机上吗?

最佳答案

查看 source 后在 PIL.Image.show(...) 方法中,该方法似乎将图像临时写入磁盘(如文档所述),然后在使用图像打开后立即删除查看器。

例如,macOS 的方法是:

def show_file(self, file, **options):
    """Display given file"""
    fd, path = tempfile.mkstemp()
    with os.fdopen(fd, "w") as f:
        f.write(file)
    with open(path, "r") as f:
        subprocess.Popen(
            ["im=$(cat); open -a Preview.app $im; sleep 20; rm -f $im"],
                shell=True,
                stdin=f,
            )
    os.remove(path)
    return 1

这使用 tempfile.mkstemp([suffix=''[, prefix='tmp'[, dir=None[, text=False]]]]) 方法创建临时文件。 documentation状态:

If dir is specified, the file will be created in that directory; otherwise, a default directory is used. The default directory is chosen from a platform-dependent list, but the user of the application can control the directory location by setting the TMPDIR, TEMP or TMP environment variables.

由于未指定 dir,因此使用默认目录,如下选择:(声明 here ):

When set to a value other than None, this variable defines the default value for the dir argument to all the functions defined in this module.

If tempdir is unset or None at any call to any of the above functions, Python searches a standard list of directories and sets tempdir to the first one which the calling user can create files in. The list is:

  1. The directory named by the TMPDIR environment variable.
  2. The directory named by the TEMP environment variable.
  3. The directory named by the TMP environment variable.
  4. A platform-specific location:
    • On RiscOS, the directory named by the Wimp$ScrapDir environment variable.
    • On Windows, the directories C:\TEMP, C:\TMP, \TEMP, and \TMP, in that order.
    • On all other platforms, the directories /tmp, /var/tmp, and /usr/tmp, in that order.
  5. As a last resort, the current working directory.

关于python - `PIL.Image.Show()`临时存储图片在哪里,之后会被删除吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61867415/

相关文章:

python - 使用 PIL 在循环中一次将文本移动到一张图像下方

python - 如何在 PIL 中使用 unicode 字符?

python - 子图是重叠的轴标签

python - simplejson.loads() 获取无效\转义 : 'x'

python - 仅获取与 Django 查询集相关的模型

python - 给 `PIL.Image.frombytes` 指定什么大小

python - cross_val_score 与 .score 的回归评分结果显着不同

python - 字典应该按公司顺序存储 key 吗?

python - 从 URL 检索 JPG 图片 (Python)

python - 如何将 PIL ImageDraw 转换为 Image