Bytes to bufferedreader python

Преобразовать байты в объект BufferedReader в Python?

Название этого вопроса такое же, как у этого, и я проголосовал за повторную постановку вопроса.

Я хочу преобразовать байтовый объект в объект BufferedReader, и вот мои попытки (после обращения ко многим статьям):

import numpy as np from PIL import Image as PILImage from io import BytesIO img_np = np.asarray([[[16, 16, 16], [2, 2, 2], [0, 0, 0], [6, 6, 6], [8, 8, 8], [0, 0, 0], [21, 21, 21], [3, 3, 3], [0, 0, 0], [62, 62, 62]], [[0, 0, 0], [71, 71, 71], [142, 142, 142], [107, 107, 107], [99, 99, 99], [101, 101, 101], [4, 4, 4], [86, 86, 86], [99, 99, 99], [146, 146, 146]], [[162, 162, 162], [203, 203, 203], [192, 192, 192], [228, 228, 228], [191, 191, 191], [178, 178, 178], [222, 222, 222], [200, 200, 200], [198, 198, 198], [182, 182, 182]], [[117, 117, 117], [178, 178, 178], [199, 199, 199], [214, 214, 214], [222, 222, 222], [208, 208, 208], [255, 255, 255], [251, 251, 251], [219, 219, 219], [255, 255, 255]], [[0, 0, 0], [0, 0, 0], [80, 80, 80], [169, 169, 169], [193, 193, 193], [238, 238, 238], [239, 239, 239], [243, 243, 243], [254, 254, 254], [230, 230, 230]], [[20, 20, 20], [20, 20, 20], [9, 9, 9], [1, 1, 1], [130, 130, 130], [194, 194, 194], [216, 216, 216], [255, 255, 255], [252, 252, 252], [255, 255, 255]], [[9, 9, 9], [0, 0, 0], [0, 0, 0], [0, 0, 0], [3, 3, 3], [44, 44, 44], [191, 191, 191], [217, 217, 217], [248, 248, 248], [225, 225, 225]], [[0, 0, 0], [11, 11, 11], [3, 3, 3], [11, 11, 11], [6, 6, 6], [15, 15, 15], [0, 0, 0], [153, 153, 153], [255, 255, 255], [253, 253, 253]], [[0, 0, 0], [5, 5, 5], [1, 1, 1], [4, 4, 4], [8, 8, 8], [4, 4, 4], [3, 3, 3], [0, 0, 0], [159, 159, 159], [241, 241, 241]], [[10, 10, 10], [9, 9, 9], [6, 6, 6], [2, 2, 2], [0, 0, 0], [0, 0, 0], [3, 3, 3], [20, 20, 20], [0, 0, 0], [185, 185, 185]]]) im = PILImage.fromarray(img_np.astype(np.uint8)) # im.save('./temp.jpeg', "JPEG") # f = open('./temp.jpeg', 'rb') # print(type(f)) # b_handle = io.BytesIO() im.save(b_handle, format="JPEG") # b = im.tobytes() print(type(b_handle)) b = b_handle.read() print(type(b)) print(b) im.save(b_handle, format="JPEG") b_br = io.BufferedReader(b_handle) print(type(b_br)) b = b_br.read() print(type(b)) print(b) 

Результат выглядит следующим образом:

Читайте также:  Portable python pip install

Кажется, что файл вроде объектов пустой. Я знаю, что для b_handle я могу получить значение с помощью b_handle.getvalue() , но для буферизованного чтения он не работает как файловый объект.

Как я могу преобразовать байтовую строку в объект буферизованного чтения так же, как я открываю файл?

Источник

Convert Bytes into BufferedReader object in Python?

You are almost there. Once you save the image bytes into the buffer you need to seek (Change stream position) to byte offset 0 prior to the read call.

b_handle = io.BytesIO() im.save(b_handle, format="JPEG") b_handle.seek(0) b_handle.name = "temp.jpeg" b_br = io.BufferedReader(b_handle) b = b_br.read() 
>>> from io import BytesIO, BufferedReader >>> >>> b_handle = BytesIO() >>> b_handle.write(b"Hello World") 11 >>> b_handle.seek(0) # This is important. 0 >>> br = BufferedReader(b_handle) >>> br >>> br.read() b'Hello World' 

Abdul Niyas P M 13686

  • How to convert bytes containing a string of a list into a Python object?
  • convert String to Bytes object for hmac.new() in python 3
  • How to convert a «custom class»-based singleton object programmatically into a python module?
  • How to convert API timestamp into python datetime object
  • How can you convert a Python identifier into a number?
  • beginner python translator: I am unable to convert a list from shelve module into a string
  • How to convert a string into a set of keystrokes in python on OSX
  • Convert python list object to an array
  • How to convert XML Files into Text files (YOLOV3 Format) for object detection
  • Convert HTML String Tag into String Python
  • Convert spanish date into a pandas datetime object
  • Get Image Object size in Python in Bytes — BadRequest Error in Azure
  • Fetch json value correctly and convert into integers using python3 and upload directly into database but in python code there is some error generated
  • Is it possible to add raw bytes to a TarFile object in python 3?
  • How do I convert a VB delegate into a python event handler?
  • python convert string to bytes error: ValueError: bytes too long
  • Convert repetitive pattern into JSON file with multiple arrays in Python
  • im working with foursquare library in python 3 and trying to convert my query which is a python dictionary into json and encode it
  • How can I convert a pcap into CSV using python
  • Python — load an in-memory ZipFile object as bytes
  • python convert list of string into list intgers
  • Temperature conversion in Python: How to convert int (0 — 255) which is a byte object to degrees Celsius in Python
  • How to convert a Python ‘bytes’ object to ctypes ‘POINTER(c_byte)’
  • How do you convert a timestamp into a datetime in python with the correct timezone?
  • Convert matlab code into python for matrix creation
  • How to convert a string input into a nested list in python without importing any module?
  • How to convert raw images into png using python
  • Python — converting a string object into a ctypes (unsigned char *)
  • Convert CFString into Python string
  • How to convert HTML CSS class into style in pure python — what kind of library could be used on GAE
  • Convert flat data into a hierarchical python list
  • Python Basics: How to convert a list containing an int into a plain int?
  • Convert this python dictionary into JSON format?
  • How to convert a list of words into sentences in python
  • Python convert list into Dictionary with key value
  • Convert a R code into Python script
  • How to convert a dictionary of strings into a block of text with python
  • Why does Python convert 0’s into None objects?
  • Python — How to convert only numbers in a mixed list into float?
  • convert first column of data from text file into a list in python
  • How to convert set into dict in python
  • The most efficient way to convert a string with keys and values into a python dict
  • Python — Convert list item into unicode if item is string
  • Python convert list of one element into string with bracket
  • Convert a JSON bytes object
  • Convert list into dictionary in python
  • python trick needed to convert dictionary of functions into dictionary of results
  • convert list of class objects into json in python or django
  • Python coding to convert US dollars into Japanese Yen failed
  • strptime() does not convert string to datetime object in Python 3.6

More Query from same tag

  • LDA visualization [ import_optional_dependency() got an unexpected keyword argument ‘errors’ ]
  • pygame.mixer sound not playing when script run from command line
  • Extract Video Frames from SDP Output
  • Text Extraction from pdf image file
  • psycopg2 INSERT INTO execute not returning result
  • I have a list of numbers where the 1st digit is appended to a new list, then last, then 2nd, then 2nd last and so on
  • Re-referencing a large number of functions in python
  • How does cython improve performance of pure python code
  • Create and save list to an excel file
  • Python equivalent of join for QList c++
  • Different sound playing modules not working
  • Python __init__ file can’t import modules
  • Django admin how to show a progress bar in percentage
  • pySerial : Can’t read data more than 8 characters
  • Conditional append of a list
  • How to check if list element is present in array in python
  • Programming thunderbird Email Client?
  • python getting Symbol not found: __PyCodecInfo_GetIncrementalDecoder
  • Run WCID With Python 2
  • Why does Gmail API fail with a 403 error, using code that works properly for Google Calendar API?
  • How to use IPython module in web IDEs
  • win32: get current DEVMODE of a monitor
  • z3: How to solve for combinations for a set of constants?
  • Google search results limits
  • Surprising output of simple Python list program
  • Get nosetests configuration options
  • Multiple modules , single instance of a class — Python
  • 3d scatter plot with color in matplotlib
  • Scrapy: Scraping very select URLs
  • Python connect to django piston
  • FontForge Python extension: Can’t get gsub_multiple lookup to work
  • How to add spaces between the squares on a squarify plot
  • Continue while loop after return True
  • Classes in Python
  • Transformers: How to use CUDA for inferencing?

Источник

Convert Bytes into BufferedReader object in Python?

The title of this question is the same as this one, and I have voted to reopoen the question.

I want to convert a byte object into a BufferedReader one, and here is my attempts(after referring to many articles):

import numpy as np from PIL import Image as PILImage from io import BytesIO img_np = np.asarray([[[16, 16, 16], [2, 2, 2], [0, 0, 0], [6, 6, 6], [8, 8, 8], [0, 0, 0], [21, 21, 21], [3, 3, 3], [0, 0, 0], [62, 62, 62]], [[0, 0, 0], [71, 71, 71], [142, 142, 142], [107, 107, 107], [99, 99, 99], [101, 101, 101], [4, 4, 4], [86, 86, 86], [99, 99, 99], [146, 146, 146]], [[162, 162, 162], [203, 203, 203], [192, 192, 192], [228, 228, 228], [191, 191, 191], [178, 178, 178], [222, 222, 222], [200, 200, 200], [198, 198, 198], [182, 182, 182]], [[117, 117, 117], [178, 178, 178], [199, 199, 199], [214, 214, 214], [222, 222, 222], [208, 208, 208], [255, 255, 255], [251, 251, 251], [219, 219, 219], [255, 255, 255]], [[0, 0, 0], [0, 0, 0], [80, 80, 80], [169, 169, 169], [193, 193, 193], [238, 238, 238], [239, 239, 239], [243, 243, 243], [254, 254, 254], [230, 230, 230]], [[20, 20, 20], [20, 20, 20], [9, 9, 9], [1, 1, 1], [130, 130, 130], [194, 194, 194], [216, 216, 216], [255, 255, 255], [252, 252, 252], [255, 255, 255]], [[9, 9, 9], [0, 0, 0], [0, 0, 0], [0, 0, 0], [3, 3, 3], [44, 44, 44], [191, 191, 191], [217, 217, 217], [248, 248, 248], [225, 225, 225]], [[0, 0, 0], [11, 11, 11], [3, 3, 3], [11, 11, 11], [6, 6, 6], [15, 15, 15], [0, 0, 0], [153, 153, 153], [255, 255, 255], [253, 253, 253]], [[0, 0, 0], [5, 5, 5], [1, 1, 1], [4, 4, 4], [8, 8, 8], [4, 4, 4], [3, 3, 3], [0, 0, 0], [159, 159, 159], [241, 241, 241]], [[10, 10, 10], [9, 9, 9], [6, 6, 6], [2, 2, 2], [0, 0, 0], [0, 0, 0], [3, 3, 3], [20, 20, 20], [0, 0, 0], [185, 185, 185]]]) im = PILImage.fromarray(img_np.astype(np.uint8)) # im.save('./temp.jpeg', "JPEG") # f = open('./temp.jpeg', 'rb') # print(type(f)) # b_handle = io.BytesIO() im.save(b_handle, format="JPEG") # b = im.tobytes() print(type(b_handle)) b = b_handle.read() print(type(b)) print(b) im.save(b_handle, format="JPEG") b_br = io.BufferedReader(b_handle) print(type(b_br)) b = b_br.read() print(type(b)) print(b) 

It seems that the file like objects are empty. I know that for the b_handle I can get the value by b_handle.getvalue() but for the bufferedreader it doesn’t work as a file object.

How can I convert a byte string into a bufferedreader object, the same as I open a file?

Answer

davy.ai

To convert a byte string into a BufferedReader object, you can use the io.BufferedReader(io.BytesIO(byte_string)) constructor. Here’s an example using the code from the question:

import numpy as np from PIL import Image as PILImage import io img_np = np.asarray([[[16, 16, 16], [2, 2, 2], [0, 0, 0], [6, 6, 6], [8, 8, 8], [0, 0, 0], [21, 21, 21], [3, 3, 3], [0, 0, 0], [62, 62, 62]], [[0, 0, 0], [71, 71, 71], [142, 142, 142], [107, 107, 107], [99, 99, 99], [101, 101, 101], [4, 4, 4], [86, 86, 86], [99, 99, 99], [146, 146, 146]], [[162, 162, 162], [203, 203, 203], [192, 192, 192], [228, 228, 228], [191, 191, 191], [178, 178, 178], [222, 222, 222], [200, 200, 200], [198, 198, 198], [182, 182, 182]], [[117, 117, 117], [178, 178, 178], [199, 199, 199], [214, 214, 214], [222, 222, 222], [208, 208, 208], [255, 255, 255], [251, 251, 251], [219, 219, 219], [255, 255, 255]], [[0, 0, 0], [0, 0, 0], [80, 80, 80], [169, 169, 169], [193, 193, 193], [238, 238, 238], [239, 239, 239], [243, 243, 243], [254, 254, 254], [230, 230, 230]], [[20, 20, 20], [20, 20, 20], [9, 9, 9], [1, 1, 1], [130, 130, 130], [194, 194, 194], [216, 216, 216], [255, 255, 255], [252, 252, 252], [255, 255, 255]], [[9, 9, 9], [0, 0, 0], [0, 0, 0], [0, 0, 0], [3, 3, 3], [44, 44, 44], [191, 191, 191], [217, 217, 217], [248, 248, 248], [225, 225, 225]], [[0, 0, 0], [11, 11, 11], [3, 3, 3], [11, 11, 11], [6, 6, 6], [15, 15, 15], [0, 0, 0], [153, 153, 153], [255, 255, 255], [253, 253, 253]], [[0, 0, 0], [5, 5, 5], [1, 1, 1], [4, 4, 4], [8, 8, 8], [4, 4, 4], [3, 3, 3], [0, 0, 0], [159, 159, 159], [241, 241, 241]], [[10, 10, 10], [9, 9, 9], [6, 6, 6], [2, 2, 2], [0, 0, 0], [0, 0, 0], [3, 3, 3], [20, 20, 20], [0, 0, 0], [185, 185, 185]]]) im = PILImage.fromarray(img_np.astype(np.uint8)) # Convert image to bytes and read into buffer b = io.BytesIO() im.save(b, format='JPEG') b.seek(0) buf = io.BufferedReader(b) # Read buffer contents data = buf.read() print(type(data)) #

In this example, we first save the image as a byte string using BytesIO , then read the byte string into a BufferedReader using io.BufferedReader(io.BytesIO(byte_string)) . Finally, we read the buffer’s contents using the read() method.

Источник

Оцените статью