How to display images in python simple gui from a api url - python

I want to read a image from api, but I am getting a error TypeError: 'module' object is not callable. I am trying to make a random meme generator
import PySimpleGUI as sg
from PIL import Image
import requests, json
cutURL = 'https://meme-api-python.herokuapp.com/gimme'
imageURL = json.loads(requests.get(cutURL).content)["url"]
img = Image(requests.get(imageURL).content)
img_box = sg.Image(img)
window = sg.Window('', [[img_box]])
while True:
event, values = window.read()
if event is None:
break
window.close()
Here is the response of the api
postLink "https://redd.it/yyjl2e"
subreddit "dankmemes"
title "Everything's fixed"
url "https://i.redd.it/put9bi0vjp0a1.jpg"
I tried using python simple gui module, IS there alternative way to make a random meme generator.

PIL.Image is a module, you can not call it by Image(...), maybe you need call it by Image.open(...). At the same, tkinter/PySimpleGUI cannot handle JPG image, so conversion to PNG image is required.
from io import BytesIO
import PySimpleGUI as sg
from PIL import Image
import requests, json
def image_to_data(im):
"""
Image object to bytes object.
: Parameters
im - Image object
: Return
bytes object.
"""
with BytesIO() as output:
im.save(output, format="PNG")
data = output.getvalue()
return data
cutURL = 'https://meme-api-python.herokuapp.com/gimme'
imageURL = json.loads(requests.get(cutURL).content)["url"]
data = requests.get(imageURL).content
stream = BytesIO(data)
img = Image.open(stream)
img_box = sg.Image(image_to_data(img))
window = sg.Window('', [[img_box]], finalize=True)
# Check if the size of the window is greater than the screen
w1, h1 = window.size
w2, h2 = sg.Window.get_screen_size()
if w1>w2 or h1>h2:
window.move(0, 0)
while True:
event, values = window.read()
if event is None:
break
window.close()

You need to use Image.open(...) - Image is a module, not a class. You can find a tutorial in the official PIL documentation.
You may need to put the response content in a BytesIO object before you can use Image.open on it. BytesIO is a file-like object that exists only in memory. Most functions like Image.open that expect a file-like object will also accept BytesIO and StringIO (the text equivalent) objects.
Example:
from io import BytesIO
def get_image(url):
data = BytesIO(requests.get(url).content)
return Image.open(data)

I would do it with tk its simple and fast
def window():
root = tk.Tk()
panel = Label(root)
panel.pack()
img = None
def updata():
response = requests.get(https://meme-api-python.herokuapp.com/gimme)
img = Image.open(BytesIO(response.content))
img = img.resize((640, 480), Image.ANTIALIAS) #custom resolution
img = ImageTk.PhotoImage(img)
panel.config(image=img)
panel.image = img
root.update_idletasks()
root.after(30, updata)
updata()
root.mainloop()

Related

How do I change the colour of my QR code?

I want to make a QR code with python. The output is a white background with a black qr code. How do I change both of them?
from tkinter import *
import os
import pyqrcode
window = Tk()
window.geometry("550x350")
window.configure(bg="#0434a0")
window.title("QR Code Maker")
photo = PhotoImage(file = "logo.png")
window.iconphoto(False, photo)
def generate():
if len(Subject.get())!=0 :
global qr,photo
qr = pyqrcode.create(Subject.get())
photo = BitmapImage(data = qr.xbm(scale=8))
else:
messagebox.showinfo("Voer een URL in...")
try:
showcode()
except:
pass
def showcode():
imageLabel.config(image = photo)
subLabel.config(text="QR van " + Subject.get())
The documentation of this module can be found here: PyQRCode Module Documentation
It says that the various methods of this module (e.g. png, if you want to get the QR code as a png image) take a background parameter that lets you define the background color, as well as a module_color parameter for the code itself.
pyqrcode module has not been updated for over 5 years. Use qrcode module instead. Note that qrcode module requires Pillow module.
...
from PIL import ImageTk
import qrcode
...
def generate():
try:
subject = Subject.get().strip()
if len(subject) != 0:
# adjust border and box_size to suit your case
qr = qrcode.QRCode(border=2, box_size=10)
qr.add_data(subject)
# change fill_color and back_color to whatever you want
img = qr.make_image(fill_color='blue', back_color='cyan')
photo = ImageTk.PhotoImage(img)
showcode(subject, photo)
else:
messagebox.showinfo("Voer een URL in...")
except Exception as ex:
print(ex)
def showcode(subject, photo):
imageLabel.config(image=photo)
imageLabel.image = photo # keep a reference of the image to avoid garbage collection
subLabel.config(text="QR van " + subject)
...
Note that I pass the photo and subject to showcode() instead of using global variables.
Suggest to merge the code in showcode() into generate().

Using def function to call image from urllib import urlopen - python 2.7

I have made def function to call JPG image to display easily but it in not working property. Also I don't want to use urllib2. It says image_file = image_to_PhotoImage(image)
NameError: name 'image' is not defined
Any suggestions? Thank you
from urllib import urlopen
from Tkinter import *
def image_to_PhotoImage(image, width = None, height = None):
# Import the Python Imaging Library, if it exists
try:
from PIL import Image, ImageTk
except:
raise Exception, 'Python Imaging Library has not been installed properly!'
# Import StringIO for character conversions
from StringIO import StringIO
# Convert the raw bytes into characters
image_chars = StringIO(image)
# Open the character string as a PIL image, if possible
try:
pil_image = Image.open(image_chars)
except:
raise Exception, 'Cannot recognise image given to "image_to_Photoimage" function\n' + \
'Confirm that image was downloaded correctly'
# Resize the image, if a new size has been provided
if type(width) == int and type(height) == int and width > 0 and height > 0:
pil_image = pil_image.resize((width, height), Image.ANTIALIAS)
# Return the result as a Tkinter PhotoImage
return ImageTk.PhotoImage(pil_image)
import Tkinter as tk
root = tk.Tk()
url = "http://www.online-image-editor.com//styles/2014/images/example_image.png"
gogo = urlopen(url)
data_stream = gogo.read()
gogo.close()
image_file = image_to_PhotoImage(image1)
label = tk.Label(root, image=image_file, bg='black')

Generate a image which produces gif like effect

I am trying to generate a image which produces gif like effect by flushing the response continuously to the browser, I am relatively new to django/python and tried with following code testing for both text and image. The generator for text works fine but in case of image only first version of image is being generated.
I tried searching but can't find anything on this. I am confused how to proceed with this or if this is at all possible with django or If the idea is conceptually wrong.
Image Generator :
def refreshx():
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
size = (1000,500)
im = Image.new('RGB', size)
draw = ImageDraw.Draw(im)
red = (255,255,255)
text_pos = (10,30)
draw.text(text_pos, str(datetime.datetime.today()), fill=red)
buffer = StringIO.StringIO()
im.save(buffer, 'PNG')
yield buffer.getvalue()
time.sleep(5)
buffers = StringIO.StringIO()
ims = Image.new('RGB', size)
draws = ImageDraw.Draw(ims)
text_poss = (30,80)
draws.text(text_poss, 'dasdasdsa', fill=red)
print 'been there'
ims.save(buffers, 'PNG')
yield buffers.getvalue()
Text Generator :
def testgenerator():
yield str(datetime.datetime.today())
time.sleep(5)
yield str(datetime.datetime.today())
View Function :
def test(request):
#return HttpResponse(testgenerator());
return HttpResponse(refreshx(), mimetype="image/png")
EDIT :
I learned while researching that there's a concept called gifsocket, I'm looking into it..please suggest if anyone has experience with these

cannot convert PIL thumbnails to PYQt4 icons

i have a problem when converting some Qimages to thumbnails using PIL.
to be used in a list widget , check the image below
where the image should look like :
please note that i use horizontal flow and the text of item is an empty text
one more thing : this only happens when i put more than 1 image
for i in listOfImages:
picture = Image.open(i)
picture.thumbnail((50,50), Image.ANTIALIAS )
qimage = QtGui.QImage(ImageQt.ImageQt(picture))
icon = QtGui.QIcon(QtGui.QPixmap.fromImage(qimage))
item = QtGui.QListWidgetItem(str(path))
item.setIcon(icon)
self.listWidget.addItem(item)
any idea what is going on ? and why images are being pixlated ?.. any better solutions
EDIT : using
pix = QtGui.QPixmap(path)
pix = pix.scaled(50,50,QtCore.Qt.KeepAspectRatio)
icon = QtGui.QIcon(pix)
will be very problematic (needed 10 seconds to run) while the code above needed 1 second.
thanks
from io import BytesIO
qimage = QtGui.QImage()
fp = BytesIO()
picture.save(fp, "BMP")
qimage.loadFromData(fp.getvalue(), "BMP")
icon ...
I had tried ImageQt, but the performance is not good.
I reference http://doloopwhile.hatenablog.com/entry/20100305/1267782841
Because I use python 3.3, cStringIO is replaced by BytesIO
I've not used PIL with PyQt. Have you tried using a QImageReader?
item = QListWidgetItem(image_path)
imageReader = QImageReader()
imageReader.setFileName(image_path)
size = imageReader.size()
size.scale(50, 50, Qt.KeepAspectRatio)
imageReader.setScaledSize(size)
image = imageReader.read()
pix = QPixmap.fromImage(image)
icon = QIcon(pix)
item.setIcon(icon)
self.listWidget.addItem(item)

How do you convert a PIL `Image` to a Django `File`?

I'm trying to convert an UploadedFile to a PIL Image object to thumbnail it, and then convert the PIL Image object that my thumbnail function returns back into a File object. How can I do this?
The way to do this without having to write back to the filesystem, and then bring the file back into memory via an open call, is to make use of StringIO and Django InMemoryUploadedFile. Here is a quick sample on how you might do this. This assumes that you already have a thumbnailed image named 'thumb':
import StringIO
from django.core.files.uploadedfile import InMemoryUploadedFile
# Create a file-like object to write thumb data (thumb data previously created
# using PIL, and stored in variable 'thumb')
thumb_io = StringIO.StringIO()
thumb.save(thumb_io, format='JPEG')
# Create a new Django file-like object to be used in models as ImageField using
# InMemoryUploadedFile. If you look at the source in Django, a
# SimpleUploadedFile is essentially instantiated similarly to what is shown here
thumb_file = InMemoryUploadedFile(thumb_io, None, 'foo.jpg', 'image/jpeg',
thumb_io.len, None)
# Once you have a Django file-like object, you may assign it to your ImageField
# and save.
...
Let me know if you need more clarification. I have this working in my project right now, uploading to S3 using django-storages. This took me the better part of a day to properly find the solution here.
I've had to do this in a few steps, imagejpeg() in php requires a similar process. Not to say theres no way to keep things in memory, but this method gives you a file reference to both the original image and thumb (usually a good idea in case you have to go back and change your thumb size).
save the file
open it from filesystem with PIL,
save to a temp directory with PIL,
then open as a Django file for this to work.
Model:
class YourModel(Model):
img = models.ImageField(upload_to='photos')
thumb = models.ImageField(upload_to='thumbs')
Usage:
#in upload code
uploaded = request.FILES['photo']
from django.core.files.base import ContentFile
file_content = ContentFile(uploaded.read())
new_file = YourModel()
#1 - get it into the DB and file system so we know the real path
new_file.img.save(str(new_file.id) + '.jpg', file_content)
new_file.save()
from PIL import Image
import os.path
#2, open it from the location django stuck it
thumb = Image.open(new_file.img.path)
thumb.thumbnail(100, 100)
#make tmp filename based on id of the model
filename = str(new_file.id)
#3. save the thumbnail to a temp dir
temp_image = open(os.path.join('/tmp',filename), 'w')
thumb.save(temp_image, 'JPEG')
#4. read the temp file back into a File
from django.core.files import File
thumb_data = open(os.path.join('/tmp',filename), 'r')
thumb_file = File(thumb_data)
new_file.thumb.save(str(new_file.id) + '.jpg', thumb_file)
This is actual working example for python 3.5 and django 1.10
in views.py:
from io import BytesIO
from django.core.files.base import ContentFile
from django.core.files.uploadedfile import InMemoryUploadedFile
def pill(image_io):
im = Image.open(image_io)
ltrb_border = (0, 0, 0, 10)
im_with_border = ImageOps.expand(im, border=ltrb_border, fill='white')
buffer = BytesIO()
im_with_border.save(fp=buffer, format='JPEG')
buff_val = buffer.getvalue()
return ContentFile(buff_val)
def save_img(request)
if request.POST:
new_record = AddNewRecordForm(request.POST, request.FILES)
pillow_image = pill(request.FILES['image'])
image_file = InMemoryUploadedFile(pillow_image, None, 'foo.jpg', 'image/jpeg', pillow_image.tell, None)
request.FILES['image'] = image_file # really need rewrite img in POST for success form validation
new_record.image = request.FILES['image']
new_record.save()
return redirect(...)
Putting together comments and updates for Python 3+
from io import BytesIO
from django.core.files.base import ContentFile
import requests
# Read a file in
r = request.get(image_url)
image = r.content
scr = Image.open(BytesIO(image))
# Perform an image operation like resize:
width, height = scr.size
new_width = 320
new_height = int(new_width * height / width)
img = scr.resize((new_width, new_height))
# Get the Django file object
thumb_io = BytesIO()
img.save(thumb_io, format='JPEG')
photo_smaller = ContentFile(thumb_io.getvalue())
To complete for those who, like me, want to couple it with Django's FileSystemStorage:
(What I do here is upload an image, resize it to 2 dimensions and save both files.
utils.py
def resize_and_save(file):
size = 1024, 1024
thumbnail_size = 300, 300
uploaded_file_url = getURLforFile(file, size, MEDIA_ROOT)
uploaded_thumbnail_url = getURLforFile(file, thumbnail_size, THUMBNAIL_ROOT)
return [uploaded_file_url, uploaded_thumbnail_url]
def getURLforFile(file, size, location):
img = Image.open(file)
img.thumbnail(size, Image.ANTIALIAS)
thumb_io = BytesIO()
img.save(thumb_io, format='JPEG')
thumb_file = InMemoryUploadedFile(thumb_io, None, file.name, 'image/jpeg', thumb_io.tell, None)
fs = FileSystemStorage(location=location)
filename = fs.save(file.name, thumb_file)
return fs.url(filename)
In views.py
if request.FILES:
fl, thumbnail = resize_and_save(request.FILES['avatar'])
#delete old profile picture before saving new one
try:
os.remove(BASE_DIR + user.userprofile.avatarURL)
except Exception as e:
pass
user.userprofile.avatarURL = fl
user.userprofile.thumbnailURL = thumbnail
user.userprofile.save()
Here is an app that can do that: django-smartfields
from django.db import models
from smartfields import fields
from smartfields.dependencies import FileDependency
from smartfields.processors import ImageProcessor
class ImageModel(models.Model):
image = fields.ImageField(dependencies=[
FileDependency(processor=ImageProcessor(
scale={'max_width': 150, 'max_height': 150}))
])
Make sure to pass keep_orphans=True to the field, if you want to keep old files, otherwise they are cleaned up upon replacement.
For those using django-storages/-redux to store the image file on S3, here's the path I took (the example below creates a thumbnail of an existing image):
from PIL import Image
import StringIO
from django.core.files.storage import default_storage
try:
# example 1: use a local file
image = Image.open('my_image.jpg')
# example 2: use a model's ImageField
image = Image.open(my_model_instance.image_field)
image.thumbnail((300, 200))
except IOError:
pass # handle exception
thumb_buffer = StringIO.StringIO()
image.save(thumb_buffer, format=image.format)
s3_thumb = default_storage.open('my_new_300x200_image.jpg', 'w')
s3_thumb.write(thumb_buffer.getvalue())
s3_thumb.close()

Categories

Resources