openableImage = None if isinstance(inputImage, str): openableImage = inputImage elif isinstance(inputImage, bytes): print("len(inputImage)=%s" % len(inputImage)) openableImage = io.BytesIO(inputImage)
imageFilename = "/Users/crifan/dev/tmp/python/resize_image_demo/hot day.png" imageFileObj = open(imageFilename, "rb") outputImageFilename = "/Users/crifan/dev/tmp/python/resize_image_demo/hot day_600x600.png" beforeTime = datetime.datetime.now() resizeImage(imageFileObj, (600, 600), outputImageFile=outputImageFilename)
<_io.BufferedReader name=’/Users/crifan/dev/tmp/python/resize_image_demo/hot day.png’>
python file object
python check file object type
An object exposing a file-oriented API (with methods such as read() or write()) to an underlying resource. Depending on the way it was created, a file object can mediate access to a real on-disk file or to another type of storage or communication device (for example standard input/output, in-memory buffers, sockets, pipes, etc.). File objects are also called file-like objects or streams.
There are actually three categories of file objects: raw binary files, buffered binary files and text files. Their interfaces are defined in the io module. The canonical way to create a file object is by using the open() function.
A file object able to read and write bytes-like objects. Examples of binary files are files opened in binary mode (‘rb’, ‘wb’ or ‘rb+’), sys.stdin.buffer, sys.stdout.buffer, and instances of io.BytesIO and gzip.GzipFile.
See also text file for a file object able to read and write str objects.
An object that supports the Buffer Protocol and can export a C-contiguous buffer. This includes all bytes, bytearray, and array.array objects, as well as many common memoryview objects. Bytes-like objects can be used for various operations that work with binary data; these include compression, saving to a binary file, and sending over a socket.
Some operations need the binary data to be mutable. The documentation often refers to these as “read-write bytes-like objects”. Example mutable buffer objects include bytearray and amemoryview of a bytearray. Other operations require the binary data to be stored in immutable objects (“read-only bytes-like objects”); examples of these include bytes and a memoryview of a bytes object.”
def isFileObject(fileObj): """"check is file like object or not""" if sys.version_info == 2: return isinstance(fileObj, file) else: # for python 3: # has read() method for: # io.IOBase # io.BytesIO # io.StringIO # io.RawIOBase return hasattr(fileObj, 'read')
imageFileObj = open(imageFilename, "rb") outputImageFilename = "/Users/crifan/dev/tmp/python/resize_image_demo/hot day_600x600.png" resizeImage(imageFileObj, (600, 600), outputImageFile=outputImageFilename) def resizeImage(inputImage, 。。。 elif isFileObject(inputImage): openableImage = inputImage