Pillow throws error on save with StringIO - python-3.x

In some tutorials was explained to use StringIO in Pillow save method. but when I use this testcode:
from PIL import Image
from io import StringIO, BytesIO
photo = Photo.objects.get(pk=1)
bytes = BytesIO()
string = StringIO()
image = Image.open(photo.image)
image.save(string, 'PNG')
then I get the error:
string argument expected, got 'bytes'
But when I use BytesIO like this:
image.save(bytes, 'PNG')
it works fine. That is strange, because the error message says that a string is expected and bytes is wrong, but obviously the opposite is correct. And that is also contrary to the informations I got while checking tutorials.
Maybe the behavior of save() was changed in the Pillow fork, and the error message was not updated? Or is it different because I use Python 3 with io module instead of StringIO module?
edit, examples where StringIO is proposed
How do you convert a PIL `Image` to a Django `File`?
https://djangosnippets.org/snippets/10473/
Django - Rotate image and save

Related

PIL Python3 - How can I open a GIF file using Pillow?

In my current condition, I can open an Image normally using a really short code like this
from PIL import Image
x = Image.open("Example.png")
x.show()
But I tried to use GIF format instead of png, It shows the file but it didn't load the frame of the GIF. Is there any possible way to make load it?
In My Current Code
from PIL import Image
a = Image.open("x.gif").convert("RGBA") # IF I don't convert it to RGBA, It will give me an error.
a.show()
Refer to Reading Sequences in the documentation:
from PIL import Image
with Image.open("animation.gif") as im:
im.seek(1) # skip to the second frame
try:
while 1:
im.seek(im.tell() + 1)
# do something to im
except EOFError:
pass # end of sequence

Is there anyway to call PubChem API In python?

I have been using PubChem API to convert Chemical smiles to the structure but still have an error.
Here is my google colab I try with PIL image plus TKinter
https://colab.research.google.com/drive/1TE9WxXwaWKSLQzKRQoNlWFqztVSoIxB7
My desired output should be in structure format like this
https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/O=C(N1C=CN=C1)N2C=CN=C2/PNG?record_type=2d&image_size=large
Download and display in a Jupyter Notebook
from urllib.request import urlretrieve
from IPython.display import Image
smiles = 'NC1=NC(C)=C(C2=CC=C(S(=O)(C)=O)C(F)=C2)S1'
urlretrieve('https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/'+smiles+'/PNG', 'smi_pic.png')
p = Image(filename='smi_pic.png')
p
Output

Trying to pass a base_64 encoded image to google authentication

So i am working on a small project(a restful service so json format which is not mentioned in the code) in which the code accepts base_64 image data and decodes it to from an image ,i'm able to convert it back to image but i am not able to use google vision(googel ocr) on the image to extract the text . The only part that isn't working is the following block of code:
from flask import Flask,request,jsonify
import os,io,re,glob,base64
from google.cloud import vision
from google.cloud.vision import types
from PIL import Image
app = Flask(__name__)
os.environ['GOOGLE_APPLICATION_CREDENTIALS']=r'date_scanner.json'
#app.route('/jason_example',methods=['POST'])
def jason_example():
req_data=request.get_json()
base_64_image_content=req_data['imgcnt']
#the issue starts from here
image = base64.b64decode(base_64_image_content)
image=Image.open(io.BytesIO(image))
image=vision.types.Image(content=content)
response=client.text_detection(image=image)
texts=response.text_annotations`
enter code here
No need to use Image.open which I think is a PIL method anyway. You should be able to decode this straight to a byte string with base64.decodebytes, as outlined in this answer,
The code should look like:
# the issue starts from here
image_bytes = base64.decodebytes(base_64_image_content)
image = vision.types.Image(content=image_bytes)
response=client.text_detection(image=image)
texts=response.text_annotations

How to fix ''PosixPath' object has no attribute 'encode'" error using librosa.load?

I'm starting learning basic feature extraction with librosa and was trying reading and storing ten kick drums with pathlib, but it doesn't work since I always getting an encoding error, where as there is no error without pathlib.
I tried changing the path, updating every imported library very often, using wav instead of mp3 but had no further idea.
My code:
%matplotlib inline
from pathlib import Path
import numpy, scipy, matplotlib.pyplot as plt, sklearn, urllib, IPython.display as ipd
import librosa, librosa.display
kick_signals = [
librosa.load(p)[0] for p in Path().glob('audio/drum_samples/train/kick_*.mp3')
]
Error messages:
RuntimeError: Error opening 'audio/techno-nine_o_three.mp3': File contains data in an unknown format.
and
AttributeError: 'PosixPath' object has no attribute 'encode'
I would be very thankful, if you would and could help me.
You can convert the PossixPath object to a string, using p.as_posix()
Example:
p = Path(file_path)
p.as_posix()
Try:
kick_signals = [
librosa.load(p.absolute())[0] for p in Path().glob('audio/drum_samples/train/kick_*.mp3')
]
That way you pass a string instead of a PosixPath to librosa.
If that does not fix it, check your mp3 file. Does it play in a regular player? If not, please post the whole error message (stacktrace). Perhaps librosa's dependencies aren't installed properly.

Python3.5 error using BytesIO or StringIO with base64.standard_b64encode

I am trying to take the contents of a BytesIO or StringIO object and use base64.standard_b64encode() to encode it. I have tried both. This works fine in python 2.7, however in python 3.5 I get the following error.
TypeError: Can't convert 'bytes' object to str implicitly
This is the portion of code having the problem.
output = BytesIO()
img.save(output, format="PNG")
output.seek(0)
data = "data:image/png;base64," + base64.standard_b64encode(output.read())
html = "<html><body><img src='DATA'></body></html>"
I have seen references to fixing this error for strings using b"sting" but I don't know how that would apply to reading from a file.
Thanks
Turns out I the problem was not with the base64 encoding, but rather the string I was trying to append it to. I had to do the following so that python did not see it as a byte encoding anymore.
base64.b64encode(output.read()).decode()

Resources