def createArrowIcon(cls, left=True, full=True): ''' Obtains a brand new Image object (don't forget to Dispose() it!) that displays either a left or right pointing arrow. ''' dir = __file__[:-(len(__name__) + len('.py'))] if full: return Image.FromFile( dir + 'fullleftarrow.png') if left \ else Image.FromFile( dir + 'fullrightarrow.png') else: return Image.FromFile( dir + 'leftarrow.png') if left \ else Image.FromFile( dir + 'rightarrow.png')
def EzToolBar(parent, toolbar_table): toolbar = ToolStrip() #toolbar.Location = Point(0, 0); #toolbar.ImageScalingSize = Size(20, 20); for m in toolbar_table: print(m) if not m.get('name') or m['name'] == '-': toolbar.Items.Add(ToolStripSeparator()) continue if m['name'] == "Button": item = ToolStripButton() if m.get('handler'): item.Click += m['handler'] if m.get('label'): item.Text = m['label'] if m.get('icon'): item.Image = Image.FromFile(m['icon']) item.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText item.TextImageRelation = TextImageRelation.ImageAboveText elif m['name'] == "Label": item = ToolStripLabel() if m.get('label'): item.Text = m['label'] elif m['name'] == 'TextBox': item = ToolStripTextBox() if m.get('handler'): item.KeyDown += m['handler'] if m.get('text'): item.Text += m['text'] item.BorderStyle = BorderStyle.FixedSingle else: continue toolbar.Items.Add(item) return toolbar
def createComicVineLogo(cls): ''' Obtains a brand new Image object (don't forget to Dispose() it!) that displays the ComicVine logo. ''' dir = __file__[:-(len(__name__) + len('.py'))] return Image.FromFile(dir + 'comicvinelogo.png')
def _get_ppt_image_size(_image_file_path, Shape=None): r"""Return the Width and Height in points of the image passed in. Used by set_bg_image_and_size(). Example: | _image_file_path = "transformations\\utils\\images\\greenarrow.png" | size=_get_ppt_image_size(_image_file_path) | print size.Width, size.Height """ import clr clr.AddReference("System.Drawing") from System.Drawing import Image from System.Drawing import SizeF _im = Image.FromFile(_image_file_path) _size_px = _im.Size _vert_dpi = _im.VerticalResolution _horz_dpi = _im.HorizontalResolution _im.Dispose() # calculate the actual size of the image in points as this is the unit # that PowerPoint uses _width = 72 * float(_size_px.Width) / _horz_dpi _height = 72 * float(_size_px.Height) / _vert_dpi _size = SizeF(_width, _height) return _size
def SetBgImageAndSize(fileName, Shape=None): try: import clr #from globals import * clr.AddReference("System.Drawing") from System.Drawing import Image from System.Drawing import SizeF im = Image.FromFile(fileName) sizePx = im.Size vertDPI = im.VerticalResolution horzDPI = im.HorizontalResolution im.Dispose() # calculate the actual size of the image in points as this is the unit that # PowerPoint uses size = SizeF(72.0 * float(sizePx.Width) / horzDPI, 72 * float(sizePx.Height) / horzDPI) SetBgImage(fileName, Shape) Shape.Width = size.Width Shape.Height = size.Height Shape.TextFrame.TextRange.Text = "" return True except: raise
def init(self): box = PictureBox() box.Dock = DockStyle.Fill box.SizeMode = PictureBoxSizeMode.AutoSize box.Image = Image.FromFile(self.imagepath) self.image = box.Image self.Controls.Add(box) self.ClientSize = box.Size
def recalculate(self, Constants=Constants, Formatting=Formatting): self.__reset() workbook = self # Worksheet creation workbook.AddWorksheet("Colored Range") workbook["Colored Range"].Bounds = (3, 5, 8, 15) workbook["Colored Range"].ShowGrid = False workbook.AddWorksheet("Silly Colors - No Grid") workbook["Silly Colors - No Grid"].ShowGrid = False workbook.AddWorksheet("The Silly Colors") # Pre-constants user code from System.Drawing import Image from System.IO import Path directory = Path.GetDirectoryName(__file__) imagePath = Path.Combine(directory, '3d-space.jpg') image = Image.FromFile(imagePath) workbook.AddImageWorksheet("Gnuplot Image", image) workbook.Populate(Constants, Formatting) # Pre-formulae user code # Formula code # Post-formulae user code from random import random def RandomColor(): return Color.FromArgb(random() * 256, random() * 256, random() * 256) def FillWithSillyColors(sheet): for x in range(1, 10): for y in range(1, 6): cellLoc = (x, y) cell = sheet.Cells[cellLoc] cell.BackColor = RandomColor() cell.Value = cellLoc cell.Bold = True print cellLoc, print sheet1 = workbook['The Silly Colors'] sheet2 = workbook['Silly Colors - No Grid'] FillWithSillyColors(sheet1) FillWithSillyColors(sheet2)
def __init__(self): Form.__init__(self) self.ClientSize = Size(400, 250) self.Text = "About FLExTools" self.FormBorderStyle = FormBorderStyle .Fixed3D self.Icon = Icon(UIGlobal.ApplicationIcon) pb = PictureBox() pb.Image = Image.FromFile(UIGlobal.ApplicationIcon) pb.BackColor = UIGlobal.helpDialogColor pb.SizeMode = PictureBoxSizeMode.CenterImage self.Controls.Add(pb) self.Controls.Add(AboutInfo())
def setup(self, filename, title): # adjust the form's client area size to the picture self.ClientSize = Size(300, 300) self.Text = title self.filename = filename self.image = Image.FromFile(self.filename) pictureBox = PictureBox() # this will fit the image to the form pictureBox.SizeMode = PictureBoxSizeMode.StretchImage pictureBox.Image = self.image # fit the picture box to the frame pictureBox.Dock = DockStyle.Fill self.Controls.Add(pictureBox) self.Show()
def main(imageFilePath, targetImageType): try: filePath, ext = os.path.splitext(imageFilePath) img = Image.FromFile(imageFilePath) targetEx = imageExt[targetImageType % 5] # make sure target ext is not same as input! if targetEx.lower() != ext[1:].lower(): outputFilePath = ".".join([filePath, targetEx]) img.Save(outputFilePath, imageFromat[targetImageType % 5]) return outputFilePath except Exception, e: return "something went wrong: " + str(e)
def GetPptImageSize(fileName): import clr clr.AddReference("System.Drawing") from System.Drawing import Image from System.Drawing import SizeF im = Image.FromFile(fileName) sizePx = im.Size vertDPI = im.VerticalResolution horzDPI = im.HorizontalResolution im.Dispose() # calculate the actual size of the image in points as this is the unit that # PowerPoint uses size = SizeF(72.0 * float(sizePx.Width) / horzDPI, 72 * float(sizePx.Height) / horzDPI) return size
def EzMenu(name, menu_table): menu = ToolStripMenuItem(name) for m in menu_table: if not m.get('name') or m['name'] == '-': menu.DropDownItems.Add(ToolStripSeparator()) continue if not m.get('item'): continue # Disabled if type(m['item']) == list: menu.DropDownItems.Add(EzMenu(m['name'], m['item'])) else: item = ToolStripMenuItem(m['name'], None, m['item']) #item.Text += m['name'] #item.Click += m['item'] if m.get('icon'): item.Image = Image.FromFile(m['icon']) if m.get('check'): item.Checked = True menu.DropDownItems.Add(item) return menu
def ScreenCapture(x, y, width, height): from NetModules import User32, GDI32 from System.Drawing import Bitmap, Image hdcSrc = User32.GetWindowDC(User32.GetDesktopWindow()) hdcDest = GDI32.CreateCompatibleDC(hdcSrc) hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, width, height) GDI32.SelectObject(hdcDest, hBitmap) # 0x00CC0020 is the magic number for a copy raster operation GDI32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, x, y, 0x00CC0020) result = Bitmap(Image.FromHbitmap(hBitmap)) User32.ReleaseDC(User32.GetDesktopWindow(), hdcSrc) GDI32.DeleteDC(hdcDest) GDI32.DeleteObject(hBitmap) return result
def image_from_local(source): """Construct an image from a local source. Parameters ---------- source : str The path to the local source file. Returns ------- System.Drawing.Image Representation of an miage in memory. Examples -------- .. code-block:: python image = image_from_local('theblock.jpg') """ return Image.FromFile(source)
def _query_image( ref, lasttry = False ): ''' ComicVine implementation of the identically named method in the db.py ''' retval = None # the Image object that we will return # 1. determine the URL image_url_s = None if isinstance(ref, SeriesRef): image_url_s = ref.thumb_url_s elif isinstance(ref, IssueRef): image_url_s = ref.thumb_url_s elif is_string(ref): image_url_s = ref # 2. attempt to load the image for the URL if image_url_s: response = None response_stream = None try: cvconnection.wait_until_ready() # throttle our request speed request = WebRequest.Create(image_url_s) request.UserAgent = "[ComicVineScraper, version " + \ Resources.SCRIPT_VERSION + "]" response = request.GetResponse() response_stream = response.GetResponseStream() retval = Image.FromStream(response_stream) except: if lasttry: log.debug_exc('ERROR retry image load failed:') retval = None else: log.debug('RETRY loading image -> ', image_url_s) retval = _query_image( ref, True ) finally: if response: response.Dispose() if response_stream: response_stream.Dispose() # if this value is stil None, it means an error occurred, or else comicvine # simply doesn't have any Image for the given ref object return retval
def __init__(self): self.pushbutons = [] self.Text = 'RedBim набор плагинов' self.Name = 'RedBimSetting' self.Height = 450 self.Width = 400 self.AutoScroll = True self.AutoScaleMode = AutoScaleMode.Font self.BackColor = Color.FromArgb(67, 67, 67) # self.BackgroundImage = Image.FromFile(os.path.join(STATIC_IMAGE, "bg.png")) # self.BackgroundImageLayout = ImageLayout.Center self.Icon = Icon(os.path.join(STATIC_IMAGE, "icon.ico"), 16, 16) self.StartPosition = FormStartPosition.CenterScreen self.tree = RB_TreeView() self.tree.CollapseAll() self.tree.BackColor = Color.FromArgb(67, 67, 67) self.tree.BackgroundImage = Image.FromFile( os.path.join(STATIC_IMAGE, "bg.png")) self.tree.BackgroundImageLayout = ImageLayout.Center self.tree.Font = Font("ISOCPEUR", 12, FontStyle.Italic) self.tree.ForeColor = Color.White self.tree.CheckBoxes = True self.tree.Height = 378 self.tree.Dock = DockStyle.Top self.find_all_pushbuttons() self.button = Button() self.button.Dock = DockStyle.Bottom self.button.Text = "Сохранить настройки" self.button.Height = 32 self.button.Font = Font("ISOCPEUR", 12, FontStyle.Italic) self.button.ForeColor = Color.White self.button.BackColor = Color.Green self.button.Click += self.active_button self.Controls.Add(self.button) self.Controls.Add(self.tree)
def image_from_remote(source): """Construct an image from a remote source. Parameters ---------- source : str The url of the remote source. Returns ------- System.Drawing.Image Representation of an miage in memory. Examples -------- .. code-block:: python image = image_from_remote('http://block.arch.ethz.ch/brg/images/cache/dsc02360_ni-2_cropped_1528706473_624x351.jpg') """ w = WebClient() d = w.DownloadData(source) m = MemoryStream(d) return Image.FromStream(m)
def checkTheInputs(): #Set defaults in case we don't find what we need. checkData1 = True checkData2 = True checkData3 = True metaDataFilePath = None thermalBandFilePath = None img = None radianceMin = None radianceMax = None toFromX = [] toFromY = [] cellGridSize = 30 #Make sure that the input to the image folder is an actual path on the person's computer. if os.path.exists(_landsatImgFolder): #Go through the files in the directory and try to find the ones that we need to make a thermal image. for file in os.listdir(_landsatImgFolder): fullFilePath = os.path.join(_landsatImgFolder, file) if os.path.isfile(fullFilePath): if str(fullFilePath).endswith('_MTL.txt'): metaDataFilePath = fullFilePath elif str(fullFilePath).endswith('_B6.TIF'): thermalBandFilePath = fullFilePath #Check to be sure that I was able to find a header file and a tiff file for the thermal band. if metaDataFilePath == None: checkData1 = False warning = 'Failed to find a valid metadata file in the connected _landsatImgFolder.' print warning ghenv.Component.AddRuntimeMessage( gh.GH_RuntimeMessageLevel.Warning, warning) if thermalBandFilePath == None: checkData1 = False warning = 'Failed to find a valid thermal band file in the connected _landsatImgFolder.' print warning ghenv.Component.AddRuntimeMessage( gh.GH_RuntimeMessageLevel.Warning, warning) else: checkData1 = False warning = '_landsatImgFolder is not a valid file path on your system.' print warning ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, warning) if metaDataFilePath != None and thermalBandFilePath != None: #Next, read the image file and get the height and width. img = Image.FromFile(thermalBandFilePath) imgWidth = img.Width imgHeight = img.Height #Next, read the metadata file and grab the max/min lat/long, and max/min radiance. latitudes = [] longitudes = [] headerData = open(metaDataFilePath, 'r') for line in headerData: if "CORNER" in line and "LAT" in line: latitudes.append(float(line.split(" = ")[-1])) elif "CORNER" in line and "LON" in line: longitudes.append(float(line.split(" = ")[-1])) elif "RADIANCE_MAXIMUM_BAND_6" in line: radianceMax = float(line.split(" = ")[-1]) elif "RADIANCE_MINIMUM_BAND_6" in line: radianceMin = float(line.split(" = ")[-1]) elif "GRID_CELL_SIZE_THERMAL" in line: cellGridSize = float(line.split(" = ")[-1]) #Pull out the maximum and minimum latitude of the scene. latitudes.sort() longitudes.sort() maxLat = latitudes[-2] minLat = latitudes[1] maxLon = longitudes[-2] minLon = longitudes[1] print "The LANDSAT scene ranges from latitude " + str( minLat) + " to " + str(maxLat) print "The LANDSAT scene ranges from longitude " + str( minLon) + " to " + str(maxLon) #If there is no connected latitude and longitude, set the default to be the center of the image otherwise, check to be sure that we are not requesting anything outside of the scene. if latitude_ == None: centerCellX = int(imgWidth / 2) print "The central latitude of the displying image is set to " + str( minLat + ((maxLat - minLat) / 2)) else: #Check to be sure that the latitude is not beyond the maximum of the scene. if latitude_ <= minLat or latitude_ >= maxLat: centerCellX = None checkData2 = False warning = 'The connected lattitude lies outside of the LANDSAT scene.' print warning ghenv.Component.AddRuntimeMessage( gh.GH_RuntimeMessageLevel.Warning, warning) else: centerCellX = int( (maxLat - latitude_) / (maxLat - minLat) * imgWidth) print "The central latitude of the displying image is set to " + str( latitude_) if longitude_ == None: centerCellY = int(imgHeight / 2) print "The central longitude of the displying image is set to " + str( minLon + ((maxLon - minLon) / 2)) else: #Check to be sure that the longitude is not beyond the maximum of the scene. if longitude_ <= minLon or longitude_ >= maxLon: centerCellY = None checkData3 = False warning = 'The connected longitude lies outside of the LANDSAT scene.' print warning ghenv.Component.AddRuntimeMessage( gh.GH_RuntimeMessageLevel.Warning, warning) else: if longitude_ < 0: centerCellY = int( (longitude_ - minLon) / (maxLon - minLon) * imgHeight) else: centerCellY = int( (longitude_ - minLon) / (maxLon - minLon) * imgHeight) print "The central longitude of the displying image is set to " + str( longitude_) if centerCellX and centerCellY: #If there is not connected imageWidth and imageHeight, set the default to 2000 meters. #If there is a connected width or height, check to be sure that we are not requesting anything outside the scene. if imageWidth_ == None: offsetX = int(1000 / cellGridSize) else: offsetX = int(((imageWidth_ * 1000) / 2) / cellGridSize) toFromX = [centerCellX - offsetX, centerCellX + offsetX] if toFromX[0] < 0: toFromX[0] = 0 warning = 'With the current imageWidth, the image would lie outside of the LANDSAT scene and so the left side has been set to the limit of the scene.' print warning if toFromX[1] > imgWidth: toFromX[1] = imgWidth warning = 'With the current imageWidth, the image would lie outside of the LANDSAT scene and so the right side has been set to the limit of the scene.' print warning if imageHeight_ == None: offsetY = int(1000 / cellGridSize) else: offsetY = int(((imageHeight_ * 1000) / 2) / cellGridSize) toFromY = [centerCellY - offsetY, centerCellY + offsetY] if toFromY[0] < 0: toFromY[0] = 0 warning = 'With the current imageHeight, the image would lie outside of the LANDSAT scene and so the bottom has been set to the limit of the scene.' print warning if toFromY[1] > imgHeight: toFromY[1] = imgHeight warning = 'With the current imageHeight, the image would lie outside of the LANDSAT scene and so the top has been set to the limit of the scene.' print warning if sampleSize_: sampleSize = sampleSize_ else: sampleSize = 1 #Do a final check of everything. if checkData1 == True and checkData2 == True and checkData3 == True: checkData = True else: checkData = False return checkData, img, toFromX, toFromY, radianceMin, radianceMax, cellGridSize, sampleSize
for l,m in zip(i,j): b = string1 + str(k) + string3 + str(z) + string34 + str(m) + string5 + str(l) + string7 a.append(b) urlList.append(a) bitmaps2 = [] for i in urlList: bitmaps = [] for j in i: request = WebRequest.Create(j) request.Accept = "text/html" request.UserAgent = "Mozilla/5.0" response = request.GetResponse() bitmaps.append(Image.FromStream(response.GetResponseStream())) bitmaps2.append(bitmaps) combinedBitmaps = [] for a,b,c in zip(bitmaps2,UniqueTileColumns,UniqueTileRows): TotalWidth = len(b)*PixelWidth TotalHeight = len(c)*PixelWidth img = Bitmap(TotalWidth,TotalHeight) g = Graphics.FromImage(img) LPx = [] n = 0 for l in j: LPx.append(n*PixelWidth) n=n+1 LPy = []
average = reduce(lambda x,y: x+y, pixels) / float(len(pixels)) bits = map(lambda x: 1 if x > average else 0, pixels ) return reduce(lambda x, (i, val): x|(val<<i), enumerate(bits), 0) else: return long(0); #============================================================================== # this is just testing code for working on the matching algorithm if __name__ == '__main__': log.install() samples_dir = r"K:/imgcmp/" bases = ["animalman", "armydark", "detective", "hip", "locke", "snow", "tower", "joe", "bedlam"] compares = [(x+"-a.jpg",x+"-b.jpg") for x in bases] +\ [("random.jpg",x+"-a.jpg")for x in bases] for file1, file2 in compares: with Image.FromFile(samples_dir+file1) as image1: with Image.FromFile(samples_dir+file2) as image2: hash1 = hash(image1) hash2 = hash(image2) #log.debug() #log.debug("hash1: ", bin(hash1)[2:].zfill(64)) #log.debug("hash2: ", bin(hash2)[2:].zfill(64)) score = similarity( hash1, hash2 ); log.debug("{0:40}: {1}% similar".format(file1+"<->"+file2, score))
def draw(self, show=True, filename=None, update=False, usecoords=False): """Create a 2D depiction of the molecule. Optional parameters: show -- display on screen (default is True) filename -- write to file (default is None) update -- update the coordinates of the atoms to those determined by the structure diagram generator (default is False) usecoords -- don't calculate 2D coordinates, just use the current coordinates (default is False) Tkinter and Python Imaging Library are required for image display. """ if update: mol = self.Mol else: mol = self.Mol.clone() if not usecoords: mol.layout() if show or filename: renderer = IndigoRenderer(indigo) indigo.setOption("render-output-format", "png") indigo.setOption("render-margins", 10, 10) indigo.setOption("render-coloring", "True") indigo.setOption("render-image-size", 300, 300) indigo.setOption("render-background-color", "1.0, 1.0, 1.0") if self.title: indigo.setOption("render-comment", self.title) if filename: filedes = None else: filedes, filename = tempfile.mkstemp() renderer.renderToFile(mol, filename) if show: if sys.platform[:4] == "java": image = javax.imageio.ImageIO.read(java.io.File(filename)) frame = javax.swing.JFrame(visible=1) frame.getContentPane().add( javax.swing.JLabel(javax.swing.ImageIcon(image))) frame.setSize(300, 300) frame.setDefaultCloseOperation( javax.swing.WindowConstants.DISPOSE_ON_CLOSE) frame.show() elif sys.platform[:3] == "cli": if filedes: errormessage = ( "It is only possible to show the molecule if you " "provide a filename. The reason for this is that I kept " "having problems when using temporary files.") raise RuntimeError(errormessage) form = Form() form.ClientSize = Size(300, 300) form.Text = self.title image = Image.FromFile(filename) box = PictureBox() box.SizeMode = PictureBoxSizeMode.StretchImage box.Image = image box.Dock = DockStyle.Fill form.Controls.Add(box) form.Show() Application.Run(form) else: if not PILtk: errormessage = ( "Tkinter or Python Imaging " "Library not found, but is required for image " "display. See installation instructions for " "more information.") raise ImportError(errormessage) root = tk.Tk() root.title((hasattr(self, "title") and self.title) or self.__str__().rstrip()) frame = tk.Frame(root, colormap="new", visual='truecolor').pack() image = PIL.open(filename) imagedata = PILtk.PhotoImage(image) label = tk.Label(frame, image=imagedata).pack() quitbutton = tk.Button( root, text="Close", command=root.destroy).pack(fill=tk.X) root.mainloop() if filedes: os.close(filedes) os.remove(filename)
workbook.AddWorksheet("Colored Range") workbook["Colored Range"].Bounds = (3, 5, 8, 15) workbook["Colored Range"].ShowGrid = False workbook.AddWorksheet("Silly Colors - No Grid") workbook["Silly Colors - No Grid"].ShowGrid = False workbook.AddWorksheet("The Silly Colors") # Pre-constants user code from System.Drawing import Image from System.IO import Path directory = Path.GetDirectoryName(__file__) imagePath = Path.Combine(directory, '3d-space.jpg') image = Image.FromFile(imagePath) workbook.AddImageWorksheet("Gnuplot Image", image) # Constants and Formatting Constants = { 'Colored Range': { (3, 5): 'Reference', (3, 6): '0001', (3, 7): '0002', (3, 8): '0003', (3, 9): '0004', (3, 10): '0005', (3, 11): '0006', (3, 12): '0007', (3, 13): '0008', (3, 14): '0009',