Comparing cursor icon bitmaps in python - python

I want to check whether the cursor icon has changed by comparing the bitmaps.
So far I have tried the snippet below, but it does not work properly.
import win32api, win32con, win32gui, win32ui
info = win32gui.GetCursorInfo()
hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
hbmp = win32ui.CreateBitmap()
hbmp.CreateCompatibleBitmap(hdc, 35, 35)
hdc = hdc.CreateCompatibleDC()
hdc.DrawIcon((0,0), info[1])
hbmp.SaveBitmapFile(hdc, 'icon.bmp')
This code just produces a black rectangle bitmap (found most of it on the internet). In general I would rather not save the bitmap and just compare the 2 bitmaps as images with pillow, but i don't know how to do that.

After you have created the memory DC and the memory bitmap, SelectObject is used to select the memory bitmap into the memory DC. Only in this way can the bitmap work.
Modified codeļ¼š
import win32api, win32con, win32gui, win32ui
info = win32gui.GetCursorInfo()
hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
hbmp = win32ui.CreateBitmap()
hbmp.CreateCompatibleBitmap(hdc, 35, 35)
hdc = hdc.CreateCompatibleDC()
hdc.SelectObject(hbmp)
hdc.DrawIcon((0,0), info[1])
hbmp.SaveBitmapFile(hdc, 'icon.bmp')
win32gui.DestroyIcon(info[1])
win32gui.DeleteObject(hbmp.GetHandle())
hdc.DeleteDC()
When you no longer need the bitmap, call the DeleteObject function to delete it.
Similar operations apply to cursor and memory DC release.

Related

How can I get the logo/icon of an app with path

import os
path = r'C:\Users\John\AppData\Roaming\Spotify\Spotify.exe'
os.startfile(path)
What I want, in this situation for example we have Spotify, is to save the logo somewhere based on its path.
I want to use it for a tkinter app I have built.
Maybe something in the idea of:
my_image = get_image_from_path(file=r'C:\Users\John\AppData\Roaming\Spotify\Spotify.exe')
This draws an icon from a given executable into a bitmap, and saves the bitmap.
My web searching to answer this question brought up a thread on the pywin32 mailing list from 2009. I don't remember writing it, but this is the code from my reply:
import win32ui
import win32gui
import win32con
import win32api
ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON)
ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON)
large, small = win32gui.ExtractIconEx("c:/windows/system32/shell32.dll",0)
win32gui.DestroyIcon(large[0])
hdc = win32ui.CreateDCFromHandle( win32gui.GetDC(0) )
hbmp = win32ui.CreateBitmap()
hbmp.CreateCompatibleBitmap( hdc, ico_x, ico_y )
hdc = hdc.CreateCompatibleDC()
hdc.SelectObject( hbmp )
hdc.DrawIcon( (0,0), small[0] )
hbmp.SaveBitmapFile( hdc, "save.bmp" )

Disable resizing for python console application in Windows

Here is a code to disable resizing using c++
How to change console window style at runtime?
HWND consoleWindow = GetConsoleWindow();
SetWindowLong(consoleWindow, GWL_STYLE, GetWindowLong(consoleWindow, GWL_STYLE) & ~WS_MAXIMIZEBOX & ~WS_SIZEBOX);
However, I want to use this code in python. It's my effort so far:
def fix_borders():
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
hWnd = kernel32.GetConsoleWindow()
kernel32.SetWindowLong(hWnd, GWL_STYLE,
kernel32.GetWindowLong(consoleWindow, GWL_STYLE) & ~WS_MAXIMIZEBOX & ~WS_SIZEBOX)
However, SetWindowLong isn't recognized and I don't know how to import other constants...
This is how I solved it still utilizing ctypes and using win32api (definitely not the most elegant solution though):
def lock_resize():
while True:
STDOUT = -11
hdl = windll.kernel32.GetStdHandle(STDOUT)
rect = ct.wintypes.SMALL_RECT(0, 50, 50, 80) # (left, top, right, bottom)
windll.kernel32.SetConsoleWindowInfo(hdl, True, byref(rect))
_thread.start_new_thread(lock_resize,()) #using the _thread module to keep everything else running

How to get the screenshot of a tkinter window

I am trying to build a program which gets me an enlarged photo of the text I want, for this I decided to use tkinter, win32gui and pygetwindow modules after taking some tips from already asked problems on stack overflow am having the following problems:
(1)I don't know how to get the hwnd value of the tkinter window which I created.
(2)I can't get hwnd value even if I know how to get it as the window is created after the complete code has run.
So please suggest me solutions to the problem
This is my code:
from tkinter import *
import win32gui
import pygetwindow as gw
#making the tkinter window
root = Tk()
root.title('DaysLeft')
#getting all the windows with their hwnd values
hwnd=gw.getAllWindows()
print(hwnd)
win32gui.SetForegroundWindow(hwnd)
bbox = win32gui.GetWindowRect(hwnd)
img = ImageGrab.grab(bbox)
img.show()
mainloop()
The above code gives error below as expected:.
line 26, in <module>
win32gui.SetForegroundWindow(hwnd)
TypeError: The object is not a PyHANDLE object
You can use PIL for taking a screenshot and win32gui or pygetwindow to get windows location.
Install PIL by saying
pip install Pillow
then your working code would be:
from tkinter import *
from win32gui import FindWindow, GetWindowRect
import pygetwindow as gw
from PIL import ImageGrab
def ss():
win = gw.getWindowsWithTitle('DaysLeft')[0]
winleft = win.left+9
wintop = win.top+38 #change 38 to 7 to not capture the titlebar
winright = win.right-9
winbottom = win.bottom-9
final_rect = (winleft,wintop,winright,winbottom)
img = ImageGrab.grab(final_rect)
img.save('Required Image.png')
#making the tkinter window
root = Tk()
root.title('DaysLeft')
root.after(3000,ss)
root.mainloop()
Why am i subtracting some amount from the pixels? its because, windows has decorations like drop shadow effect to the windows, which are also part of the windows and will be included in the screenshot, so i used this to get rid of those extra pixels.
Or if your still reluctant on using win32gui then, change the function to:
from win32gui import FindWindow, GetWindowRect
from PIL import ImageGrab
......
def ss():
win = FindWindow(None, 'DaysLeft')
rect = GetWindowRect(win)
list_rect = list(rect)
list_frame = [-9, -38, 9, 9] #change -38 to -7 to not capture the titlebar
final_rect = tuple((map(lambda x,y:x-y,list_rect,list_frame))) #subtracting two lists
img = ImageGrab.grab(bbox=final_rect)
img.save('Image.png')
What is after method? It just calls the function after 3000 ms, i.e, 3 seconds. We are basically giving the system some time to build the GUI and capture screenshot.
Hope it helped, do let me know if any errors or doubts.
Cheers

how to change background using render.py in CGKIT

i am working with CGKIT in my project, i came across a situation that i must use only render.py file and change the background of the picture.
i know how to use viewer.py and change the picture but implementing that i.e. changing background in GLOBALS it is not changing the background as per render.py
so please any one help me out
# Use the previously rendered texture map
from time import sleep
import Image
from cgkit.cgtypes import vec3, mat4
from cgkit.cmds import load, worldObject
from cgkit.glmaterial import GLMaterial, GLTexture
from cgkit.scene import getScene
from cgkit.sceneglobals import Globals
from OpenGL.GL import glReadPixels
from pyglet.gl import GL_RGBA, GL_UNSIGNED_BYTE, GL_DECAL
Globals(
resolution=(512,512),
up = (0,1,0),
background=(1,1,1,1),
output = "kishoreGoodBoy.png",
)
load("singleSofa.obj")
model = worldObject("small_sofa_dark_grey")
mat = GLMaterial(
diffuse = (0,1,0),
texture = GLTexture(
"final1.png",
mode = GL_DECAL,
transform = mat4().scaling(vec3(1,-1,1))
)
)
model.setMaterial(mat)
as per code i had textre file and so that i am directing it to a .PNG file and it is saving. but it is coming with a black background so i need to change the background clour

Scale an image in GTK

In GTK, how can I scale an image? Right now I load images with PIL and scale them beforehand, but is there a way to do it with GTK?
Load the image from a file using gtk.gdk.Pixbuf for that:
import gtk
pixbuf = gtk.gdk.pixbuf_new_from_file('/path/to/the/image.png')
then scale it:
pixbuf = pixbuf.scale_simple(width, height, gtk.gdk.INTERP_BILINEAR)
Then, if you want use it in a gtk.Image, crate the widget and set the image from the pixbuf.
image = gtk.Image()
image.set_from_pixbuf(pixbuf)
Or maybe in a direct way:
image = gtk.image_new_from_pixbuf(pixbuf)
It might be more effective to simply scale them before loading. I especially think so since I use these functions to load in 96x96 thumbnails from sometimes very large JPEGs, still very fast.
gtk.gdk.pixbuf_new_from_file_at_scale(..)
gtk.gdk.pixbuf_new_from_file_at_size(..)
Scale image from URL. ( scale reference )
import pygtk
pygtk.require('2.0')
import gtk
import urllib2
class MainWin:
def destroy(self, widget, data=None):
print "destroy signal occurred"
gtk.main_quit()
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect("destroy", self.destroy)
self.window.set_border_width(10)
self.image=gtk.Image()
self.response=urllib2.urlopen(
'http://192.168.1.11/video/1024x768.jpeg')
self.loader=gtk.gdk.PixbufLoader()
self.loader.set_size(200, 100)
#### works but throwing: glib.GError: Unrecognized image file format
self.loader.write(self.response.read())
self.loader.close()
self.image.set_from_pixbuf(self.loader.get_pixbuf())
self.window.add(self.image)
self.image.show()
self.window.show()
def main(self):
gtk.main()
if __name__ == "__main__":
MainWin().main()
*EDIT: (work out fix) *
try:
self.loader=gtk.gdk.PixbufLoader()
self.loader.set_size(200, 100)
# ignore tihs:
# glib.GError: Unrecognized image file format
self.loader.write(self.response.read())
self.loader.close()
self.image.set_from_pixbuf(self.loader.get_pixbuf())
except Exception, err:
print err
pass
Just FYI, here is a solution which scales the image based on window size (Implying you are implementing this in a class which extends GtkWindow).
let [width, height] = this.get_size(); // Get size of GtkWindow
this._image = new GtkImage();
let pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filePath,width,height,true);
this._image.set_from_pixbuf(pixbuf);
anyone doing this in C. This is how it's done
//Assuming you already loaded the file and saved the filename
//GTK_IMAGE(image) is the container used to display the image
GdkPixbuf *pb;
pb = gdk_pixbuf_new_from_file(file_name, NULL);
pb = gdk_pixbuf_scale_simple(pb,700,700,GDK_INTERP_BILINEAR);
gtk_image_set_from_pixbuf(GTK_IMAGE(image), pb);
actually when we use
gdk_pixbuf_scale_simple(pb,700,700,GDK_INTERP_BILINEAR); this function causes memory leakage (If we monitor task manager the memory requirement goes on increasing till it kills the process) when used with a timer event. How to solve that

Categories

Resources