1

I want to load an image file into memory

In Delphi language there is a class named TMemoryStream that you can use to load some data to memory, how I should use something like MemoryStream in Python language ?

G3ntle
  • 51
  • 1
  • 6

3 Answers3

4

Having a quick look at TMemoryStream in the Delphi docs, it looks like the class is about producing a block of memory that is enhanced with file-like IO operators.

The equivalent class in Python can be found in the StringIO module: https://docs.python.org/2/library/stringio.html

(c)StringIO is not strictly a block of memory, as Python doesn't really expose raw memory as a concept. It can however be used to implement files in RAM, for example, creating an image file as a string for PIL (or Pillow), and then write it out to a browser as part of a CGI script. https://stackoverflow.com/a/41501060/7811466

Community
  • 1
  • 1
Gareth Pulham
  • 654
  • 4
  • 10
  • 1
    Or `io.BytesIO`. Regardless, probably want to specify a Python 3 solution (`stringio` is `io.StringIO` in Python 3). – juanpa.arrivillaga Apr 24 '17 at 21:33
  • There's no indication of needing a Python 3 solution here, and Python 2 is more widely used (and certainly I'm more confident in explaining it with 2). – Gareth Pulham Apr 24 '17 at 21:37
  • Python 2 is at its end-of-life and will no longer be supported after 2020. Generally, I assume Python 3 unless Python 2 is stated explicitly. – juanpa.arrivillaga Apr 24 '17 at 21:39
  • We could argue for a long time about the lifecycle of the language, but statistically I'm still more confident in this being a question related to 2 than it is to 3, and that still doesn't account for my own personal preferences in answering this question. Should you feel strongly about it, you're entirely welcome to submit your own answer relevant to 3. – Gareth Pulham Apr 24 '17 at 21:43
  • 1
    Fair enough, but you should at the very least be explicit that your solution is Python 2 only, and that there is a different API in Python 3, if the tag is the generic [python] tag without any specific tags. – juanpa.arrivillaga Apr 24 '17 at 21:46
  • io.BytesIO was exactly what I needed to solve my issue! Thanks for mentioning it, I've been looking for hours for a solution! Everyone says to use io.StringIO but it was actually io.BytesIO that solved it! – Aalawlx Mar 24 '22 at 18:44
4

I don't know TMemoryStream but this is how you would read a binary file into RAM (assuming Python 3):

with open('filename', mode='rb') as infile:
    data = infile.read()
wonce
  • 1,893
  • 12
  • 18
1

There are many packages for image manipulation in python. One of them is PIL, here is an example:

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))

See a Jupyter Notebook with this code, here!

Sidon
  • 1,316
  • 2
  • 11
  • 26