How to decode JPG/PNG in python? - python

This is a code of a JPG/PNG(I don't know exactly)
Here's on google docs
I need to decode it in Python to complete image and show it using Pillow or something like that. Do you know any libraries or ways how to decode it? Thanks!

(for Python 3)
If the image is stored as a binary file, open it directly:
import PIL
# Create Image object
picture = PIL.Image.open('picture_code.dat')
#display image
picture.show()
# print whether JPEG, PNG, etc.
print(picture.format)
If the image is stored as hex in a plaintext file picture_code.dat similar to your Google Docs link, it needs to first be converted to binary data:
import binascii
import PIL
import io
# Open plaintext file with hex
picture_hex = open('picture_code.dat').read()
# Convert hex to binary data
picture_bytes = binascii.unhexlify(picture_hex)
# Convert bytes to stream (file-like object in memory)
picture_stream = io.BytesIO(picture_bytes)
# Create Image object
picture = PIL.Image.open(picture_stream)
#display image
picture.show()
# print whether JPEG, PNG, etc.
print(picture.format)

Related

Cannot convert base64 string into image

Can someone help me turn this base64 data into image? I don't know if it's because the data was not decoded properly or anything else. Here is how I decoded the data:
import base64
c_data = { the data in the link (string type) }
c_decoded = base64.b64decode(c_data)
But it gave the error Incorrect Padding so I followed some tutorials and tried different ways to decode the data.
c_decoded = base64.b64decode(c_data + '=' * (-len(c_data) % 4))
c_decoded = base64.b64decode(c_data + '=' * ((4 - len(c_data) % 4) % 4)
Both ways decoded the data without giving the error Incorrect Padding but now I can't turn the decoded data into image.
I have tried creating an empty png then write the decoded data into it:
from PIL import Image
with open('c.png', 'wb') as f:
f.write(c_decoded)
image = Image.open('c.png')
image.show()
It didn't work and gave the error: cannot identify image file 'c.png'
I have tried using BytesIO:
from PIL import Image
import io
from io import BytesIO
image = Image.open(io.BytesIO(c_decoded))
image.show()
Now it gave the error: cannot identify image file <_io.BytesIO object at 0x0000024082B20270>
Please help me.
Not sure if you definitely need a Python solution, or you just want help decoding your image like the first line of your question says, and you thought Python might be needed.
If the latter, you can just use ImageMagick in the Terminal:
cat YOURFILE.TXT | magick inline:- result.png
Or equivalently and avoiding "Useless Use of cat":
magick inline:- result.png < YOURFILE.TXT
If the former, you can use something like this (untested):
from urllib import request
with request.urlopen('data:image/png;base64,iVBORw0...') as response:
im = response.read()
Now im contains a PNG-encoded [^1] image, so you can either save to disk as such:
with open('result.png','wb') as f:
f.write(im)
Or, you can wrap it in a BytesIO and open into a PIL Image:
from io import BytesIO
from PIL import Image
pilImage = Image.open(BytesIO(im))
[^1]: Note that I have blindly assumed it is a PNG, it may be JPEG, so you should ideally look at the start of the DataURI to determine a suitable extension for saving your file.
Credit to #jps for explaining why my code didn't work. Check out #Mark Setchell solution for the reliable way of decoding base64 data (his code fixes my mistake that #jps pointed out)
So basically remove the [data:image/png;base64,] at the beginning of the base64 string because it is just the format of the data.
Change this:
c = "data:image/png;base64,iVBORw0KGgoAAAANSUh..."
to this:
c = "iVBORw0KGgoAAAANSUh..."
and now we can use
c_decoded = base64.b64decode(c)

Different filesize when changing heic to jpeg in python

I could easily convert HEIC to JPEG in python with a pyheic library.
But the filesize gets larger when it's converted to JPEG. (About 4 times). Can I reduce the size of the file saving it?
How can I get base64-encoded string instead of saving JPEG image?
My code is as follows:
# -*- coding: utf-8 -*-
import sys
import os
from PIL import Image # pip3 install pillow
import pyheif # pip3 install pyheif
def call(oriPath, defPath):
try:
# if defPath is webp or heic
fileType = oriPath.split(".")[-1]
if fileType == "heic":
heif_file = pyheif.read(oriPath)
image = Image.frombytes(
heif_file.mode,
heif_file.size,
heif_file.data,
"raw",
heif_file.mode,
heif_file.stride,
)
image.save(defPath, "JPEG")
except:
print(False)
return
print(True)
Since you are converting from one data type to the other the format is changing. I am not too familiar with HEIC but it could be the case that it is simply a smaller file size with the compression parameters that you have set for the JPEG.
wikipedia has the following to say about it
A HEIF image using HEVC requires less storage space than the equivalent quality JPEG.
So unless you want to drop the quality it might not even be possible to get a smaller image (note: I have no idea what type the HEIC/HEIF is).
As for the base64 encoded string, you could just read the binary data and convert it to base64 per this question: Python: How do I convert from binary to base 64 and back?

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.

Error when trying to convert base64 string to image in Python

I am trying create a Python dashboard in which a user uploads an image and then the image is analyzed. The uploaded image is received as a base64 string and it needs to be converted to an image. I have tried
decoded = BytesIO(base64.b64decode(base64_string))
image = Image.open(decoded)
but I received this error:
cannot identify image file <_io.BytesIO object at 0x00000268954E9888>
Image needs a file-like object, the sort of thing returned by an open. The easiest way to do this is using a with statement:
decoded = base64.b64decode(base64)
with BytesIO(decoded) as fh:
image = Image.open(fh)
# do stuff with image here: when the with block ends
# it's very likely the image will no longer be usable
See if that works better for you. :)

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/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRol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ldlBNZ3MYe28KeEJQCQ+3QkPlqP4mwnTHpnp9Mlxc6dBEkg8M+EMNuI3aCi8Acc7epII/DrQlod74cxrm7Nel3p+ByFh4q+MOo2IvrGSSWyeZIoZv7FgKSht3zK4h2kLtIbng8Hvj2n4U694mOjahF4i1C3nv4rzDLHapEYFaGKQRuBGnzjfzxweM8YHHLNaR3Eco8PeEY5SnnxynQQC5DHBU7Mnpu3cd+4r0f4WahFeaHezDTNHgZr1932WzWNZDtTLkY5J9Tz0ppI5cVkmLoUnUm1a/d/qj2B40kKl1BKnIPoacAAAB0HFFFVY8C5Fd28V3azW1wu+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