I am attempting to display images from Mysql database. I am able to load the image but can not get it to display, Target here is simply a box layout which I am referring to. This code throws an error
AttributeError: 'kivy.graphics.texture.Texture' object has no attribute 'fbind'
row = mycursor.fetchall()
target = self.ids.thebox #This is a simple boxlayout
for value in row:
if value[9]:
texture = Texture.create(size=(64, 64))
image = value[9]
binary_data = image
data = io.BytesIO(binary_data)
img = CoreImage(data, ext="png").texture
new_img = Image()
new_img.texture = img
target.add_widget(new_img.texture)
I figured this out.
First load an image in form of blob data using normal mysql python and store in a variable, my case called image, you convert it as below to data then add data to CoreImage
image = value[9]
data = io.BytesIO(image)
img = CoreImage(data, ext="png").texture
Make sure you use this for your import
from kivy.uix.image import Image, CoreImage
Next ensure you add a default image within your project folder and call it using widget as follows
widget = Image(source = 'a.jpg')
Set the texture of widget to img, then add it to your target widget or parent
widget.texture = img
target.add_widget(widget)
The full working code like below:
image = value[9] #Add your data
data = io.BytesIO(image)
img = CoreImage(data, ext="png").texture
widget = Image(source = 'a.jpg')
widget.texture = img
target.add_widget(widget)
Related
I am working on making PowerPoint (.pptx) files using python-pptx package so, what I am doing adding images in slides with joining these images with a watermark using imagemagick. so, the problem I am facing is that images on which I am adding watermarks are of different sizes. some are giving good results but some not. so I want that logo can easily adjust according to the image size.
Here is my code:
from pptx import Presentation
from pptx.util import Inches,Pt
from wand.image import Image
# function to add watermark using Imagemagick
def addwatermark(pic_path,i):
with Image(filename = pic_path) as image:
with Image(filename = 'nike_black.png') as water:
print(water.width,water.height)
water.resize(2000,600)
with image.clone() as watermark:
watermark.watermark(water,0.1,10,20)
new_pic = "newimage{}.jpg".format(i)
watermark.save(filename = new_pic)
return new_pic
prs = Presentation()
for i in range(1,6):
# Changing size of ppt acc. to sample ppt
prs.slide_width = Inches(16)
prs.slide_height = Inches(9)
blank_slide_layout = prs.slide_layouts[6]
slide = prs.slides.add_slide(blank_slide_layout)
# Text box --1
text_Box = slide.shapes.add_textbox(left = Inches(3),top = Inches(0),width = Inches(2),height = Inches(1))
tf = text_Box.text_frame
p = tf.add_paragraph()
p.text = "Image With Nike LOGO"
p.font.bold = True
p.font.size = Pt(40)
# Text box --2
text_Box1 = slide.shapes.add_textbox(left = Inches(1),top = Inches(3),width = Inches(2),height = Inches(1))
tf1 = text_Box.text_frame
p = tf1.add_paragraph()
run = p.add_run()
p.level = 0
run.text = "sample section {}".format(i)
run.font.size = Pt(40)
# Image height and width acc. to sample ppt
height = Inches(5.21)
width = Inches(4.17)
pic = slide.shapes.add_picture(addwatermark("image{}.jpg".format(i),i) ,left = Inches(1),top = Inches(2), height=height, width = width)
prs.save('new.pptx')
This is what I am expecting to generate from every image
but this slide is not giving the correct output.
Can anyone tell me how can I adjust a logo dynamically?
Simply execute this code
from io import FileIO
import os
from wand.image import Image
from pptx.util import Inches
from pptx import Presentation
def add_watermark()->FileIO:
for file in os.listdir():
if file.endswith('.jpg'):
# Import the image
with Image(filename =file) as image:
# Import the watermark image
width, height = image.size
with Image(filename ='nike_black.png') as logo:
# Resize the logo image according to the image size
logo.resize(width//3, height//8)
# Clone the image in order to process
with image.clone() as watermark:
# Resize the watermark
watermark.watermark(logo)
# Save the image
watermark.save(filename ='watermarked_'+file)
def create_slide()->FileIO:
# Creating presentation object
root = Presentation()
for file in os.listdir():
if file.startswith('watermarked_'):
# Creating slide layout
first_slide_layout = root.slide_layouts[1]
slide = root.slides.add_slide(first_slide_layout)
shapes = slide.shapes
#Adding title or heading to the slide
title_shape = shapes.title
title_shape.text = f" Created By python-pptx for Watermarking "
#Adding sub-title with border to the slide
body_shape = shapes.placeholders[1]
tf = body_shape.text_frame
tf.text = f"This is a watermarked image of {file}"
with open( f'{file}','rb') as watermarked_image:
# Add the watermarked image to the slide
slide.shapes.add_picture(watermarked_image ,Inches(1), Inches(3),
width=Inches(5), height=Inches(3))
root.save("Output.pptx")
add_watermark()
create_slide()
Note:- Make sure that all your image files are in the same folder
I am trying to build a GUI that displays sequence of images as videos. The images are numpy arrays.
The code is working when I try to display one image at a time but it crashes when I try to run them as a sequence.
The code:
from tkinter import *
from scipy.io import loadmat
from PIL import ImageTk, Image
import time
data = loadmat('DepthFrames.mat')['DepthFrames'].squeeze(axis=0)
print(data.shape)
counter = 0
root = Tk()
image = ImageTk.PhotoImage(image = Image.fromarray(data[counter]))
root.title("WUDU VIDEOS LABEL TOOL")
myLabel = Label(root, image = image)
myLabel.grid(row = 0)
def changeImg():
global counter
counter +=1
print(counter)
image = ImageTk.PhotoImage(image = Image.fromarray(data[counter]))
myLabel.configure(image = image)
myLabel.image = image
def playVideo():
for i in range(10):
image = ImageTk.PhotoImage(image = Image.fromarray(data[i]))
myLabel.configure(image = image)
myLabel.image = image
time.sleep(0.03333)
my_Button = Button(text = "Play video",command = playVideo)
my_Button.grid(row = 1)
root.mainloop()
time.sleep blocks the main thread of tkinter. Your code will freeze the GUI until the for loop is completed and the image will be shown as the last image. For more details, see this post.
You need to use the after method. Something like this:
def playVideo(frame=0):
try:
image = ImageTk.PhotoImage(image = Image.fromarray(data[frame]))
except IndexError:
return
myLabel.configure(image = image)
myLabel.image = image
root.after(33, playVideo, frame+1)
I've been working on a small program to convert PNG, JPG and JPEG files to .ICO files. This was relatively simple to do, but while I was trying to display the selected PNG image in Tkinter using PIL's ImageTk, I get a strange error.
from tkinter import *
from tkinter import filedialog
import re
from PIL import Image, ImageTk
root = Tk()
pathToImage = ''
selectedImage = ''
def make_square(im, min_size=256, fill_color = (0, 0, 0)): # Puts the selected image into a black square
x, y = im.size
size = max(min_size, x, y)
new_im = Image.new('RGB', (size,size), fill_color)
new_im.paste(im, (int((size - x) / 2), int((size - y) / 2)))
return new_im
def select_image(): # Function that is run when Select PNG button is clicked
global pathToImage
pathToImage = filedialog.askopenfilename(filetypes=[('PNG Files','*.png'),('JPG Files','*.jpg'),('JPEG Files','*.jpeg')]) # Gets path to PNG, JPG or JPEG image
image = Image.open(pathToImage) # Opens image in PIL
image = make_square(im=image) # Turns image into square for ICO conversion
#!!!!!!!!!!!!!!!!!!!!! ERROR Among these 3 lines
global selectedImage # Here I try to tell Python I'm referring to the global variable selectedImage
selectedImage = (ImageTk.PhotoImage(image=pathToImage)) # selectedImage is given the value of ImageTk.PhotoImage with the source image being the path of the selected image
Label(root, image=selectedImage).pack() # Throws an error for some reason
# Rest of the code works fine
image.save('output.ico')
Label(root,text='Converted file stored in the same folder as \'PNG to ICO.py\'').pack()
Button(root,text='Select PNG', command=select_image).pack()
root.mainloop()
I've tried saving the image to display to a variable, but that doesn't seem to work either. Could anyone help point out what I did wrong? I'd really appreciate it.
There are couple of issues with your code.
In your line (ImageTk.PhotoImage(image=pathToImage)) you are passing a path (str) which is not what it should take, ImageTk.PhotoImage takes instance of Image(path). So change it to the image getting returned by make_square function.
Every time when the button is clicked, it'll create a new label if that's what you want then ignore this, if not then create your labels outside of the function select_image after you create the Button and later in the function update them.
I don't really get why you are using global when you can achieve your purpose without making variables pathToImage or selectedImage unless you want to access that image later in the program.
Here is the improved version of your code.
from tkinter import *
from tkinter import filedialog
import re
from PIL import Image, ImageTk
def make_square(im, min_size=256, fill_color = (0, 0, 0)): # Puts the selected image into a black square
x, y = im.size
size = max(min_size, x, y)
new_im = Image.new('RGB', (size,size), fill_color)
new_im.paste(im, (int((size - x) / 2), int((size - y) / 2)))
return new_im
def select_image(): # Function that is run when Select PNG button is clicked
pathToImage = filedialog.askopenfilename(filetypes=[('PNG Files','*.png'),('JPG Files','*.jpg'),('JPEG Files','*.jpeg')])
image = Image.open(str(pathToImage)) # Opens image in PIL
image = make_square(im=image) # Turns image into square for ICO conversion
selectedImage = ImageTk.PhotoImage(image=image)
imglabel.img = selectedImage # create a reference of the image
imglabel['image'] = selectedImage
# selectedImage is given the value of ImageTk.PhotoImage with the source image being the path of the selected image
# Rest of the code works fine
image.save('output.ico', 'ICO')
infolabel['text'] = 'Converted file stored in the same folder as \'PNG to ICO.py\''
root = Tk()
but1 = Button(root,text='Select PNG', command=select_image)
but1.pack()
imglabel = Label(root)
imglabel.pack()
infolabel = Label(root)
infolabel.pack()
root.mainloop()
Some weeks ago i load a png image into my Tkinter Canvas and drawed with create_image, but now i can't do this anymore, i tried convert with ImageTk but png did not display
I have the following code:
load = Image.open("mouse.png")
self.img = ImageTk.PhotoImage(load)
self.draw.create_image(100,100,image=self.img,anchor = NW)
self.draw.image = self.img
I just need to present a png image
Try this
vSmallIco = (15, 15)
self.original = Image.open('.//data//img//plus.png')
resized = self.original.resize(vSmallIco, Image.ANTIALIAS)
self.plusIco = ImageTk.PhotoImage(resized)
self.medIco = ttk.Label(self.mf, image=self.plusIco, style='Main.TLabel')
this is done with this import
from PIL import Image, ImageTk
Also, please use a *.png image if you wish to use png.
I'm trying to take a .GIF file, open it with PIL, and write a text on it frame by frame. However, the code only saves an image (1 frame;it doesn't move like a .GIF file.
The code:
import giphypop
from urllib import request
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
g = giphypop.Giphy()
img = g.translate("dog")
request.urlretrieve(img.media_url, "test.gif")
opened_gif = Image.open("test.gif")
opened_gif.load()
opened_gif.seek(1)
try:
while 1:
slide = opened_gif.seek(opened_gif.tell()+1)
draw = ImageDraw.Draw(slide)
# font = ImageFont.truetype(<font-file>, <font-size>)
font = ImageFont.truetype("sans-serif.ttf", 16)
# draw.text((x, y),"Sample Text",(r,g,b))
draw.text((0, 0),"Sample Text",(255,255,255),font=font)
except EOFError:
pass # end of sequence
except AttributeError:
print("Couldn't use this slide")
opened_gif.save('test_with_caption.gif')
Code from https://github.com/python-pillow/Pillow/issues/3128 that, nicely enough, solves this exact problem.
from PIL import Image, ImageDraw, ImageSequence
import io
im = Image.open('Tests/images/iss634.gif')
# A list of the frames to be outputted
frames = []
# Loop over each frame in the animated image
for frame in ImageSequence.Iterator(im):
# Draw the text on the frame
d = ImageDraw.Draw(frame)
d.text((10,100), "Hello World")
del d
# However, 'frame' is still the animated image with many frames
# It has simply been seeked to a later frame
# For our list of frames, we only want the current frame
# Saving the image without 'save_all' will turn it into a single frame image, and we can then re-open it
# To be efficient, we will save it to a stream, rather than to file
b = io.BytesIO()
frame.save(b, format="GIF")
frame = Image.open(b)
# Then append the single frame image to a list of frames
frames.append(frame)
# Save the frames as a new image
frames[0].save('out.gif', save_all=True, append_images=frames[1:])