Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert canvas content to an image?

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?

like image 242
liupeixin Avatar asked Mar 27 '12 08:03

liupeixin


People also ask

How to convert a canvas into an image?

function convertCanvasToImage() { let canvas = document. getElementById("canvas"); let image = new Image(); image. src = canvas. toDataURL(); return image; } let pnGImage = convertCanvasToImage(); document.

How do you define a canvas in Python?

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.


1 Answers

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!

like image 69
B.Jenkins Avatar answered Sep 22 '22 12:09

B.Jenkins