BytesIO from url using open() - python

Can you help me , I need to open my_url in rb mode. Try to do this.
url = "https://my url/" + file_info.file_path
response = requests.get(url)
with open(BytesIO(response.content), "rb") as f: # Open in 'rb' mode for reading it in way like: 010101010
byte = f.read(1)
#some algorithm..............
while byte:
hexadecimal = binascii.hexlify(byte)
decimal = int(hexadecimal, 16)
binary = bin(decimal)[2:].zfill(8)
hiddenData += binary
byte = f.read(1)
Have an error:
Expected str,bytes or.osPathLIke object, not _ioBytesIO
Can you help ,please, how I should open my url in "rb" mode?
I was trying to open an image, using Pillow - it is okay. But as for using open() , I can not do the same. Please..

you're passing a BytesIO object (basically a file handle) where a filename is expected.
So quickfix:
f = BytesIO(response.content)
but better, iterate on a bytes objects using iter either manually (for the start of your algorithm) or automatically (using a for loop which will stop when the iterator is exhausted, so no need for while):
f = iter(response.content)
byte = next(f)
#some algorithm..............
for byte in f:
hexadecimal = binascii.hexlify(byte)
decimal = int(hexadecimal, 16)
binary = bin(decimal)[2:].zfill(8)
hiddenData += binary

Related

Convert PNG to a binary (base 2) string in Python

I Basically want to read a png file and convert it into binary(base 2) and store the converted base 2 value in a string. I've tried so many things, but all of them are showing some error
You can use two approaches:
At first, try to read the image and decode it into base64 format:
import base64
with open("my_image.png", "rb") as f:
png_encoded = base64.b64encode(f.read())
Then, you encode base64 string into base2 string:
encoded_b2 = "".join([format(n, '08b') for n in png_encoded])
print(encoded_b2)
Although, you may decode base2 string into png file:
decoded_b64 = b"".join([bytes(chr(int(encoded_b2[i:i + 8], 2)), "utf-8") for i in range(0, len(encoded_b2), 8)])
with open('my_image_decoded.png', 'wb') as f:
f.write(base64.b64decode(decoded_b64))
At second, read bytes directly and write byte as base 2 number into string:
from PIL import Image
from io import BytesIO
out = BytesIO()
with Image.open("my_image.png") as img:
img.save(out, format="png")
image_in_bytes = out.getvalue()
encoded_b2 = "".join([format(n, '08b') for n in image_in_bytes])
print(encoded_b2)
And you may decode base2 string into file:
decoded_b2 = [int(encoded_b2[i:i + 8], 2) for i in range(0, len(encoded_b2), 8)]
with open('my_image_decoded.png', 'wb') as f:
f.write(bytes(decoded_b2))

Python binary messes up some files

I have written two python scripts. One of which encodes the file to binary, stores it as a textfile for later decryption. The other script can turn the textfile back into readable information, or at least, that's my aim.
script 1 (encrypt)
(use any .png image file as input, any .txt file as output):
u_input = input("What file to encrypt?")
file_store = input("Where do you want to store the binary?")
character = "" #Blank for now
encrypted = "" #Blank for now, stores the bytes before they are written
with open(u_input, 'rb') as f:
while True:
c = f.read(1)
if not c:
f.close()
break
encrypted = encrypted + str(bin(ord(c))[2:].zfill(8))
print("")
print(encrypted) # This line is not necessary, but I have included it to show that the encryption works
print("")
with open(file_store, 'wb') as f:
f.write(bytes(encrypted, 'UTF-8'))
f.close()
As far as I can tell, this works okay for text files (.txt)
I then have a second script (to decrypt the file)
Use the previously created .txt file as source, any .png file as dest:
u_input =("Sourcefile:")
file_store = input("Decrypted output:")
character = ""
decoded_string = ""
with open(u_input, 'r' as f:
while True:
c = f.read(1)
if not c:
f.close()
break
character = character + c
if len(character) % 8 == 0:
decoded_string = decoded_string + chr(int(character, 2))
character = ""
with open(file_store, 'wb') as f:
f.write(bytes(decoded_string, 'UTF-8'))
f.close()
print("SUCCESS!")
Which works partially. i.e. it writes the file. However, I cannot open it or edit it. When I compare my original file (img.png) with my second file (img2.png), I see characters have been replaced or line breaks not entered correctly. I can't view the file in any image viewing / editing program. I do not understand why.
Please could someone try to explain and provide a solution (albeit, partial)? Thanks in advance.
Note: I am aware that my use of "encryption" and "decryption" are not necessarily used correctly, but this is a personal project, so it doesn't matter to me
It appears you're using Python 3, as you put a UTF-8 parameter on the bytes call. That's your problem - the input should be decoded to a byte string, but you're putting together a Unicode string instead, and the conversion isn't 1:1. It's easy to fix.
decoded_string = b""
# ...
decoded_string = decoded_string + bytes([int(character, 2)])
# ...
f.write(decoded_string)
For a version that works in both Python 2 and Python 3, another small modification. This actually measures faster for me in Python 3.5 so it should be the preferred method.
import struct
# ...
decoded_string = decoded_string + struct.pack('B', int(character, 2))

Python: Decode base64 multiple strings in a file

I'm new to python and I have a file like this:
cw==ZA==YQ==ZA==YQ==cw==ZA==YQ==cw==ZA==YQ==cw==ZA==YQ==cw==ZA==dA==ZQ==cw==dA==
It's an keybord input, coded with base64, and new I want to decode it
I try this by the code is stoping at first character decoded.
import base64
file = "my_file.txt"
fin = open(file, "rb")
binary_data = fin.read()
fin.close()
b64_data = base64.b64decode(binary_data)
b64_fname = "original_b64.txt"
fout = open(b64_fname, "w")
fout.write(b64_data)
fout.close
Any help is welcome. thanks
I assume that you created your test input string yourself.
If I split your test input string in blocks of 4 characters and decode each one apart, I get the following:
>>> import base64
>>> s = 'cw==ZA==YQ==ZA==YQ==cw==ZA==YQ==cw==ZA==YQ==cw==ZA==YQ==cw==ZA==dA==ZQ==cw==dA=='
>>> ''.join(base64.b64decode(s[i:i+4]) for i in range(0, len(s), 4))
'sdadasdasdasdasdtest'
However, the correct base64 encoding of your test string sdadasdasdasdasdtest is:
>>> base64.b64encode('sdadasdasdasdasdtest')
'c2RhZGFzZGFzZGFzZGFzZHRlc3Q='
If you place this string in my_file.txt (and rewriting your code to be a bit more concise) then it all works.
import base64
with open("my_file.txt") as f, open("original_b64.txt", 'w') as g:
encoded = f.read()
decoded = base64.b64decode(encoded)
g.write(decoded)

python image (.jpeg) to hex code

I operate with a thermal printer, this printer is able to print images, but it needs to get the data in hex format. For this I would need to have a python function to read an image and return a value containing the image data in hex format.
I currently use this format to sent hex format to the printer:
content = b"\x1B\x4E"
Which is the simplest way to do so using Python2.7?
All the best;
I don't really know what you mean by "hex format", but if it needs to get the whole file as a sequence of bytes you can do:
with open("image.jpeg", "rb") as fp:
img = fp.read()
If your printer expects the image in some other format (like 8bit values for every pixel) then try using the pillow library, it has many image manipulation functions and handles a wide range of input and ouput formats.
How about this:
with open('something.jpeg', 'rb') as f:
binValue = f.read(1)
while len(binValue) != 0:
hexVal = hex(ord(binValue))
# Do something with the hex value
binValue = f.read(1)
Or for a function, something like this:
import re
def imgToHex(file):
string = ''
with open(file, 'rb') as f:
binValue = f.read(1)
while len(binValue) != 0:
hexVal = hex(ord(binValue))
string += '\\' + hexVal
binValue = f.read(1)
string = re.sub('0x', 'x', string) # Replace '0x' with 'x' for your needs
return string
Note: You do not necessarily need to do the re.sub portion if you use struct.pack to write the bits, but this will get it into the format that you need
Read in a jpg and make a string of hex values. Then reverse the procedure. Take a string of hex and write it out as a jpg file...
import binascii
with open('my_img.jpg', 'rb') as f:
data = f.read()
print(data[:10])
im_hex = binascii.hexlify(data)
# check out the hex...
print(im_hex[:10])
# reversing the procedure
im_hex = binascii.a2b_hex(im_hex)
print(im_hex[:10])
# write it back out to a jpg file
with open('my_hex.jpg', 'wb') as image_file:
image_file.write(im_hex)

Python bytearray isn't as long as it should be

I'm trying to read an Android yuv image represented as a raw byte file.
f = open(self.fn)
self.yuvArray = bytearray(f.read())
I know that the file contains 720K bytes, but self.yuvArrayhas only 350K.
Moreover, after trying this with multiple filesof the same format, all of which are 720K byte long (verified both in file size, and c# code returns a 720k size array), I noticed all of them are different sizes, around 350K.
I tried to see if its some kind of compression, or something, couldn't find anything.
It is vital to me to receive the correct length, regardless of if its all there, just I can't see it.
How can I read it into a 720K sized array?
Open the file in binary mode (b).
f = open(self.fn, 'rb')
Otherwise, in Windows, carriage return, newline is converted, and a specific byte (26 == 0x1A) cause read return earlier.
with open('testfile', 'wb') as f:
f.write('\r\n')
with open('testfile', 'r') as f:
assert f.read() == '\n' # converted
with open('testfile', 'wb') as f:
f.write(''.join(chr(i) for i in range(256)))
with open('testfile', 'r') as f:
assert len(f.read()) < 256 # len(..) == 26

Categories

Resources