Create temporary file in memory

1

I would like to know if there is a way to make a file saved in memory without having to write it to disk. for example:

imagen = wx.Bitmap('imagen.png', wx.BITMAP_TYPE_ANY)

Now I want to take the image data and save it in memory, wx.Bitmap has a function to save the image:

imagen.SaveFile('nombre_Archivo.png',wx.BITMAP_TYPE_PNG) 

Is there any way to save the image in memory without writing to disk ?, something like:

imagen.SaveFile('espacio en memoria',wx.BITMAP_TYPE_PNG)
    
asked by Krilosax 04.12.2018 в 14:42
source

1 answer

3

Yes you can, using the module io , but I still do not know if it will work for what you propose.

The io module allows you to create objects that behave as if they were files and can be passed as parameters to the functions that wait for a file, but do not access the disk but to memory.

For example:

import io

f = io.BytesIO()
imagen.SaveFile(f, wx.BITMAP_TYPE_PNG)

...

data = f.getvalue()

The problem is that wx.Bitmap.SaveFile() does not support a file as a parameter, but a file name , which is not the same. Internally it will open that name to obtain the file in which to dump the bytes. If you could access in some way to that machinery that dumps the bytes by passing the object BytesIO instead of the file, the problem would be solved. You should look at the API and maybe the implementation of WxPython.

Update

Although the class wx.BitMap does not provide low level methods for accessing the stream of bytes, the class wx.Image instead yes. Therefore, the following should, in principle, work.

import io
import wx

imagen = wx.Image()
imagen.LoadFile('imagen.png')

# Tal vez procesarla...
# Y ahora guardar el resultado en memoria

f = io.BytesIO()
imagen.SaveFile(f, wx.BITMAP_TYPE_PNG)

# Los bytes los tenemos aqui:
data = f.getvalue()

# Comprobación de que la cosa va bien
print(data[:10])

The above shows:

b'\x89PNG\r\n\x1a\n\x00\x00'

that in principle looks good.

    
answered by 04.12.2018 / 15:57
source