Get Base64 image dimension in python - python

Assuming one has a base64 encoded image.
How can one extract the image dimensions from the string, preferably without storing the string to disc as an image?
For PNG files, I can get this from bytes 16-24 of the string which are part of the PNG header, but for JPEG images, it appears no such hack exists.
What are some nice ways of getting the image dimensions in this case?

Using the pillow library one can do:
import io
import PIL
from PIL import Image
imgdata = base64.b64decode(base64_str)
im = Image.open(io.BytesIO(imgdata))
width, height = im.size

Related

Convert Image to array and array to image using python, does the array contain metadata or other info?

Sorry for my english but it's not my first language.
I would like to create a program that:
Transform a jpeg or png image into an array (very important: I would like an array composed only of the values that the pixels of the image have and not metadata or other information. Where I can select each specific pixel of the image).
Save this array in a txt file.
Transform this array composed of only the pixel values of the image back into jpg or png image and save it in a file.
Requests:
Is the array I created with the program I wrote composed only of the pixel values of the image? is there also metadata or other information?
Is this a valid way to remove metadata from an image?
Is this a valid way to create the array representing that image pixel by pixel?
Is this a valid way to convert png images to jpeg or jpeg to png?
Thank you!
This is the program I created, any opinion?
import numpy as np
from PIL import Image
import sys
img_data = Image.open("imagea.jpeg")
img_arr = np.array(img_data)
np.set_printoptions(threshold=sys.maxsize)
print(img_arr.shape)
new_img = Image.fromarray(img_arr)
new_img.save("imageb.jpeg")
print("Image saved!")
file = open("file1.txt", "w+")
content = str(img_arr)
file.write(content)
file.close()
print("Finished!")
Loading an image and converting it to a Numpy array is a perfectly legitimate way of discarding all metadata including:
EXIF data, copyright data,
IPTC and XMP data,
ICC colour profile data
You can tell it's all gone by thinking about the Numpy array you hold and its dimensions and data type.
Note that you need to be careful with PNG palette images and images with an alpha channel.
Note that you can achieve this more simply on the command-line with ImageMagick using:
magick mogrify -strip IMAGE.JPG
Or with exiftool.
Note that you can achieve this by using a format that doesn't support metadata, such as NetPBM, with extension .ppm e.g.:
magick INPUT.JPG -strip -compress none RESULT.PPM # gives P3/plain ASCII file
magick INPUT.JPG -strip RESULT.PPM # gives P6/binary file
You can also read/write PPM files with PIL.

Python: how to convert an image in memory?

I have an image in memory (downloaded from an online source) and I want to convert it to a different format before sending it on to a different online location.
The conversion is .webp to .jpg but that's not really relevant.
With Pillow I can easily convert local images and save them back to disc, but I can't get it to work with an image in memory.
I don't necessarily need to use Pillow. Any way to convert the image without having to save anything to disc is fine.
I am new to BytesIO with PIL, so just check my code attempt, with my test image it works, let me know
from PIL import Image
from io import BytesIO
img = Image.open('test.webp')
print('image : ', img.format)
img.show()
# Write PIL Image to in-memory PNG
membuf = BytesIO()
img.save(membuf, format="png")
img = Image.open(membuf)
print('image : ', img.format)
img.show()

conveting bytes to image using tinytag and PIL

I am using tinytags module in python to get the cover art of a mp3 file and want to display or store it. The return type of the variable is showing to be bytes. I have tried fumbling around with PIL using frombytes but to no avail. Is there any method to convert the bytes to image?
from tinytag import TinyTag
tag = TinyTag.get("03. Me, Myself & I.mp3", image=True)
img = tag.get_image()
I actually got a PNG image when I called tag.get_image() but I guess you might get a JPEG. Either way, you can wrap it in a BytesIO and open it with PIL/Pillow or display it. Carrying on from your code:
from PIL import Image
import io
...
im = tag.get_image()
# Make a PIL Image
pi = Image.open(io.BytesIO(im))
# Save as PNG, or JPEG
pi.save('cover.png')
# Display
pi.show()
Note that you don't have to use PIL/Pillow. You could look at the first few bytes and if they are a PNG signature (\x89PNG) save data as binary with PNG extension. If the signature is JPEG (\xff \xd8) save data as binary with JPEG extension.

Problems Converting Images from 8-bit to 10-bit

I am trying to convert 8 bit images to 10 bit. I thought it would be as easy as changing the bin values. I've tried to pillow and cv-python:
from PIL import Image
from numpy import asarray
import cv2
path = 'path/to/image'
img = Image.open(path)
data = asarray(img)
newdata = (data/255)*1023 #2^10 is 1024
img2 = Image.fromarray(newdata) #this fails
cv2.imwrite('path/newimage.png, newdata)
While cv2.imwrite successfully writes the new file, it is still encoded as an 8bit image even though bin goes up to 1023.
$ file newimage.png
newimage.png: PNG Image data, 640 x 480, 8-bit/color RGB, non-interlaced
Is there another way in either python or linux that can convert 8-bit to 10-bit?
Lots of things going wrong here.
You are mixing OpenCV (cv2.imwrite) with PIL (Image.open) for no good reason. Don't do that, you will confuse yourself as they use different RGB/BGR orderings and conventions,
You are trying to store 10-bit numbers in 8-bit vectors,
You are trying to hold 3 16-bit RGB pixels in a PIL Image which will not work as RGB images must be 8-bit in PIL.
I would suggest:
import cv2
import numpy as np
# Load image
im = cv2.imread(IMAGE, cv2.IMREAD_COLOR)
res = im.astype(np.uint16) * 4
cv2.imwrite('result.png', res)
I found a solution using pgmagick wrapper for python
import pgmagick as pgm
imagePath = 'path/to/image.png'
saveDir = '/path/to/save'
img = pgm.Image(imagePath)
img.depth(10) #sets to 10 bit
save_path = os.path.join(saveDir,'.'.join([filename,'dpx']))
img.write(save_path)

seve picture 'data:image/jpeg;base64' with python

How i can save or download this picture with python
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCABkADwDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5O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AAAB0HFFFVY8C5Fd28V3azW1wu+GZDG65IypGCMj2Ncd/wqvwb/0Bv/Jqb/4uiig6KOLr4dNUZuN+za/Id/wq/wAIbAn9ktsBJC/a58Ang/x98D8qb/wqvwb/ANAb/wAmpv8A4uiig2/tTG/8/pf+BP8AzFHwt8HgEDSCAeo+1Tc/+P1s6N4T0XRrZ7fTbLyYXcyMvmu2WIAzlmJ7Ciigipj8VVXLUqya85N/qf/Z
Well, the start of the string (this part data:image/jpeg;base64,) tells you it is base64 encoded. So, you need to strip all that off and find the start the image, which is /9j, and just grab the image part which is the rest of the string.
b = b'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...'
z = b[b.find(b'/9'):]
Then you need base64 decode the result, and make it into a BytesIO object that PIL can read. Then read it into a PIL Image and save it:
im = Image.open(io.BytesIO(base64.b64decode(z))).save('result.jpg')
So, the entire code will look like:
import base64
import io
from PIL import Image
# Initialise your data
b = b'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...'
z = b[b.find(b'/9'):]
im = Image.open(io.BytesIO(base64.b64decode(z))).save('result.jpg')
Keywords: image, image processing, base64, b64, encode, encoded, decode, decoded, PIL, Pillow, Python

Categories

Resources