Skip to content

Commit 38fd9fc

Browse files
committed
RF: Rename serialize to to_bytes, add from_bytes
1 parent ca60a19 commit 38fd9fc

File tree

1 file changed

+33
-18
lines changed

1 file changed

+33
-18
lines changed

nibabel/filebasedimages.py

Lines changed: 33 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,21 @@ def from_filename(klass, filename):
260260
file_map = klass.filespec_to_file_map(filename)
261261
return klass.from_file_map(file_map)
262262

263+
@classmethod
264+
def from_bytes(klass, bstring):
265+
""" Construct image from a byte string
266+
267+
Class method
268+
269+
Parameters
270+
----------
271+
bstring : bytes
272+
Byte string containing the on-disk representation of an image
273+
"""
274+
bio = io.BytesIO(bstring)
275+
file_map = self.make_file_map({'image': bio, 'header': bio})
276+
return klass.from_file_map(file_map)
277+
263278
@classmethod
264279
def from_file_map(klass, file_map):
265280
raise NotImplementedError
@@ -334,6 +349,24 @@ def to_filename(self, filename):
334349
self.file_map = self.filespec_to_file_map(filename)
335350
self.to_file_map()
336351

352+
def to_bytes(self):
353+
""" Return a ``bytes`` object with the contents of the file that would
354+
be written if the image were saved.
355+
356+
Parameters
357+
----------
358+
None
359+
360+
Returns
361+
-------
362+
bytes
363+
Serialized image
364+
"""
365+
bio = io.BytesIO()
366+
file_map = self.make_file_map({'image': bio, 'header': bio})
367+
self.to_file_map(file_map)
368+
return bio.getvalue()
369+
337370
@deprecate_with_version('to_filespec method is deprecated.\n'
338371
'Please use the "to_filename" method instead.',
339372
'1.0', '3.0')
@@ -512,21 +545,3 @@ def path_maybe_image(klass, filename, sniff=None, sniff_max=1024):
512545
if sniff is None or len(sniff[0]) < klass._meta_sniff_len:
513546
return False, sniff
514547
return klass.header_class.may_contain_header(sniff[0]), sniff
515-
516-
def serialize(self):
517-
""" Return a ``bytes`` object with the contents of the file that would
518-
be written if the image were saved.
519-
520-
Parameters
521-
----------
522-
None
523-
524-
Returns
525-
-------
526-
bytes
527-
Serialized image
528-
"""
529-
bio = io.BytesIO()
530-
file_map = self.make_file_map({'image': bio, 'header': bio})
531-
self.to_file_map(file_map)
532-
return bio.getvalue()

0 commit comments

Comments
 (0)