def OnSize(self, event):
# The Buffer init is done here, to make sure the buffer is always
# the same size as the Window
Size = self.canvas.GetClientSize()
if Size.width <= 0 or Size.height <= 0:
return
Size.width = max(1, Size.width)
Size.height = max(1, Size.height)
# Make new offscreen bitmap: this bitmap will always have the
# current drawing in it, so it can be used to save the image to
# a file, or whatever.
#self._Buffer = wx.Bitmap(Size.width, Size.height)
if IsNotWX4():
self._img = wx.EmptyImage(Size.width,Size.height)
self._Buffer = wx.BitmapFromImage(self._img)
else:
self._img = wx.Image(Size.width,Size.height)
self._Buffer = wx.Bitmap(self._img)
self._Buffer.SetHeight(Size.height)
self._Buffer.SetWidth(Size.width)
self._setSize()
self.last_PointLabel = None # reset pointLabel
if self.last_draw is None:
self.Clear()
else:
graphics, xSpec, ySpec = self.last_draw
self._Draw(graphics, xSpec, ySpec)
python类Image()的实例源码
def display_matches(self):
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
self.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.images = []
self.labels = []
m = self.session.matches()
for i in range(len(m)):
match = m[i]
# Thumb
fd = urlopen(match.user.thumbnails[0])
file = io.BytesIO(fd.read())
img = wx.Image(file, wx.BITMAP_TYPE_ANY)
self.images.append(wx.StaticBitmap(self.panel, wx.ID_ANY,
wx.Bitmap(img)))
self.images[i].Bind(wx.EVT_BUTTON, self.onClick)
# Label for name
self.labels.append(wx.StaticText(self.panel, label=match.user.name))
# Add to sizer
self.mainSizer.Add(self.labels[i], 0, wx.ALL, 5)
self.mainSizer.Add(self.images[i], 0, wx.ALL, 5)
self.mainSizer.Add(self.sizer, 0, wx.ALL, 5)
self.panel.SetSizer(self.mainSizer)
self.panel.Layout()
self.panel.Refresh()
def ConvertWXToPIL(self, bmp):
""" Convert wx.Image Into PIL Image. """
width = bmp.GetWidth()
height = bmp.GetHeight()
im = wx.EmptyImage(width, height)
im.fromarray("RGBA", (width, height), bmp.GetData())
return im
# ------------------------------------------------------------
# ImFrame.ConvertPILToWX()
# Expropriated from Andrea Gavana's
# ShapedButton.py in the wxPython dist
# ------------------------------------------------------------
def ConvertPILToWX(self, pil, alpha=True):
""" Convert PIL Image Into wx.Image. """
if alpha:
image = wx.EmptyImage(*pil.size)
image.SetData(pil.convert("RGB").tostring())
image.SetAlphaData(pil.convert("RGBA").tostring()[3::4])
else:
image = wx.EmptyImage(pil.size[0], pil.size[1])
new_image = pil.convert('RGB')
data = new_image.tostring()
image.SetData(data)
return image
def OnInit(self):
"""Create the Image Application."""
ImFrame(None, 'wxImage Example')
return True
# ---------------------------------------------------------------------
# If this file is running as main or a standalone test, begin execution here.
# ---------------------------------------------------------------------
def updateAfterRotate(self,evt):
screenShotPath = os.path.join(os.getcwd(), "screenShot", "screenshot.png")
img = Image.open(screenShotPath)
out = img.rotate(90,expand=1)
out.save(screenShotPath)
wx.CallAfter(pub.sendMessage, "update", msg=screenShotPath)
def __init__(self,parent,id,title):
wx.Frame.__init__(self,parent,id,title,size=(475,600))
self.parent = parent
self.initialize()
# Exit
exit_button = wx.Button(self, label="Exit", pos=(240+75,550))
exit_button.Bind(wx.EVT_BUTTON, self.onClose)
# robot = "/home/pi/Desktop/GoBox/Troubleshooting_GUI/dex.png"
# png = wx.Image(robot, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
# wx.StaticBitmap(self, -1, png, (0, 0), (png.GetWidth()-320, png.GetHeight()-20))
# self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground) # Sets background picture
#----------------------------------------------------------------------
def get(self, iconname):
try:
image = 'img\\' + self.img_dict[iconname]
except KeyError:
print 'Image: "{}" not found!'.format(iconname)
image = 'img\\' + self.img_dict['toilet']
wximage = wx.Image(self.path + image, wx.BITMAP_TYPE_PNG).ConvertToBitmap()
return wximage
def ShowSplashScreen(self):
from wx.lib.agw.advancedsplash import AdvancedSplash
bmp = wx.Image(self.splashPath).ConvertToBitmap()
self.splash = AdvancedSplash(None, bitmap=bmp)
# process all events
# even the events generated by splash themself during showing
if wx.Platform == '__WXMSW__':
self.splash.Show()
self.splash.ProcessEvent(wx.PaintEvent())
else:
for i in range(0, 30):
wx.Yield()
time.sleep(0.01)
def validate_photo(self,path):
import wx
img = wx.Image(path, wx.BITMAP_TYPE_ANY)
# scale the image, preserving the aspect ratio
W=img.GetWidth()
H=img.GetHeight()
if W>120 or H>120 or W<100 or H<100:
return False," Image Height and Width must be between 100-120 pixels"
return [True]
def ConvertWXToPIL(self, bmp):
""" Convert wx.Image Into PIL Image. """
width = bmp.GetWidth()
height = bmp.GetHeight()
im = wx.EmptyImage(width, height)
im.fromarray("RGBA", (width, height), bmp.GetData())
return im
# ------------------------------------------------------------
# ImFrame.ConvertPILToWX()
# Expropriated from Andrea Gavana's
# ShapedButton.py in the wxPython dist
# ------------------------------------------------------------
def ConvertPILToWX(self, pil, alpha=True):
""" Convert PIL Image Into wx.Image. """
if alpha:
image = wx.EmptyImage(*pil.size)
image.SetData(pil.convert("RGB").tostring())
image.SetAlphaData(pil.convert("RGBA").tostring()[3::4])
else:
image = wx.EmptyImage(pil.size[0], pil.size[1])
new_image = pil.convert('RGB')
data = new_image.tostring()
image.SetData(data)
return image
def OnInit(self):
"""Create the Image Application."""
ImFrame(None, 'wxImage Example')
return True
# ---------------------------------------------------------------------
# If this file is running as main or a standalone test, begin execution here.
# ---------------------------------------------------------------------
def __init__(self, parent, id):
# create the panel
wx.Panel.__init__(self, parent, id)
try:
# pick an image file you have in the working
# folder you can load .jpg .png .bmp or
# .gif files
image_file = 'big_cat.jpg'
bmp1 = wx.Image(
image_file,
wx.BITMAP_TYPE_ANY).ConvertToBitmap()
# image's upper left corner anchors at panel
# coordinates (0, 0)
self.bitmap1 = wx.StaticBitmap(
self, -1, bmp1, (0, 0))
# show some image details
str1 = "%s %dx%d" % (image_file, bmp1.GetWidth(),
bmp1.GetHeight())
parent.SetTitle(str1)
except IOError:
print("Image file %s not found" % imageFile)
raise SystemExit
# button goes on the image --> self.bitmap1 is the
# parent
self.button1 = wx.Button(
self.bitmap1, label='Button1',
pos=(8, 8))
def createWidgets(self):
instructions = 'Browse for an image'
img = wx.Image(240,240)
self.imageCtrl = wx.StaticBitmap(self.panel, wx.ID_ANY,
wx.Bitmap(img))
instructLbl = wx.StaticText(self.panel, label=instructions)
self.photoTxt = wx.TextCtrl(self.panel, size=(200,-1))
browseBtn = wx.Button(self.panel, label='Browse')
browseBtn.Bind(wx.EVT_BUTTON, self.onBrowse)
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
self.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.mainSizer.Add(wx.StaticLine(self.panel, wx.ID_ANY),
0, wx.ALL|wx.EXPAND, 5)
self.mainSizer.Add(instructLbl, 0, wx.ALL, 5)
self.mainSizer.Add(self.imageCtrl, 0, wx.ALL, 5)
self.sizer.Add(self.photoTxt, 0, wx.ALL, 5)
self.sizer.Add(browseBtn, 0, wx.ALL, 5)
self.mainSizer.Add(self.sizer, 0, wx.ALL, 5)
self.panel.SetSizer(self.mainSizer)
self.mainSizer.Fit(self.frame)
self.panel.Layout()
def initToolbar(self):
"""
Initialize the toolbar
"""
self.toolbar = self.CreateToolBar()
self.toolbar.SetToolBitmapSize((16,16))
open_ico = wx.ArtProvider.GetBitmap(
wx.ART_FILE_OPEN, wx.ART_TOOLBAR, (16,16))
openTool = self.toolbar.AddSimpleTool(wx.ID_ANY, open_ico,
"Open", "Open an Image Directory")
self.Bind(wx.EVT_MENU, self.onOpenDirectory, openTool)
self.toolbar.Realize()
def __init__(self):
"""Constructor"""
BASEURL = "http://127.0.0.1:8000"
self.InitUpdates(BASEURL,
BASEURL + 'ChangeLog.txt')
self.CheckForUpdate()
frame = ViewerFrame()
self.SetTopWindow(frame)
self.SetAppDisplayName('Image Viewer')
return True
def load(cls, gfx_type, path):
if path in cls._gfx_cache[gfx_type]["loaded"]:
return cls._gfx_cache[gfx_type]["loaded"][path]
gfx = wx.Bitmap(path) if gfx_type == "bitmap" else wx.Image(path)
cls._gfx_cache[gfx_type]["loaded"][path] = gfx
return gfx
def create_main_panel(self):
# Panels
self.img_panel = wx.Panel(self)
self.joy_panel = wx.Panel(self)
self.record_panel = wx.Panel(self)
# Images
img = wx.Image(320,240)
self.image_widget = wx.StaticBitmap(self.img_panel, wx.ID_ANY, wx.Bitmap(img))
# Joystick
self.init_plot()
self.PlotCanvas = FigCanvas(self.joy_panel, wx.ID_ANY, self.fig)
# Recording
self.txt_outputDir = wx.TextCtrl(self.record_panel, wx.ID_ANY, pos=(5,0), size=(320,30))
uid = datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
self.txt_outputDir.ChangeValue("samples/" + uid)
self.btn_record = wx.Button(self.record_panel, wx.ID_ANY, label="Record", pos=(335,0), size=(100,30))
self.Bind(wx.EVT_BUTTON, self.on_btn_record, self.btn_record)
self.Bind(wx.EVT_UPDATE_UI, self.on_update_btn_record, self.btn_record)
# sizers
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(self.img_panel, 0, wx.ALL, 5)
sizer.Add(self.joy_panel, 0, wx.ALL, 5)
mainSizer_v = wx.BoxSizer(wx.VERTICAL)
mainSizer_v.Add(sizer, 0 , wx.ALL, 5)
mainSizer_v.Add(self.record_panel, 0 , wx.ALL, 5)
# finalize layout
self.SetAutoLayout(True)
self.SetSizer(mainSizer_v)
self.Layout()
def NewFile(self,e):
wcd='All files(*)|*'
dest = 'stopgo_project_'
destid = int(time.time())
try:
dirname = self.clargs['project']
except OSError:
dirname = os.path.expanduser('~')
except:
dirname = os.path.join(os.path.expanduser('~'),self.myprefs['dir'])
sd = wx.FileDialog(self, message='Save file as...',
defaultDir=dirname, defaultFile='stopgo_project_' + str(destid),
wildcard=wcd,
style=wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
if sd.ShowModal() == wx.ID_OK:
projnam = sd.GetFilename()
projpath= os.path.join(sd.GetPath(),projnam)
# make the directory
# the OS does this for us but just in case..
#if not os.path.exists( os.path.dirname(projpath) ):
#os.makedirs( os.path.dirname(projpath))
# make image dir
os.makedirs( os.path.join(os.path.dirname(projpath),'images'))
dbfile = projpath
self.imgdir = os.path.join(os.path.dirname(projpath), 'images')
logging.exception(dbfile)
logging.exception(projpath)
logging.exception(self.imgdir)
self.con = sq.connect(dbfile, isolation_level=None )
self.cur = self.con.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS Project(Id INTEGER PRIMARY KEY, Path TEXT, Name TEXT, [timestamp] timestamp)")
self.cur.execute("CREATE TABLE IF NOT EXISTS Timeline(Id INTEGER PRIMARY KEY, Image TEXT, Blackspot INT)")
self.cur.execute("INSERT INTO Project(Path, Name, timestamp) VALUES (?,?,?)", ("images", "StopGo Project", datetime.now() ))
#self.con.close()
self.BindKeys(dbfile)
sb = self.GetStatusBar()
stat = os.path.basename(projpath) + ' created'
sb.SetStatusText(stat, 0)
sb.SetStatusText('', 1)
sd.Destroy()