Python中的内存流

2024-09-30 18:12:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把一个图像文件加载到内存中

在Delphi语言中,有一个名为TMemoryStream的类,可以用来将一些数据加载到内存中,我该如何使用Python语言中的MemoryStream?在


Tags: 数据内存语言图像文件delphimemorystreamtmemorystream
3条回答

python中有许多用于图像处理的包。其中之一是PIL,下面是一个例子:

from matplotlib.pyplot import imshow
import numpy as np
from PIL import Image
%matplotlib inline     

# Loada Image
img = Image.open('debian1.png', 'r') 

# Show image:
imshow(np.asarray(img))

看到了Jupyter Notebook with this code, here!在

快速浏览一下Delphi文档中的TMemoryStream,它看起来像是在生成一个内存块,这个内存块通过类似于文件的IO操作符进行了增强。在

Python中的等价类可以在StringIO模块中找到:https://docs.python.org/2/library/stringio.html

(c)严格来说,StringIO并不是一个内存块,因为Python并没有真正将原始内存作为一个概念公开。然而,它可以用于在RAM中实现文件,例如,将图像文件创建为PIL(或Pillow)的字符串,然后将其作为CGI脚本的一部分写入浏览器。 https://stackoverflow.com/a/41501060/7811466

我不知道TMemoryStream,但这是如何将二进制文件读入RAM(假设是python3):

with open('filename', mode='rb') as infile:
    data = infile.read()

相关问题 更多 >