from Tkinter import * root = Tk() cv = Canvas(root) cv.create_rectangle(10,10,50,50) cv.pack() root.mainloop()
I want to convert canvas content to a bitmap or other image, and then do other operations, such as rotating or scaling the image, or changing its coordinates.
Bitmaps can improve efficiency to show if I am no longer drawing.
What should I do?
function convertCanvasToImage() { let canvas = document. getElementById("canvas"); let image = new Image(); image. src = canvas. toDataURL(); return image; } let pnGImage = convertCanvasToImage(); document.
The Canvas is a rectangular area intended for drawing pictures or other complex layouts. You can place graphics, text, widgets or frames on a Canvas.
I have found a great way of doing this which is really helpful. For it, you need the PIL module. Here is the code:
from PIL import ImageGrab def getter(widget): x=root.winfo_rootx()+widget.winfo_x() y=root.winfo_rooty()+widget.winfo_y() x1=x+widget.winfo_width() y1=y+widget.winfo_height() ImageGrab.grab().crop((x,y,x1,y1)).save("file path here")
What this does is you pass a widget name into the function. The command root.winfo_rootx()
and the root.winfo_rooty()
get the pixel position of the top left of the overall root
window.
Then, the widget.winfo_x()
and widget.winfo_y()
are added to, basically just get the pixel coordinate of the top left hand pixel of the widget which you want to capture (at pixels (x,y) of your screen).
I then find the (x1,y1) which is the bottom left pixel of the widget. The ImageGrab.grab()
makes a printscreen, and I then crop it to only get the bit containing the widget. Although not perfect, and won't make the best possible image, this is a great tool for just getting a image of any widget and saving it.
If you have any questions, post a comment! Hope this helped!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With