def OnCopyBitmap(self, evt): dlg = wx.FileDialog(self, "Choose a bitmap to copy", wildcard="*.bmp") if dlg.ShowModal() == wx.ID_OK: bmp = wx.Bitmap(dlg.GetPath(), wx.BITMAP_TYPE_BMP) bmpdo = wx.BitmapDataObject(bmp) if wx.TheClipboard.Open(): wx.TheClipboard.SetData(bmpdo) wx.TheClipboard.Close() wx.MessageBox( "The bitmap is now in the Clipboard. Switch to a graphics\n" "editor and try pasting it in...") else: wx.MessageBox( "There is no data in the clipboard in the required format", "Error") dlg.Destroy()
def CopyRBand(self): # get rubberband extent ext = self.rband.getCurrentExtent() # trivial case if ext is None: return # convert the region into image space rect = wx.Rect(int(ext[0] / self.r + .5), int(ext[1] / self.r + .5), int((ext[2] - ext[0]) / self.r + .5), int((ext[3] - ext[1]) / self.r + .5)) # create bitmap data object clipdata = wx.BitmapDataObject() crop = self.wximg.GetSubImage(rect) clipdata.SetBitmap(wx.Bitmap(crop)) # copy to the clipboard if wx.TheClipboard.Open(): wx.TheClipboard.SetData(clipdata) wx.TheClipboard.Close()
def OnCopyToClipboard(self, event): try: bitmap = wx.Bitmap(self.thumbFileName, wx.BITMAP_TYPE_JPEG) except: return d = wx.BitmapDataObject(bitmap) if wx.TheClipboard.Open(): wx.TheClipboard.SetData(d) wx.TheClipboard.Flush() wx.TheClipboard.Close() Utils.MessageOK( self, u'\n\n'.join([ _('Photo Copied to Clipboard.'), _('You can now Paste it into another program.') ]), _('Copy to Clipboard Succeeded')) else: Utils.MessageOK(self, _('Unable to Copy Photo to Clipboard.'), _('Copy Failed'), iconMask=wx.ICON_ERROR)
def set_data(self, data): if _backend == "gtk2": if isinstance(data, (unicode, str)): self._clipboard.set_text(data) elif isinstance(data, Image): self._clipboard.set_image(data._image) elif _backend == "gtk3": if isinstance(data, (unicode, str)): self._clipboard.set_text(str(data), -1) elif isinstance(data, Image): self._clipboard.set_image(data._image) elif _backend == "wx": if isinstance(data, (unicode, str)): data = wx.TextDataObject(data) elif isinstance(data, Image): data = wx.BitmapDataObject(wx.BitmapFromImage(data._image)) self._clipboard.AddData(data) elif _backend == "win32": pass elif _backend == "objc": pass
def get_clipboard(self): """Returns the clipboard content If a bitmap is contained then it is returned. Otherwise, the clipboard text is returned. """ bmpdata = wx.BitmapDataObject() textdata = wx.TextDataObject() if self.clipboard.Open(): is_bmp_present = self.clipboard.GetData(bmpdata) self.clipboard.GetData(textdata) self.clipboard.Close() else: wx.MessageBox(_("Can't open the clipboard"), _("Error")) if is_bmp_present: return bmpdata.GetBitmap() else: return textdata.GetText()
def onPasteImage(self, event): bdo = wx.BitmapDataObject() self.clipboard.Open() self.clipboard.GetData(bdo) self.clipboard.Close() bmp = bdo.GetBitmap() #print bmp.SaveFile("foo.png", wx.BITMAP_TYPE_PNG) #buf = bytearray([0]*4*bmp.GetWidth()*bmp.GetHeight()) #bmp.CopyToBuffer(buf, wx.BitmapBufferFormat_RGBA) #image = pygame.image.frombuffer(buf, (bmp.getWidth(), bmp.getHeight()), "RBGA") data = bmp.ConvertToImage().GetData() image = pygame.image.fromstring(data, (bmp.GetWidth(), bmp.GetHeight()), "RGB") obj = objects.Image({ "image": image, "rect": image.get_rect() }, self.viewer, isUserObject=True) self.addObject(obj) self.onObjectCreationCompleted(obj)
def StartDragOpperation(self): # pickle the lines list linesdata = pickle.dumps(self.lines) # create our own data format and use it in a # custom data object ldata = wx.CustomDataObject(CUSTOM_DATA_FORMAT) ldata.SetData(linesdata) # Also create a Bitmap version of the drawing size = self.GetSize() bmp = wx.Bitmap(size.width, size.height) dc = wx.MemoryDC() dc.SelectObject(bmp) dc.SetBackground(wx.WHITE_BRUSH) dc.Clear() self.DrawSavedLines(dc) dc.SelectObject(wx.NullBitmap) # Now make a data object for the bitmap and also a composite # data object holding both of the others. bdata = wx.BitmapDataObject(bmp) data = wx.DataObjectComposite() data.Add(ldata) data.Add(bdata) # And finally, create the drop source and begin the drag # and drop operation dropSource = wx.DropSource(self) dropSource.SetData(data) self.log.WriteText("Beginning DragDrop\n") result = dropSource.DoDragDrop(wx.Drag_AllowMove) self.log.WriteText("DragDrop completed: %s\n" % dragResultNames[result]) if result == wx.DragMove: self.lines = [] self.Refresh()
def clipboard2file(check_for_filename=False): if wx.TheClipboard.IsOpened(): return False if not wx.TheClipboard.Open(): return False data_obj = wx.TextDataObject() got_it = wx.TheClipboard.GetData(data_obj) if got_it: clipboard_text_content = data_obj.Text wx.TheClipboard.Close() if check_for_filename: try: io.open(clipboard_text_content).close() return clipboard_text_content except IOError: _log.exception('clipboard does not seem to hold filename: %s', clipboard_text_content) fname = gmTools.get_unique_filename(prefix='gm-clipboard-', suffix='.txt') target_file = io.open(fname, mode='wt', encoding='utf8') target_file.write(clipboard_text_content) target_file.close() return fname data_obj = wx.BitmapDataObject() got_it = wx.TheClipboard.GetData(data_obj) if got_it: fname = gmTools.get_unique_filename(prefix='gm-clipboard-', suffix='.png') bmp = data_obj.Bitmap.SaveFile(fname, wx.BITMAP_TYPE_PNG) wx.TheClipboard.Close() return fname wx.TheClipboard.Close() return None
def OnCopyToClipboard( self, event ): try: bitmap = wx.Bitmap( self.thumbFileName, wx.BITMAP_TYPE_JPEG ) except: return if not wx.TheClipboard.Open(): Utils.MessageOK( self, _('Cannot open Clipboard.'), _('Copy Failed'), iconMask=wx.ICON_ERROR ) return d = wx.BitmapDataObject( bitmap ) try: wx.TheClipboard.SetData( d ) wx.TheClipboard.Flush() Utils.MessageOK( self, u'\n\n'.join([_('Photo Copied to Clipboard.'), _('You can now Paste it into another program.')]), _('Copy to Clipboard Succeeded') ) except Exception as e: Utils.logException( e, sys.exc_info() ) Utils.MessageOK( self, u'{}:\n\n{}'.format( _('Error copying Clipboard'), e ), _('Copy Failed'), iconMask=wx.ICON_ERROR ) finally: wx.TheClipboard.Close()
def OnPaste(self, event): clip = wx.TheClipboard clip.Open() try: data = wx.BitmapDataObject() try: clip.GetData(data) except: wx.LogError(_('Not a picture')) else: self.modeChoice.SetSelection(0) self.setMode('Move') self.snapshot() self.dragbmp = data.GetBitmap() self.dragsrcrect = -1, -1, 0, 0 self.dragpos = 0, 0 self.sel = 0, 0, self.dragbmp.GetWidth( ) - 1, self.dragbmp.GetHeight() - 1 self.mDC.DrawBitmap(self.dragbmp, 0, 0) self.editWindow.Refresh() self.imageModified() finally: clip.Close()
def OnGraphPopupMenu(self, event): if event.GetId() == 1: if wx.TheClipboard.Open(): wx.TheClipboard.SetData( wx.BitmapDataObject(self.static_image.GetBitmap()))
def OnKeyDown(self, evt): global SCALE_SPEED global ADJUST_SCALE_SPEED global ALL_FRAME global LANGUAGE_TYPE tempFrame = [] keycode = evt.GetKeyCode() ctrldown = evt.ControlDown() shiftdown = evt.ShiftDown() altdown = evt.AltDown() #print (keycode) #,ctrldown #print wx.WXK_CONTROL_V ''' 72 H 67 s 86 V 127 delete 45 - 61 + 85 u 341 F2 83 S 68 D 67 C ''' if 32 <= keycode <= 126: #------------copy and paste image if keycode == 86 and ctrldown and wx.TheClipboard.Open(): clipBitmap = wx.BitmapDataObject() if wx.TheClipboard.GetData(clipBitmap): wx.TheClipboard.Close() a = random.randint(0, 10000) mapName = GRAP_PF_NAME + "_" + str(a) + "_" + str( int(time.time())) + ".png" clipBitmap.GetBitmap().ConvertToImage().SaveFile( mapName, wx.BITMAP_TYPE_PNG) createImage("noname_paste", True, [(self.pos[0] + 7), (self.pos[1] + 7)], 1, mapName) print "paste image from clipboard! " if keycode == 67 and ctrldown and os.path.isfile( self.path) and wx.TheClipboard.Open( ) and self.path != "imagePin.png": setClipBitmap = wx.BitmapDataObject( wx.Bitmap(self.path, wx.BITMAP_TYPE_PNG)) wx.TheClipboard.SetData(setClipBitmap) wx.TheClipboard.Close() print "copy image to clipboard! " #---------scale image if keycode == 45: if ctrldown == False and self.scale > IMAGE_SCALE_MIN_MAX[ 0] and self.path != "imagePin.png": self.scale = self.scale * (1 - SCALE_SPEED) self.resizeMap(self.scale) print "-", self.scale, SCALE_SPEED elif ctrldown and SCALE_SPEED > ADJUST_SCALE_SPEED * 2: SCALE_SPEED -= ADJUST_SCALE_SPEED print "SCALE_SPEED", SCALE_SPEED if keycode == 61: if ctrldown == False and self.scale < IMAGE_SCALE_MIN_MAX[ 1] and self.path != "imagePin.png": self.scale = self.scale * (SCALE_SPEED + 1) self.resizeMap(self.scale) print "+", self.scale, SCALE_SPEED elif ctrldown and SCALE_SPEED < 0.3: SCALE_SPEED += ADJUST_SCALE_SPEED print "SCALE_SPEED", SCALE_SPEED #----------hide and show and delete image if keycode == 72 and ctrldown and self.path != "imagePin.png": if shiftdown: for s in ALL_FRAME: s.Show() s.hide = False else: self.Hide() s.hide = True if keycode == 85 and ctrldown: temp = True for s in ALL_FRAME: if s.IsShown(): s.Hide() s.hide = True else: s.Show() s.hide = False if s.IsShown(): temp = False if temp: imagePinFrame.Show() else: imagePinFrame.Hide() if keycode == 81 and altdown: if self.isolation: for s in ALL_FRAME: if s != self and s.hide == False: s.Show() self.isolation = False else: for s in ALL_FRAME: if s != self and s.hide == False: s.Hide() self.isolation = True #-----------save if keycode == 83 and ctrldown: self.onSave(evt) #----------showInExplorer if keycode == 68 and ctrldown: self.showInExplorer(evt) #----------showInExplorer if keycode == 87 and ctrldown: self.onClose(evt) if keycode == 342: if ctrldown and shiftdown and altdown: console = PyConsoleFrame(parent=None, id=-1) console.Show() if keycode == 341: self.reName(evt) if ctrldown and shiftdown and altdown: console = pyConsole(parent=None, id=-1, text="xxxxxxxxxxxxxxx") console.Show() if keycode == 340: #print "help" help_Frame = helpFrame(parent=None, id=0) help_Frame.Show() if keycode == 127 and self.path != "imagePin.png": if shiftdown: os.remove(self.path) else: if os.path.isdir("backup") != True: os.mkdir("backup") c = "move " + self.path + " " + ("backup/" + self.path) os.system(c) self.Close() ALL_FRAME.remove(self) if keycode == 65 and altdown and ctrldown and shiftdown: grapStart()
def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(1300, 1000)) # Placed up front so other screen elementes will be placed OVER it! self.barChartGraphic = BarChartGraphic( self) # DON'T PUT THIS IN THE SIZER -- It needs to be hidden! # Create a Sizer s1 = wx.BoxSizer(wx.HORIZONTAL) # Add a RichTextCtrl self.txt = richtext.RichTextCtrl(self, -1) # Put the RichTextCtrl on the Sizer s1.Add(self.txt, 1, wx.EXPAND) # Set the main sizer self.SetSizer(s1) # Lay out the window self.Layout() self.SetAutoLayout(True) self.txt.AppendText('Now comes the fun part.\n\n') # Prepare some fake data for a demonstration graph title = 'Keyword Frequency' data = [50, 45, 25, 22, 20, 18, 15, 12, 11, 8, 7, 6, 4, 2, 1, 1] dataLabels = [ 'Long Label 1', 'Long Label 2', 'Really, really long label 3', 'Long Label 4', 'Long Label 5', 'Long Label 6', 'Long Label 7', 'Long Label 8', 'Long Label 9', 'Long Label 10', 'Long Label 11', 'Long Label 12', 'Long Label 13', 'Long Label 14', 'Long Label 15', '16' ] # Draw the BarChart. This places the graphic in the Clipboard. self.barChartGraphic.plot(title, data, dataLabels) # If the Clipboard isn't Open ... if not wx.TheClipboard.IsOpened(): # ... open it! clip = wx.Clipboard() clip.Open() # Create an Image Data Object bitmapObject = wx.BitmapDataObject() # Get the Data from the Clipboard clip.GetData(bitmapObject) # Convert the BitmapsDataObject to a Bitmap bitmap = bitmapObject.GetBitmap() # Convert the Bitmap to an Image image = bitmap.ConvertToImage() # Write the plain text into the Rich Text Ctrl # self.txt.WriteBitmap(bitmap, wx.BITMAP_TYPE_BMP) BAD FOR RTF self.txt.WriteImage(image) self.txt.AppendText('Bitmap Added!!\n\n') # Close the Clipboard clip.Close() # Draw a second BarChart # Prepare some fake data for a demonstration graph title = 'Keyword Frequency' data = [25, 22, 20, 18, 15] dataLabels = [ 'Long Label 4', 'Long Label 5', 'Long Label 6', 'Long Label 7', 'Long Label 8' ] self.barChartGraphic.plot(title, data, dataLabels) self.barChartGraphic.canvas.Copy_to_Clipboard() # If the Clipboard isn't Open ... if not wx.TheClipboard.IsOpened(): # ... open it! clip = wx.Clipboard() clip.Open() # Create an Image Data Object bitmapObject = wx.BitmapDataObject() # Get the Data from the Clipboard clip.GetData(bitmapObject) # Convert the BitmapsDataObject to a Bitmap bitmap = bitmapObject.GetBitmap() # Convert the Bitmap to an Image image = bitmap.ConvertToImage() # Write the plain text into the Rich Text Ctrl # self.txt.WriteBitmap(bitmap, wx.BITMAP_TYPE_BMP) BAD FOR RTF self.txt.WriteImage(image) self.txt.AppendText('Bitmap Added!!\n\n') # Close the Clipboard clip.Close()
def _return_if_bitmap(): clip_data = wx.BitmapDataObject( ) #http://stackoverflow.com/questions/2629907/reading-an-image-from-the-clipboard-with-wxpython success = clipboard.GetData(clip_data) if not success: return self.setThrottle("slow") image_old = CLIENT_RECENT_DATA.get() #print "image_old %s"%image_old try: image_old_buffer_array = image_old.GetDataBuffer( ) #SOLVED GetDataBuffer crashing! You need to ensure that you do not use this buffer object after the image has been destroyed. http://wxpython.org/Phoenix/docs/html/MigrationGuide.html bitmap.ConvertToImage().GetDataBuffer() WILL FAIL because the image is destroyed after GetDataBuffer() is called so doing a buffer1 != buffer2 comparison will crash except AttributeError: image_old_buffer_array = None #if previous is not an image try: bitmap = clip_data.GetBitmap() image_new = bitmap.ConvertToImage( ) #OLD #GET DATA IS HIDDEN METHOD, IT RETURNS BYTE ARRAY... DO NOT USE GETDATABUFFER AS IT CRASHES. BESIDES GETDATABUFFER IS ONLY GOOD TO CHANGE BYTES IN MEMORY http://wxpython.org/Phoenix/docs/html/MigrationGuide.html image_new_buffer_array = image_new.GetDataBuffer() if image_new_buffer_array == image_old_buffer_array: #for performance reasons we are not using the bmp for hash, but rather the wx Image GetData array image_new.Destroy( ) #will be created again in next iteration return megapixels = len(image_new_buffer_array) / 3 / 1000000.0 if megapixels > 100.0: image_new.Destroy( ) #will be created again in next iteration self.sb.toggleStatusIcon( msg= 'Bitmap not uploaded. Maximum resolution is 100 megapixels.', icon="bad") return megapixels = "%.2f" % megapixels clip_hash_fast = format( hash128(image_new_buffer_array), "x" ) #hex(hash128(image_new)) #KEEP PRIVATE and use to get hash of large data quickly clip_hash_secure = hashlib.new( "ripemd160", clip_hash_fast + self.websocket_worker.ACCOUNT_SALT ).hexdigest( ) #to prevent rainbow table attacks of known files and their hashes, will also cause decryption to fail if file name is changed img_file_name = "%s.bmp" % clip_hash_secure img_file_path = os.path.join(TEMP_DIR, img_file_name) print "\nimg_file_path: \n%s\n" % img_file_path bitmap.SaveFile( img_file_path, wx.BITMAP_TYPE_BMP) #change to or compliment upload try: image_old.Destroy( ) #image new will be image_old in next iteration, so get rid of old reference. except AttributeError: pass return __prepare_for_upload(file_names=[img_file_name], clip_type="bitmap", clip_display=[megapixels], clip_hash_secure=clip_hash_secure, compare_next=image_new) finally: bitmap.Destroy() gc.collect()
def setClipboardContent(self, container_name, clip_type): #NEEDS TO BE IN MAIN LOOP FOR WRITING TO WORK, OR ELSE WE WILL #GET SOMETHING LIKE: "Failed to put data on the clipboard #(error 2147221008: coInitialize has not been called.)" success = False try: with wx.TheClipboard.Get() as clipboard: self.sb.toggleStatusIcon( msg='Downloading and decrypting %s data...' % clip_type, icon="unlock") container_path = self.downloadClipFileIfNotExist( container_name) if container_path: print "DECRYPT" with encompress.Encompress(password="******", directory=TEMP_DIR, file_name_decrypt=container_name ) as file_paths_decrypt: #print file_paths_decrypt if clip_type in ["text", "link"]: clip_file_path = file_paths_decrypt[0] with open(clip_file_path, 'r') as clip_file: clip_text = self.decodeClip(clip_file.read()) clip_data = wx.TextDataObject() clip_data.SetText(clip_text) success = clipboard.SetData(clip_data) elif clip_type == "bitmap": clip_file_path = file_paths_decrypt[0] bitmap = wx.Bitmap(clip_file_path, wx.BITMAP_TYPE_BMP) clip_data = wx.BitmapDataObject(bitmap) success = clipboard.SetData(clip_data) elif clip_type == "files": clip_file_paths = file_paths_decrypt clip_data = wx.FileDataObject() for each_file_path in clip_file_paths: clip_data.AddFile(each_file_path) success = clipboard.SetData(clip_data) else: self.destroyBusyDialog() wx.MessageBox( "Unable to download this clip from the server", "Error") except: wx.MessageBox("Unexpected error: %s" % sys.exc_info()[0], "Error", wx.ICON_ERROR) self.destroyBusyDialog() if success: self.sb.toggleStatusIcon(msg='Successfully received %s data.' % clip_type, icon="good") return success
def test_BitmapDataObject(self): do = wx.BitmapDataObject() do.Bitmap = wx.Bitmap(pngFile) self.assertTrue(do.GetBitmap().IsOk()) self.assertTrue(do.Bitmap.IsOk())
def copyImageToClipboard(self): bitmap = wx.BitmapFromImage(self.image) bmpdo = wx.BitmapDataObject(bitmap) if wx.TheClipboard.Open(): wx.TheClipboard.SetData(bmpdo) wx.TheClipboard.Close()