Python изображение в байты

Python изображение в байты

Subreddit for posting questions and asking for general advice about your python code.

I have a small png image with transparency: (16×16) pixels, bitdepth = 8 , and the size of 326 bytes.

with open(«add.png», «rb») as fileobj: data = fileobj.read()

then I just want to store that data somewhere in a script:

and somehow place it in a wxpython gui:

self.m_toolPlus = self.m_toolBar1.AddLabelTool( wx.ID_ANY, u»plus», wx.Bitmap(«add.png»), wx.NullBitmap, wx.ITEM_NORMAL, wx.EmptyString, wx.EmptyString, None )

In the bitmap bit. I’ve been trying to work this out all day but I just can’t find a solution.

Somehow modules don’t seem to work like they used to do, for some reason.

from PIL import Image import numpy as np im = Image.open(‘add.png’) # Can be many different formats. pix = im.load() print(im.size) # Get the width and hight of the image for iterating over print(pix[x,y]) # Get the RGBA Value of the a pixel of an image

but all it does for me is print a singular value for each pixel, shouldn’t that be a tuple?

here are the bytes of the image in pastebin: https://pastebin.com/VhLfMRcu

apparently to the bytes of the transparency layer I can do:

img = PIL.Image.open(imFile, ‘r’) img.info[‘transparency’]

when I try to get a picture back from the bytes:

with open(«add.png», «rb») as imageFile: f = imageFile.read() Image.frombytes(«P», (16, 16), f)

I get a weird looking picture, while the modes «RGB»,»RGBA» say that there isn’t enough image data.

Источник

Convert Image Into Byte Array in Python

Python’s built-in bytearray function allows us to convert arrays to byte arrays. Because an image is just an array of numbers, we will leverage this method to convert images into a byte array.

What is Python bytearray?

The bytearray method returns a Python bytearray object, an array of the given bytes. The bytearray class is a mutable sequence of integers from 0 to 255.

The general syntax for the bytearray method is given below:

bytearray([source[, encoding[, errors]]])

The bytearray method takes three optional parameters- source, encoding, and errors where

  • source is provided as initialization to the array. This parameter can take different data types – strings, integers, or an iterable,
  • encoding – encoding to be used if the source is a string,
  • errors – action to be taken whenever encoding fails for a given character.

Based on our application, we will investigate how bytearray works with integers and iterables (like lists and arrays) as the source. It is important to note that bytearray objects are always generated by calling the constructor since they lack a specialized literal syntax.

If the source is an integer, the array will have that size and be initialized with null bytes. The array can only contain integer elements between 0 and 256 (exclusive) when a source is an iterable object.

Источник

Introduction

Sometimes, we may want an in-memory jpg or png image that is represented as binary data. But often, what we have got is image in OpenCV (Numpy ndarray) or PIL Image format. In this post, I will share how to convert Numpy image or PIL Image object to binary data without saving the underlying image to disk.

If the image file is saved on disk, we can read it directly in binary format with open() method by using the b flag:

Now the image will be read from disk to memory and is still in binary format.

What if we want to resize the original image and convert it to binary data, without saving the resized image and re-read it from the hard disk? How should we do it?

Convert image to bytes

We can do it with the help of OpenCV or PIL.

OpenCV

This is how to achieve that in OpenCV:

A little explanation here. imencode() will encode the Numpy ndarray in the specified format. This method will return two values, the first is whether the operation is successful, and the second is the encoded image in a one-dimension Numpy array.

Then you can convert the returned array to real bytes either with the tobytes() method or io.BytesIO() . We can finally get the byte_im . It is the same with saving the resized image in hard disk and then reading it in binary format, but the saving step is removed and all the operation is done in memory.

PIL

If you like to use PIL for image processing. You can use the following code:

In the above code, we save the im_resize Image object into BytesIO object buf . Note that in this case, you have to specify the saving image format because PIL does not know the image format in this case. The bytes string can be retrieved using getvalue() method of buf variable.

References

Источник

Как преобразовать PIL объект в Bytes?

dimonchik2013

Эта часть прекрасно работает. Мне нужно отрезать картинку, потом дальше её отправить post запросом через requests multipart/form-data. Как преобразовать PIL Image объект в двоичные данные, чтобы отправить их так, как указано в последней строке кода?

dimonchik2013

YardalGedal

dimonchik2013, без сохранения в левый файл. Вы не совсем понимаете суть:

Пускай у меня есть Pil Image-объект
image = Image.new(. )

мне нужно его отправить как изображение через requests, это можно как-то сделать?

dimonchik2013

ну, если ты такой крутой, то без промежуточных файлов нужно уметь работать с буфером, который Bytesio

например, не забывать за
image_content.seek(0)

YardalGedal

dimonchik2013, .seek(0) оказалось решением, но, так как вы беспричинно начали выпендриваться, решением не отмечу.

sanya84

Max Payne, Как бы там не было а всё таки человек вам помог, и вы обязаны отметить ответ как решение вашего вопроса!

dimonchik2013

sanya84, не стоит, право выпендриваться недорогое )), Вы же понимаете, что вопросы у него еще будут ))))

Источник

Читайте также:  Javascript диалоговое окно confirm
Оцените статью