def init_cmap_popup_menu(self): cmap_button_bitmap_height = 10 cmap_button_bitmap_width = 200 cmap_menu_bitmap_height = 20 cmap_menu_bitmap_width = 200 self.cmap_button_bitmaps = {} self.cmap_menu_bitmaps = {} for cmap in self.ztv_frame.available_cmaps: temp = cm.ScalarMappable(cmap=cmap) rgba = temp.to_rgba( np.outer(np.ones(cmap_button_bitmap_height, dtype=np.uint8), np.arange(cmap_button_bitmap_width, dtype=np.uint8))) self.cmap_button_bitmaps[cmap] = wx.BitmapFromBufferRGBA( cmap_button_bitmap_width, cmap_button_bitmap_height, np.uint8(np.round(rgba * 255))) rgba = temp.to_rgba( np.outer(np.ones(cmap_menu_bitmap_height, dtype=np.uint8), np.arange(cmap_menu_bitmap_width, dtype=np.uint8))) self.cmap_menu_bitmaps[cmap] = wx.BitmapFromBufferRGBA( cmap_menu_bitmap_width, cmap_menu_bitmap_height, np.uint8(np.round(rgba * 255))) menu = wx.Menu() for cmap in self.ztv_frame.available_cmaps: menu_item = menu.AppendCheckItem(self.cmap_to_eventID[cmap], cmap) wx.EVT_MENU(menu, self.cmap_to_eventID[cmap], self.on_change_cmap_event) if hasattr(menu_item, 'SetBitmap'): menu_item.SetBitmap(self.cmap_menu_bitmaps[cmap]) self.cmap_popup_menu = menu
def _WX28_clipped_agg_as_bitmap(agg, bbox): """ Convert the region of a the agg buffer bounded by bbox to a wx.Bitmap. Note: agg must be a backend_agg.RendererAgg instance. """ l, b, width, height = bbox.bounds r = l + width t = b + height srcBmp = wx.BitmapFromBufferRGBA(int(agg.width), int(agg.height), agg.buffer_rgba()) srcDC = wx.MemoryDC() srcDC.SelectObject(srcBmp) destBmp = wx.EmptyBitmap(int(width), int(height)) destDC = wx.MemoryDC() destDC.SelectObject(destBmp) destDC.BeginDrawing() x = int(l) y = int(int(agg.height) - t) destDC.Blit(0, 0, int(width), int(height), srcDC, x, y) destDC.EndDrawing() srcDC.SelectObject(wx.NullBitmap) destDC.SelectObject(wx.NullBitmap) return destBmp
def RenderPage(self, gc, pageno, scale=1.0): " Render the set of pagedrawings into gc for specified page " self.trans = fitz.scale_matrix(scale, scale) self.rect = self.trans.transform_rect( self.page_rect) #page_rect is the unscaled one self.bbox = self.rect.round_rect() try: self.pix = self.context.new_pixmap_with_irect( fitz.fz_device_rgb, self.bbox) self.pix.clear_pixmap(255) width = self.pix.get_width() height = self.pix.get_height() dev = self.pix.new_draw_device() self.pagedrawings[pageno].run_display_list(dev, self.trans, self.rect, None) bmp = wx.BitmapFromBufferRGBA(width, height, self.pix.get_samples()) gbmp = gc.CreateBitmap(bmp) gc.DrawBitmap(gbmp, 0, 0, width, height) self.zoom_error = False except RuntimeError, MemoryError: if not self.zoom_error: # report once only self.zoom_error = True dlg = wx.MessageDialog(self, 'Out of memory. Zoom level too high', 'pdf viewer', wx.OK | wx.ICON_EXCLAMATION) dlg.ShowModal() dlg.Destroy()
def bitmapfrompil(self,img): if wx.VERSION[0]<4: return wx.BitmapFromBufferRGBA(img.size[0],\ img.size[1],img.convert("RGBA").tobytes()) else: return wx.Bitmap.FromBufferRGBA(img.size[0],\ img.size[1],img.convert("RGBA").tobytes())
def grid_to_buffer(self): from stars.core.DKDEWrapper import call_kde x = [] y = [] for i in self.query_points: pt = self.points[i] x.append(pt[0]) y.append(pt[1]) n = len(self.query_points) if n < len(self.points): query_points = range(n) arr, rows, cols, grad_min, grad_max = call_kde( n, x, y, #self.query_points, range(n), self.extent, self.bandwidth, self.cell_size, self.kernel, self.color_band, self.opaque * 2.55) #from PIL import Image #Image.fromarray(arr).save("test.png") self.bmp = wx.BitmapFromBufferRGBA(cols, rows, arr) #self.bmp.SaveFile("test.png", wx.BITMAP_TYPE_PNG) self.gradient_color_min = grad_min self.gradient_color_max = grad_max
def __init__(self, parent, currentmap): self.currentmap = currentmap self.mode = UNSELECTED self.overlays = np.zeros_like(self.currentmap.terrain) self.red_counters = np.ones_like(self.currentmap.terrain) * -1 self.selectedTile = None self.sourceTile = None self.original_board = None self.arrows = [] self.circles = [] width_px, height_px = self.currentmap.width * 32 + 16, self.currentmap.height * 26 + 8 MapPanel.__init__(self, parent, background_tile=wx.Bitmap("logo_background_repeating.png"), size=(width_px, height_px)) ## create buffer with mask self.Buffer = wx.BitmapFromBufferRGBA(width_px, height_px, np.ones((width_px, height_px), np.int32) * int("0xff00ff", 0)) self.battle_result_panel = BattleResultPanel(self) self.battle_result_panel.SetBackgroundColour("WHITE") self.battle_result_panel.Hide() self.RedrawMap() self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp) self.Bind(wx.EVT_MOTION, self.OnMove) self.Bind(wx.EVT_SIZE, self.OnResize)
def copy_to_clipboard(plot): # WX specific, though QT implementation is similar using # QImage and QClipboard import wx width, height = plot.outer_bounds gc = PlotGraphicsContext((width, height), dpi=72) backbuffer = plot.use_backbuffer plot.use_backbuffer = False gc.render_component(plot) plot.use_backbuffer = backbuffer # Create a bitmap the same size as the plot # and copy the plot data to it bmp = gc.bmp_array if gc.format().startswith('bgra'): bmp_rgba = bmp[:,:,[2,1,0,3]] else: bmp_rgba = bmp bitmap = wx.BitmapFromBufferRGBA(width+1, height+1, bmp_rgba.flatten()) data = wx.BitmapDataObject() data.SetBitmap(bitmap) if wx.TheClipboard.Open(): wx.TheClipboard.SetData(data) wx.TheClipboard.Close() else: wx.MessageBox("Unable to open the clipboard.", "Error")
def GetWxBitmap(self): (width, height) = self._size if self._format == wx.BitmapBufferFormat_RGB: return wx.BitmapFromBuffer(width, height, self._GetData()) else: return wx.BitmapFromBufferRGBA(width, height, self._GetData())
def load_costume(self, costume): width, height, raw_image = costume.get_raw_image() bitmap = wx.BitmapFromBufferRGBA(width, height, raw_image) image = wx.ImageFromBitmap(bitmap) image_scaled = image.Scale(30, 30, wx.IMAGE_QUALITY_HIGH) sprite_bitmap = wx.BitmapFromImage(image_scaled) self.il.Add(sprite_bitmap) self.InsertImageStringItem(0, costume.name, 0)
def colorbar_bitmap(colormap, length, thickness=10, orientation='horizontal'): """ Convert a colormap to a bitmap showing a colorbar for the colormap. Orientation can be vertical or horizontal (only looks at the first letter). """ # Make an RGBA array from the colormap, either horizontally or vertically. V = colormap(numpy.linspace(0, 1, length), bytes=True) if orientation[0].lower() == 'h': V = numpy.tile(V, (thickness, 1)) bitmap = wx.BitmapFromBufferRGBA(length, thickness, V) elif orientation[0].lower() == 'v': V = numpy.tile(V, (1, thickness)) bitmap = wx.BitmapFromBufferRGBA(thickness, length, V) else: raise ValueError, "expected orientation [V]ertical or [H]orizontal" return bitmap
def MakeBgBmp(self): w, h = self.GetClientSize() if w == 0 or h == 0: return self.bmp_bg = wx.BitmapFromBufferRGBA( w, h, make_checker(w, h, 16, (150, 150, 150), (220, 220, 220)))
def bufferToBitmap(data): w, h, comps = data.shape if comps == 4: return wx.BitmapFromBufferRGBA(w, h, data) elif comps == 3: return wx.BitmapFromBuffer(w, h, data) else: raise
def GetWxBitmap(self): (width, height) = self._size if self._format == wx.BitmapBufferFormat_RGB: return wx.BitmapFromBuffer(width, height, lz4.loads(self._data)) else: return wx.BitmapFromBufferRGBA(width, height, lz4.loads(self._data))
def __init__(self, parent, id, title, pos, size): wx.Frame.__init__(self, parent, id, title, pos, size) Img = 'test_data/b5.tif' print "Draw ", Img Img2D = gdal.Open(str(Img), GA_ReadOnly) #Imgarray = gdal_array.LoadFile(str(Img)) #geomatrix = Img2D.GetGeoTransform() #north = geomatrix[0] #resolution_y = abs(geomatrix[1]) ##print resolution_y #west = geomatrix[3] #resolution_x = abs(geomatrix[5]) ##print resolution_x #projection = Img2D.GetProjection() ##print projection #x_min = y_min = 0 x_max = Img2D.RasterXSize y_max = Img2D.RasterYSize #corners = [(x_min, y_min), #(x_min, y_max), #(x_max, y_min), #(x_max, y_max),] #south = north - y_max*resolution_y #east = west + x_max*resolution_x imgH = y_max imgW = x_max #prepare buffer rgba = numpy.ndarray(shape=(imgH, imgW, 4), dtype=numpy.uint8) #fill with black band1 = 10 #red band2 = 200 #green band3 = 0 #blue alpha = 255 rgba[:, :, 0].fill(band1) rgba[:, :, 1].fill(band2) rgba[:, :, 2].fill(band3) rgba[:, :, 3].fill(alpha) #alpha print "X= ", imgW, "Y= ", imgH for iBand in range(1, Img2D.RasterCount + 1): inband = Img2D.GetRasterBand(iBand) for x in range(0, inband.XSize - 1, 1): #print "X= ",x scanline = inband.ReadAsArray(x, 0, 1, inband.YSize, 1, inband.YSize) #print scanline[x] for y in range(inband.YSize - 1, -1, -1): pixel = scanline[y][0] rgba[y, x, 0] = pixel rgba[y, x, 1] = pixel rgba[y, x, 2] = pixel #print scanline[y][0], pixel, rgba[y,x,0] bmp = wx.BitmapFromBufferRGBA(imgW, imgH, rgba) #wxPython 2.8 static_bmp = wx.StaticBitmap(self, -1, bmp) self.Show(True)
def output_plot(): import matplotlib import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4]) plt.ylabel('some numbers') figure = plt.figure() figure.canvas.draw() w, h = figure.canvas.get_width_height() buf = figure.canvas.tostring_argb() bitmap = wx.BitmapFromBufferRGBA(w, h, buf)
def mng2wx(string,size,offset=0,alpha=True): if alpha: return wx.BitmapFromBufferRGBA(size[0], size[1], string) image = wx.EmptyImage(*size) image.SetData( string[:offset] ) image.SetAlphaData( string[offset:] ) else: image = wx.EmptyImage(*size) image.SetData( string ) return image
def MakeBgBmp(self, size=None): if size is None: w, h = self.GetClientSize() else: w, h = size if w == 0 or h == 0: return self.bmp_bg = wx.BitmapFromBufferRGBA( w, h, make_checker(w, h, 16, (150, 150, 150), (220, 220, 220)))
def DrawImage(context, image, x, y, width, height): # ignore the width & height provided width = image.shape[1] height = image.shape[0] if image.shape[2] == 3: bmp = wx.BitmapFromBuffer(width, height, image.flatten()) else: bmp = wx.BitmapFromBufferRGBA(width, height, image.flatten()) context.DrawBitmap(bmp, x, y, width, height)
def _wx_bitmap_from_buffer(buf, width, height): """ Given a pixel buffer in ARGB order, return a WX bitmap object with the pixels in BGRA order. """ arr = np.frombuffer(buf, dtype=np.uint8).reshape((width, height, 4)) copy = np.zeros_like(arr) copy[..., 0::4] = arr[..., 2::4] copy[..., 1::4] = arr[..., 1::4] copy[..., 2::4] = arr[..., 0::4] copy[..., 3::4] = arr[..., 3::4] return wx.BitmapFromBufferRGBA(width, height, np.ravel(copy))
def __onPaint(self, e): wx.PaintDC( self ) # Make a PaintDC, else the paint event will be called again. self.SetCurrent(self._context) size = self._parent.GetSizeTuple() if self._color_texture is None: self._color_texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, self._color_texture) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, size[0], size[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, None) glBindTexture(GL_TEXTURE_2D, 0) self._depth_texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, self._depth_texture) glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, size[0], size[1], 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, None) glBindTexture(GL_TEXTURE_2D, 0) self._fbo = glGenFramebuffers(1) glBindFramebuffer(GL_FRAMEBUFFER, self._fbo) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, self._color_texture, 0) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, self._depth_texture, 0) glBindFramebuffer(GL_FRAMEBUFFER, 0) self._fboSize = size if self._fboSize != size: self._fboSize = size glBindTexture(GL_TEXTURE_2D, self._color_texture) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, size[0], size[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, None) glBindTexture(GL_TEXTURE_2D, 0) glBindTexture(GL_TEXTURE_2D, self._depth_texture) glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, size[0], size[1], 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, None) glBindTexture(GL_TEXTURE_2D, 0) glBindFramebuffer(GL_FRAMEBUFFER, self._fbo) self._parent._onRender() glFlush() glBindFramebuffer(GL_FRAMEBUFFER, 0) glBindTexture(GL_TEXTURE_2D, self._color_texture) data = glGetTexImageub(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE) self._bitmap = wx.BitmapFromBufferRGBA(size[0], size[1], data) glBindTexture(GL_TEXTURE_2D, 0) self.SwapBuffers() self._parent.Refresh()
def update(self, image): if not hasattr(self, 'staticbmp'): self.staticbmp = wx.StaticBitmap(self) frame = self.GetParent() frame.SetSize((image.width, image.height)) if image.encoding == 'rgba8': bmp = wx.BitmapFromBufferRGBA(image.width, image.height, image.data) self.staticbmp.SetBitmap(bmp) elif image.encoding == 'rgb8': bmp = wx.BitmapFromBuffer(image.width, image.height, image.data) self.staticbmp.SetBitmap(bmp)
def render_complete(self, size, output_buffer): this_second = math.floor(time.clock()) if self.current_second != this_second: # rolled over into a new second, print FPS #print("Renders/sec: %d" % self.renders_this_second) self.current_second = this_second self.renders_this_second = 0 w, h = size self.bmp = wx.BitmapFromBufferRGBA(w, h, output_buffer) self.Refresh() self.renders_this_second += 1
def _perform_wx(self, width, height, gc): import wx bitmap = wx.BitmapFromBufferRGBA(width + 1, height + 1, gc.bmp_array.flatten()) data = wx.BitmapDataObject() data.SetBitmap(bitmap) if wx.TheClipboard.Open(): wx.TheClipboard.SetData(data) wx.TheClipboard.Close() else: wx.MessageBox("Unable to open the clipboard.", "Error")
def OnPaint(self, evt): # Where the magic happens. Here the controls are drawn. dc = wx.BufferedPaintDC(self) dc.Clear() w, h = self.GetSize() width_gradient = w - 2 * PUSH_WIDTH height_gradient = h x_init_gradient = PUSH_WIDTH y_init_gradient = 0 x_init_push1 = self.min_position - PUSH_WIDTH x_init_push2 = self.max_position width_transparency = self.max_position - self.min_position # Drawing the left blank area. pen = wx.Pen((0, 0, 0)) brush = wx.Brush((0, 0, 0)) dc.SetPen(pen) dc.SetBrush(brush) dc.DrawRectangle(0, 0, PUSH_WIDTH, h) # Drawing the right blank area. pen = wx.Pen((255, 255, 255)) brush = wx.Brush((255, 255, 255)) dc.SetPen(pen) dc.SetBrush(brush) dc.DrawRectangle(x_init_gradient + width_gradient, 0, PUSH_WIDTH, h) # Drawing the gradient. dc.GradientFillLinear((x_init_gradient, y_init_gradient, width_gradient, height_gradient), (0, 0, 0), (255, 255, 255)) try: n = wx.RendererNative.Get() except AttributeError: n = wx.RendererNative_Get() # Drawing the push buttons n.DrawPushButton(self, dc, (x_init_push1, 0, PUSH_WIDTH, h)) n.DrawPushButton(self, dc, (x_init_push2, 0, PUSH_WIDTH, h)) # Drawing the transparent slider. bytes = numpy.array(self.colour * width_transparency * h, 'B') try: slider = wx.BitmapFromBufferRGBA(width_transparency, h, bytes) except: pass else: dc.DrawBitmap(slider, self.min_position, 0, True)
def OnPaint(self, event): dc = wx.BufferedPaintDC(self._screen) # dc.SetBackground(wx.Brush('black')) # dc.Clear() if self._ctx: w = self._ctx.get_width() h = self._ctx.get_height() data = self._ctx.get_data() wxbmp = wx.BitmapFromBufferRGBA(w, h, data) dc.DrawBitmap(wxbmp, 0, 0) event.Skip()
def update(self, image): # http://www.ros.org/doc/api/sensor_msgs/html/msg/Image.html if not hasattr(self, 'staticbmp'): self.staticbmp = wx.StaticBitmap(self) frame = self.GetParent() frame.SetSize((image.width, image.height)) if image.encoding == 'rgba8': bmp = wx.BitmapFromBufferRGBA(image.width, image.height, image.data) self.staticbmp.SetBitmap(bmp) elif image.encoding == 'rgb8': bmp = wx.BitmapFromBuffer(image.width, image.height, image.data) self.staticbmp.SetBitmap(bmp)
def _convert_agg_to_wx_bitmap(agg, bbox): """ Convert the region of the agg buffer bounded by bbox to a wx.Bitmap. If bbox is None, the entire buffer is converted. Note: agg must be a backend_agg.RendererAgg instance. """ if bbox is None: # agg => rgba buffer -> bitmap return wx.BitmapFromBufferRGBA(int(agg.width), int(agg.height), agg.buffer_rgba()) else: # agg => rgba buffer -> bitmap => clipped bitmap return _WX28_clipped_agg_as_bitmap(agg, bbox)
def mathtext_to_wxbitmap(s, taille=100, color=None): global mathtext_parser if s == "": return wx.NullBitmap if s[0] <> r"$": s = mathText(s) # color = matplotlib.rcParams['text.color'] # print color, # matplotlib.rcParams['text.color'] ='r' # print matplotlib.rcParams['text.color'] ftimage, depth = mathtext_parser.parse(s, taille) # ftimage, depth = mathtext_parser.to_rgba(s, 'r') # print ftimage # matplotlib.rc('text', color=color) # color = wx.Colour(255,0,0) if color != None: x = ftimage.as_array() # Create an RGBA array for the destination, w x h x 4 rgba = scipy.zeros((x.shape[0], x.shape[1], 4), dtype=scipy.uint8) rgba[:, :, 0:3] = color # set the RGB components to the constant value passed in rgba[:, :, 3] = x bmp = wx.BitmapFromBufferRGBA(ftimage.get_width(), ftimage.get_height(), rgba.tostring()) else: bmp = wx.BitmapFromBufferRGBA(ftimage.get_width(), ftimage.get_height(), ftimage.as_rgba_str()) return bmp
def MakeBitmapRGBA(self, width, height): # Make a bitmap using an array of RGBA bytes bpp = 4 # bytes per pixel bytes = array.array('B', [0] * width*height*bpp) for y in xrange(height): for x in xrange(width): offset = y*width*bpp + x*bpp r,g,b,a = self.GetRGB(x, y, bpp) bytes[offset + 0] = r bytes[offset + 1] = g bytes[offset + 2] = b bytes[offset + 3] = a self.rgbaBmp = wx.BitmapFromBufferRGBA(width, height, bytes)
def GetWxImage(self): (width, height) = self._size if self._format == wx.BitmapBufferFormat_RGB: return wx.ImageFromBuffer(width, height, lz4.loads(self._data)) else: bitmap = wx.BitmapFromBufferRGBA(width, height, lz4.loads(self._data)) image = wx.ImageFromBitmap(bitmap) wx.CallAfter(bitmap.Destroy) return image