How to convert a Base64 file to bytes? - python

I am trying to pass a base64 to bytes. But I think I'm doing it wrong because I'm passing it to ascii. The file is much bigger but I didn't want to put it all. I hope you can support me.
def convert():
base64_message = 'JVBERi0xLjUKJeLjz9MKMSAwIG9iago8PC9DcmVhdG9yKFdyaXRlcikvc2l6ZV9oZWlnaHQoMTI1LjApL01vZERhdGUoRDoyMDIyMDIxNjE5MzQzOS0wNicwMCcpL2xhc3RQYWdlKDEpL0NyZWF0aW9uRGF0ZShEOjIwMjIwMjE2MTkzNDM3LTA2JzAwJykvc3BhY2VfYm94KDIwLjApL2Nvb3JkaW5hdGVzUGFnZSg1NC4wLTU5Ny4wLTIsKS9Qcm9kdWNlcihMaWJyZU9mZmljZSA2LjQ7IG1vZGlmaWVkIHVzaW5nIGlUZXh0riA1LjUuOCCpMjAwMC0yMDE1IGlUZXh0IEdyb3VwIE5WIFwoQUdQTC12ZXJzaW9uXCkpL0F1dGhvcihGR0RSKS9zaXplX3dpZHRoKDIyNS4wKS9UaXRsZShQQUdBUkUpL3BkZkFQSU1hbmlwdWxhdGVkKDEpPj4KZW5kb2JqCjIgMCBvYmoKPDwvR3JvdXA8PC9TL1RyYW5zcGFyZW5jeS9JIHRydWUvQ1MvRGV2aWNlUkdCPj4vQ29udGVudHMgMyAwIFIvVHlwZS9QYWdlL1Jlc291cmNlcyA0IDAgUi9QYXJlbnQgNSAwIFIvTWVkaWFCb3hbMCAwIDYxMiA3OTJdPj4KZW5kb2JqCjMgMCBvYmoKPDwvRmlsdGVyL0ZsYXRlRGVjb2RlL0xlbmd0aCAzMTUwPj5zdHJlYW0KeJzVW0uLJLkRvvevyPNC1SpCj0xBk1Bd3W28t7EbfDA+2V7D4rGZvezft0KhR0gpZfWAfTADXZVZUigUjy8e0qgrLL89fVvUoq4Kt8UBXP0Ky+r589e/P/3ph+VfT+rq/KZ0GLVtDtfwuYZHv/z6j6cwY1s2uCq72DBL20WvV7Bh6vLzD09flm/LRYVV4h8XB68er1hIf4tvnSUe6CfmxS5//fr04++/muX138uXSOZ/xmMkHf6FgS8fT5u9umW129UvH39bfnyHBdTVLh8///lZwX7BZ4V7+KOV2SF9t/sF1LNy+18+fnp6+3j60pEE9GHzgia2NDXR0UzzEoja9Oni33Vfn9XW0L5qtMaHT6vstoVPVOtm0mqo42qo81ra8Uo+scwfN/Uy43eFq1mcN1d9FMFKXAVet0DuFvl7Uffwj9++7vZZvan3KWUkK3A+qOMgCE8iuBNrr4EuBLm+kVzD83t4CSpIGoB+Ho55pTEYlgdNSgLaI1hiir8yfzQV1jSFpkKeBfRSF3qwxal+N/lrJMvLRII30vw9vFQrzZpsmJUhdixlSdIK+wpCjMsHTsIqtvIOyrIRqI2EsObBLkiqmcd/zYwJrcmmx2I/SOMF7izpVh6v0ej5t7eodw3vUSS3+BuqhlL4RCgij9pSVVtB5CRSFuxtZyXwNpvJUemI5WsUP+p2aOCYR8C51Vl7XY/bj/vy+8la+jltcL+sLq66hiezb88Y7QujOqIs+IXSaOJLNOG1y2+jT+MaFIxh48GuSJbpNxseLiuL2+nkC7dEtI4O48Ir59txDBZYvwa/dGvmlAzF6fIE7EviVdZQNCybdIM+/AZ5HfaeIuYLaDyxeaN1K29ozI2dC7MFe95QWMFFr8r+5eOYl8QuOQQb3xS1LKxhkZGaadWPX4ZzMESLiWlE+9JeeMSpeRmYmhdr3rFOI607e9PRgZJajKmaCt/plY0O46JgzDPeEgZYkyckfysIhRG8KhoKlyIdWltWKto1yXuNP4O0NURWuV9o9kuk4h4jlMVvrMq3nXVuWNsWotMYnZ8wcoY8mh+C4IwtvwNtGQkYzVpIxJ1l10XxHEb2i0e7IrbIQ+zWEhZGFx1TZ/EXdvnV/dwMcA1Q24uFGWKrZ6xOOH8Bz2xgwNpk4WiEzdMvioOAN0KcBKb5pc0bi4='
base64_bytes = base64_message.encode('ascii')
message_bytes = base64.b64decode(base64_bytes)
message = message_bytes.decode('ascii')
print(message)

you can find the following here:
import base64
base64_message = 'UHl0aG9uIGlzIGZ1bg=='
base64_bytes = base64_message.encode('ascii')
message_bytes = base64.b64decode(base64_bytes)
message = message_bytes.decode('ascii')
print(message)
Source: https://stackabuse.com/encoding-and-decoding-base64-strings-in-python/

just two line could solve this problem:
import base64
base64_code = "VER30QHI30JFOIAIO3020085723F" # this is just a example
img_data = base64_code.encode()
content = base64.b64decode(img_data)
with open('/path/to/your/image.jpg', 'wb') as fw:
fw.write(content)
print(content)
then you could check the image bytes.

Related

string formatted as base64 to base64 object

From a post request, I receive a base64 in JSON. Problem is that I can't just change the file type from string to base64 since it's already formatted as base64. need the base64 to convert it back to an image.
json_data = request.get_json(force=True)
img = json_data['img']
print(img)
with open("imageToSave.png", "wb") as fh:
fh.write(base64.decodebytes(img))
In order to decode it, add the third line which decodes the string to base64
json_data = request.get_json(force=True)
img = json_data['img']
imgdata = base64.b64decode(img)
filename = 'upload/newimg.jpg' # I assume you have a way of picking unique filenames
with open(filename, 'wb') as f:
f.write(imgdata)

Pull random image from directory, encode to base64 and then print

I'm having difficult time trying to work these two together. It's frustrating me a little, so I hope to find ideas/solutions.
The complete works (what I'm planning on) should grab a random image from an online directory, encode it to base64 then print the base64. I've had total curl madness going all day and now I'm turning to python. Onwards!
These are kinda just notes at the minute but should explain the process.
import random, os
import base64
def search(): #get file
path = r"/Users/Impshum/Pictures" #should be able to http
random_filename = random.choice([
x for x in os.listdir(path)
if os.path.isfile(os.path.join(path, x))
])
print(random_filename) #not printing full location
def encode(): #encode to base64
image = open('heaven.jpg', 'rb')
image_read = image.read()
image_64_encode = base64.encodestring(image_read)
print image_64_encode
search() #notes
encode() #notes
Many thanks in advance.
You have most of the code you need
import random, os
import base64
def search(path): #get file
random_filename = random.choice([
x for x in os.listdir(path)
if os.path.isfile(os.path.join(path, x))
])
return os.path.join(path, random_filename)
def encode(path):
image = open(path, 'rb')
image_read = image.read()
image.close()
image_64_encode = base64.encodestring(image_read)
return image_64_encode
print(encode(search(r"/Users/Impshum/Pictures")))
There are things you can do to make this "nicer", but this should get you started.
For instance, you might want to use glob instead of os.listdir / os.path.join, etc. And using a context manager
import glob
import base64
import random
def search(path): #get file
random_filename = random.choice(glob.glob(path))
return random_filename
def encode(path):
with open(path, 'rb') as image:
image_read = image.read()
image_64_encode = base64.encodestring(image_read)
return image_64_encode
print(encode(search(r"/Users/Impshum/Pictures/*")))
Error handling is left as an exercise to the OP

Generating a Temporary url in Python

I've been trying to generate a temporary url in python, the url will some data that i need to make sure isn't changed so i'll add a hash in the end but i keep ending with a bString no matter what i try, can anyone point out what i'm doing wrong?
Here's a sample of my code
oh and i know that maybe changing the algorithms/encoding might solve the problem but i can't find a suitable one, can any downvoter explain why he downvoted
import hashlib
import datetime
from Crypto.Cipher import AES
def checkTemp(tempLink):
encrypter = AES.new('1234567890123456', AES.MODE_CBC, 'this is an iv456')
decryption = encrypter.decrypt(tempLink)
length = len(decryption)
hash_code = decryption[length-32:length]
data= decryption[:length-32].strip()
hasher = hashlib.sha256()
hasher.update(data)
hashCode = hasher.digest()
if(hash_code==hashCode):
array = data.decode().split(",",5)
print("expiry date is :"+ str(array[5]))
return array[0],array[1],array[2],array[3],array[4]
else:
return "","","","",""
def createTemp(inviter,email,role,pj_name,cmp_name):
delim = ','
data = inviter+delim+email+delim+role+delim+pj_name+delim+cmp_name+delim+str(datetime.datetime.now().time())
data = data.encode(encoding='utf_8', errors='strict')
hasher = hashlib.sha256()
hasher.update(data)
hashCode = hasher.digest()
encrypter = AES.new('1234567890123456', AES.MODE_CBC, 'this is an iv456')
# to make the link a multiple of 16 by adding for AES with the addition of spaces
newData = data+b' '*(len(data)%16)
result = encrypter.encrypt(newData+hashCode)
return result
#print(str(link).split(",",5))
link = createTemp("name","email#homail.com","Designer","Project Name","My Company")
print(link)
inviter,email,role,project,company = checkTemp(link)
The problem was not being able to putout a normal string because the encryption will result in characters that are almost impossible to encode, so the solution is to use binascii to encode the bStrings for us and decode them
import binascii
then we encode the resulting usable string for the link
hexedLink = binascii.hexlify(link).decode()
and we unhexify it before using it in the method
inviter,email,role,project,company = checkTemp(binascii.unhexlify(hexedLink))

Prepend information in base64 encoding

Here is an answer which gives some information on how to base64 encode a file. However, I also want to pass in the filetype and mimetype. for the information in the base64 encoded string.
So far I have for my base64 string:
x=base64.b64encode(open('/Users/user/Desktop/img.PNG').read())
What is the correct information to prepend, and how would I do this?
It seems like the following is how I would get the base64 file information to pass to the server:
file = '/Users/user/Desktop/img.PNG'
prepend_info = 'data:%s;base64' % mimetypes.guess_type(file)[0]
base_64_data = open(file).read().encode('base64')
image_data_base64 = '%s,%s' % (prepend_info, base_64_data)
This then gives me:
data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wB...
Perhaps something along these lines:
from __future__ import print_function
import base64
import binascii
import os
def base64_encode_file(filename):
filetype = os.path.splitext(filename)[1][1:] # remove leading '.' from ext
with open(filename) as file:
data = file.read()
return base64.b64encode(','.join((filename, filetype, data))), data
filename = 'C:/Users/martin/Desktop/img.PNG'
#filename = '/Users/user/Desktop/img.PNG'
encoded, data = base64_encode_file(filename)
print('encoded: {} (hex file data: {})'.format(encoded, binascii.hexlify(data)))
decoded = base64.b64decode(encoded).split(',', 2)
print('decoded:', decoded[0], decoded[1], binascii.hexlify(decoded[2]))
Output:
encoded: QzovVXNlcnMvbWFydGluL0Rlc2t0b3AvaW1nLlBORyxQTkcsiVBORwo=
(hex file data: 89504e470a)
decoded: C:/Users/martin/Desktop/img.PNG PNG 89504e470a

Getting TypeError when trying to convert in-memory image to base64 string?

I'm getting URL through POST via DAJAX.
The URL is then passed into the function below. A TypeError is thrown.
I do not want to save the 'img' to disk and then reopen it to do the conversion.
I'm not sure what else to try so I figured I as the world. Thanks for the help in advance.
def getqrcode(link):
bsettings = Bitcoinsettings.objects.get(pk=1)
qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=bsettings.qrcodesize , border=5,)
qr.add_data(link)
qr.make(fit=True)
img = qr.make_image()
output = StringIO.StringIO()
img.save(output, 'GIF')
contents = output.getvalue()
data = base64.b64encode(open(contents,'rb').read())
data = "data:image/png;base64," + data
output.close()
img = []
return data
TypeError: file() argument 1 must be encoded string without NULL bytes, not str
Here is the ajax.py code.
from torgap.bitcoin.bitcoin import getqrcode
from dajaxice.decorators import dajaxice_register
from dajax.core import Dajax
#dajaxice_register
def getimage(request, image):
try:
dajax = Dajax()
link = image
image = getqrcode(link)
dajax.assign('#qrcode', 'src', image)
return dajax.json()
except Exception as e:
print e
I'm not sure you understand what returns ouput.getvalue() since you are trying to read the file again with
data = base64.b64encode(open(contents,'rb').read())
but in the line above contents already contains a string representation of the image file. And it is almost sure that here is where are hidden the annoying NULL bytes that file() complains about.
Try change the line above by:
data = base64.b64encode(contents)
Also you can give a look at StringIO reference.

Categories