Python - Is Base64 Data A Valid Image?
I am using Python and I have a base64 string. I want to know that if the base64 data I have received is a image and not any other file (eg. PDF, DOCX) whose extension is changed to
Solution 1:
The PNG format has a fixed header that consists of the 8 bytes 89 50 4e 47 0d 0a 1a 0a
which, when converted to base64, look like this:
iVBORw0KGgo=
As you can see, it ends with a padding character "=", which will not be there in a real base64 representation of an image, and instead of "o" there could be a different character depending on the bytes after the header.
So you can easily recognize a base64 encoded PNG by comparing the first characters of the base64 string with
iVBORw0KGg
This principle works for all file formats that have a fixed header.
Solution 2:
With the help of this function, I check 3 things:
- checking base64 image string validation
- checking format of image that I want to support
- checking image dimentions
Code:
import base64
import io
from PIL import Image
defis_valid_base64_image(self, image_string):
# checking valid base64 image string try:
image = base64.b64decode(image_string)
img = Image.open(io.BytesIO(image))
except Exception:
raise Exception('file is not valid base64 image')
# end of check base64 image string# checking image format I want to supportif img.format.lower() in ["jpg", "jpeg", "png"]:
# if you need to check image dimension
width, height = img.size
if width < 800and height < 800:
returnTrueelse:
raise Exception(
'image size exceeded, width and height must be less than 800 pixels')
# end of checking dimentionselse:
raise Exception('Image is not valid, only \'base64\' image (jpg, jpeg, png) is valid')
# end of checking image format
Post a Comment for "Python - Is Base64 Data A Valid Image?"