wolph / numpy-stl

Simple library to make working with STL files (and 3D objects in general) fast and easy.
http://numpy-stl.readthedocs.org/
BSD 3-Clause "New" or "Revised" License
624 stars 105 forks source link

Mesh.from_file from BytesIO / SpooledTemporaryFile #146

Closed mrtnbrst closed 3 years ago

mrtnbrst commented 3 years ago

Is it possible to use an in memory object like BytesIO to load a numpy-stl mesh?

Right now there seems to be an issue with the use of numpy.fromfile in https://github.com/WoLpH/numpy-stl/blob/92900a54dd4446bacc827fb11b958e8ea6416c56/stl/stl.py#L128. This numpy/numpy#2230 addresses this behaviour and potential workarounds like numpy.frombuffer .

import base64
import io
import tempfile

with open(r"C:\Users\user\Moon.stl", "rb") as f:
    decoded = base64.b64decode(f.read())

data = data = io.BytesIO(decoded)

mesh.Mesh.from_file("Moon.stl", fh=data)

"""
mesh.Mesh.from_file("test", fh=data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\user\miniconda3\envs\streamlit\lib\site-packages\stl\stl.py", line 326, in from_file
    fh, mode=mode, speedups=speedups)
  File "C:\Users\user\miniconda3\envs\streamlit\lib\site-packages\stl\stl.py", line 95, in load
    name, data = cls._load_binary(fh, header)
  File "C:\Users\user\miniconda3\envs\streamlit\lib\site-packages\stl\stl.py", line 128, in _load_binary
    return name, numpy.fromfile(fh, dtype=cls.dtype, count=count)
io.UnsupportedOperation: fileno
"""

fh = tempfile.SpooledTemporaryFile(decoded)
mesh.Mesh.from_file("Moon.stl", fh=fh)

"""
mesh.Mesh.from_file("Moon.stl", fh=fh)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\user\miniconda3\envs\streamlit\lib\site-packages\stl\stl.py", line 326, in from_file
    fh, mode=mode, speedups=speedups)
TypeError: cannot unpack non-iterable NoneType object
>>>
"""

System: Windows 10, 10.0.17134 Build 17134

wolph commented 3 years ago

Wow... crazy that an issue since 2012 still hasn't been fixed :P

In any case, it's easy enough to fix so a new release will be coming soon. The new version is on develop

mrtnbrst commented 3 years ago

Thank you!

wolph commented 3 years ago

The new release is online :)