def __drawPictureThumbnail(self): # load original image origImage = Bitmap.FromFile(self.filename, False) # calculate size = ThumbnailSize if self.__dims is None: self.__dims = (origImage.Width, origImage.Height) width, height = self.CalcResizedDims(size) drawWidth, drawHeight = width, height width, height = max(width, size), max(height, size) drawXOffset, drawYOffset = (width - drawWidth) / 2, (height - drawHeight) / 2 # draw new image newImage = Bitmap(width, height) g = Graphics.FromImage(newImage) g.InterpolationMode = InterpolationMode.HighQualityBicubic g.FillRectangle(Brushes.GhostWhite, 0, 0, width, height) g.DrawRectangle(Pens.LightGray, 0, 0, width - 1, height - 1) g.DrawImage(origImage, drawXOffset, drawYOffset, drawWidth, drawHeight) imageBytes = BitmapToBytes(newImage) # cleanup g.Dispose() newImage.Dispose() origImage.Dispose() return imageBytes
def average_hash_and_sizes(self): height = 0 width = 0 if isJython(): image = ImageIO.read(File(self.image_path)) height = image.getHeight() width = image.getWidth() newImage = BufferedImage(self.hash_size, self.hash_size, BufferedImage.TYPE_INT_ARGB) g = newImage.createGraphics() g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC) g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY) g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.drawImage(image, 0, 0, self.hash_size, self.hash_size, None) g.dispose() allchannelpixels = [[], [], [], []] for i in range(self.hash_size): for j in range(self.hash_size): pixel = int(newImage.getRGB(i, j)) allchannelpixels[0].append((pixel >> 16) & 0xFF) allchannelpixels[1].append((pixel >> 8) & 0xFF) allchannelpixels[2].append((pixel) & 0xFF) allchannelpixels[3].append((pixel >> 24) & 0xFF) elif isIronPython(): srcImage = Bitmap(self.image_path) height = srcImage.Height width = srcImage.Width newImage = Bitmap(self.hash_size, self.hash_size) gr = Graphics.FromImage(newImage) gr.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias gr.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic gr.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality gr.DrawImage(srcImage, Rectangle(0, 0, self.hash_size, self.hash_size)) allchannelpixels = [[], [], [], []] for i in range(self.hash_size): for j in range(self.hash_size): pixel = newImage.GetPixel(i, j) allchannelpixels[0].append(int(pixel.R)) allchannelpixels[1].append(int(pixel.G)) allchannelpixels[2].append(int(pixel.B)) allchannelpixels[3].append(int(pixel.A)) else: self.image = Image.open(self.image_path) width, height = self.image.size image = self.image.resize((self.hash_size, self.hash_size), Image.ANTIALIAS) # image.show() allchannelpixels = [ list(channel.getdata()) for channel in image.split() ] bits = [] for pixels in allchannelpixels: bits.append(self.getBitString(pixels)) return bits, width, height
def _cli_screenshot(self, path): bmp = Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height) graphics = Graphics.FromImage(bmp) try: graphics.CopyFromScreen(0, 0, 0, 0, bmp.Size) finally: graphics.Dispose() bmp.Save(path, Imaging.ImageFormat.Jpeg)
def pick(snip=False): snipper = PickSnipTool(PickSnipTool.take_screenshot(), snip=snip) while True: result = snipper.ShowDialog() if result in [DialogResult.OK, DialogResult.Cancel]: break if snipper.mouse_down_seconds == 1: Mouse.Instance.Click(snipper.mouse_down) time.sleep(0.5) snipper.BackgroundImage = PickSnipTool.take_screenshot() if result == DialogResult.OK and snip: if snipper.snip_rectangle.Width and snipper.snip_rectangle.Height: img = Bitmap( snipper.snip_rectangle.Width, snipper.snip_rectangle.Height, ) gr = Graphics.FromImage(img) gr.DrawImage( snipper.BackgroundImage, Rectangle(0, 0, img.Width, img.Height), snipper.snip_rectangle, GraphicsUnit.Pixel, ) fp = MemoryStream() img.Save(fp, ImageFormat.Png) return { 'bytes': bytes(bytearray(fp.ToArray())), } return {} elif result == DialogResult.OK: if (snipper.mouse_down_seconds and snipper.mouse_down_seconds <= snipper.click_timeout): Mouse.Instance.Click(snipper.mouse_down) time.sleep(0.5) el = AutomationElement.FromPoint(snipper.mouse_up) result = { prop.ProgrammaticName.split('.', 1)[-1]: el.GetCurrentPropertyValue(prop) for prop in el.GetSupportedProperties() } result.update({ 'NameProperty': el.GetCurrentPropertyValue(el.NameProperty), 'ControlTypeProperty': el.GetCurrentPropertyValue( el.ControlTypeProperty, ).ProgrammaticName.split('.', 1)[-1], 'AutomationIdProperty': el.GetCurrentPropertyValue(el.AutomationIdProperty, ), }) return result else: return {}
def take_screenshot(as_bytes=False): bounds = Screen.PrimaryScreen.Bounds screenshot = Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppPArgb) graphics = Graphics.FromImage(screenshot) graphics.CopyFromScreen(0, 0, 0, 0, screenshot.Size) if as_bytes: fp = MemoryStream() screenshot.Save(fp, ImageFormat.Png) return bytes(bytearray(fp.ToArray())) else: return screenshot
class Image(object): ImageEncoders = dict([(i.MimeType, i) for i in ImageCodecInfo.GetImageEncoders()]) @staticmethod def ImageFromZip(zipFile, file): if ZipFile is None: raise Exception( "'Ionic.Zip.dll' not found! ZipFile not supported!") z = ZipFile(zipFile) m = MemoryStream() e = z[file] e.Extract(m) return Image(m) def __init__(self, file): self._file = file self._bitmap = Bitmap(file) @property def width(self): return self._bitmap.Width @property def height(self): return self._bitmap.Height def resize(self, width, height): rImg = Bitmap(width, height) g = Graphics.FromImage(rImg) g.InterpolationMode = HighQualityBicubic g.DrawImage(self._bitmap, 0, 0, width, height) g.Dispose() self._bitmap.Dispose() self._bitmap = rImg def crop(self, left=0, top=0, right=0, bottom=0): width = self._bitmap.Width - right height = self._bitmap.Height - bottom r = Rectangle(left, top, width, height) try: cropImage = self._bitmap.Clone(r, self._bitmap.PixelFormat) except: print "retrying rectangle=%s" % str(r) self.resize(self._bitmap.Width + 10, self._bitmap.Height + 10) try: cropImage = self._bitmap.Clone(r, self._bitmap.PixelFormat) except Exception, e: print "Error in crop: %s" % str(e) return self._bitmap.Dispose() self._bitmap = cropImage
def crop_image(img_path, rectangle_crop): source_bmp = Bitmap(img_path) new_img_path = create_img_copy(img_path) # Without this, images that are not 96 dpi get cropped out of scale source_bmp.SetResolution(96, 96) # An empty bitmap which will hold the cropped image bmp = Bitmap(rectangle_crop.Width, rectangle_crop.Height) graphic = Graphics.FromImage(bmp) # Draw the given area (rectangle_crop) of the source_bmp image at location 0,0 on the empty bitmap (bmp) graphic.DrawImage(source_bmp, 0, 0, rectangle_crop, GraphicsUnit.Pixel) cropped_img = bmp cropped_img.Save(new_img_path) return new_img_path
def strip_back_cover(image): """ Checks the given image to see if it has the pixel ratio of 2 comic book pages side by side. If it does NOT, then this method does nothing and the given image is returned without modification. But if it does have that magic pixel ratio, then we assume that the 2 pages are the front and back covers of a comic book (on the right and left halves of the image, respectively) and we create and return a NEW image that contains only the front cover (right half) of the original. If a new image is returned, this method will call Dispose on the original. """ if image: pixel_ratio = float(image.Width) / float(image.Height) if pixel_ratio < 1.5 and pixel_ratio > 1.2: # create a new image with the back cover (left half) deleted new_image = Bitmap(image.Width / 2, image.Height) graphics = Graphics.FromImage(new_image) graphics.DrawImage(image, -image.Width / 2, 0) graphics.Dispose() image.Dispose() image = new_image return image
def __init__(self): ListView.__init__(self) self.SuspendLayout() # List appearance self.Dock = DockStyle.Fill self.View = View.Details self.GridLines = True self.FullRowSelect = True self.HeaderStyle = ColumnHeaderStyle.None self.ShowItemToolTips = True self.Columns.Add("", -2, HorizontalAlignment.Left) # Events self.Resize += self.__OnResize self.DoubleClick += self.__OnDoubleClick # Register this class as the sink for all messages. # The higher level passes self.Reporter to the Modules. self.Reporter = FTReport.FTReporter() self.Reporter.RegisterUIHandler(self.Report) # Configure icons self.SmallImageList = ImageList() images = ("information", "exclamation", "cross_circle") for i in images: self.SmallImageList.Images.Add( Bitmap.FromFile(i.join(UIGlobal.ReportIconParams))) self.ResumeLayout(False)
def createFilelessComics(self, exportlist, tagstext): #Get a correctly formated string of the tags #print "Starting to create" tags = "" if tagstext: tags = self.createtaglist(tagstext) #print "finished getting tags" for item in exportlist: #The series and number and come together in the title, seperate them out. series, number, count = self.seperateSeriesAndNumber(item["Title"]) comic = ComicRack.App.AddNewBook(False) comic.Series = series #Remember number is a string and count is an integer comic.Number = number if count: comic.Count = int(count) comic.Publisher = item["Publisher"].title() comic.Tags = tags #Try to add a cover by loading a bitmap from the cover's file path try: if item["Image"]: b = Bitmap(item["Image"]) ComicRack.App.SetCustomBookThumbnail(comic, b) del (b) except Exception, ex: print ex
def DrawResizedImage(self, size): # load original image origImage = Bitmap.FromFile(self.filename, False) # calculate if self.__dims is None: self.__dims = (origImage.Width, origImage.Height) width, height = self.CalcResizedDims(size) # draw new image newImage = Bitmap(width, height) g = Graphics.FromImage(newImage) g.InterpolationMode = InterpolationMode.HighQualityBicubic g.DrawImage(origImage, 0, 0, width, height) imageBytes = BitmapToBytes(newImage) # cleanup g.Dispose() newImage.Dispose() origImage.Dispose() return imageBytes
def resize(self, width, height): rImg = Bitmap(width, height) g = Graphics.FromImage(rImg) g.InterpolationMode = HighQualityBicubic g.DrawImage(self._bitmap, 0, 0, width, height) g.Dispose() self._bitmap.Dispose() self._bitmap = rImg
def take_screenshot(): bounds = Screen.PrimaryScreen.Bounds screenshot = Bitmap( bounds.Width, bounds.Height, PixelFormat.Format32bppPArgb, ) graphics = Graphics.FromImage(screenshot) graphics.CopyFromScreen(0, 0, 0, 0, screenshot.Size) return screenshot
def __drawFolderThumbnail(self, parent): size = ThumbnailSize # create new image newImage = Bitmap(size, size) g = Graphics.FromImage(newImage) g.InterpolationMode = InterpolationMode.HighQualityBicubic # draw background if parent: bc = ParentFolderColor else: bc = ChildFolderColor b = LinearGradientBrush(Point(0, 0), Point(size, size), bc, Color.GhostWhite) g.FillRectangle(b, 0, 0, size, size) b.Dispose() g.DrawRectangle(Pens.LightGray, 0, 0, size - 1, size - 1) # draw up to 4 subitems folderItems = self.GetFirstFolderItems(4) delta = 10 side = (size - 3 * delta) / 2 - 1 rects = (Rectangle(delta + 3, delta + 12, side, side), Rectangle(size / 2 + delta / 2 - 3, delta + 12, side, side), Rectangle(delta + 3, size / 2 + delta / 2 + 6, side, side), Rectangle(size / 2 + delta / 2 - 3, size / 2 + delta / 2 + 6, side, side)) for rect, item in zip(rects, folderItems): subImage = Bitmap.FromStream(MemoryStream(item.thumbnail()), False) g.DrawImage(subImage, rect) subImage.Dispose() for rect in rects: g.DrawRectangle(Pens.LightGray, rect) # draw folder name if parent: name = '[..]' else: name = Path.GetFileName(self.path) f = Font('Arial', 10) g.DrawString(name, f, Brushes.Black, RectangleF(2, 2, size - 2, size - 2)) f.Dispose() # get the bytes of the image imageBytes = BitmapToBytes(newImage) # cleanup g.Dispose() newImage.Dispose() return imageBytes
def write(self, contents, size=400, encode='utf-8'): writer = BarcodeWriter() writer.Format = BarcodeFormat.QR_CODE writer.Options = new(QrCodeEncodingOptions, DisableECI = True, CharacterSet = encode, Width = size, Height = size) mtx = writer.Write(contents) bmp = Bitmap(mtx) return BitmapUtils.netbmp_to_pil(bmp)
def __copy_transparent(self, image): ''' Creates a semi-transparent copy of the given image ''' b = Bitmap( image.Width, image.Height ) g = Graphics.FromImage(b) cm = ColorMatrix() cm.Matrix33 = 0.3 ia = ImageAttributes() ia.SetColorMatrix(cm) g.DrawImage(image, Rectangle(0,0, image.Width, image.Height), 0,0,\ image.Width, image.Height, GraphicsUnit.Pixel, ia) return b
def __buttonBuilder(self, buttonDetails): button = ToolBarButton() if buttonDetails: button.Text = buttonDetails[self.__BUTTON_Text] button.ToolTipText = buttonDetails[self.__BUTTON_Tooltip] self.ImageList.Images.Add( Bitmap.FromFile(buttonDetails[self.__BUTTON_Image].join( UIGlobal.ToolbarIconParams))) button.ImageIndex = self.ImageList.Images.Count - 1 button.Tag = buttonDetails else: button.Style = ToolBarButtonStyle.Separator self.Buttons.Add(button)
def ScreenCapture(x, y, width, height): 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 __perceptual_hash(image): ''' Returns a 'perceptual' image hash for the given Image. ''' if image is not None: SIZE = 8 # create ImageAttributes for converting image to greyscale # see: http://tech.pro/tutorial/660/ # csharp-tutorial-convert-a-color-image-to-grayscale attr = ImageAttributes() attr.SetColorMatrix( ColorMatrix(Array[Array[Single]](( \ (0.3, 0.3, 0.3, 0.0, 0.0), (.59, .59, .59, 0.0, 0.0), (.11, .11, .11, 0.0, 0.0), (0.0, 0.0, 0.0, 1.0, 0.0), (0.0, 0.0, 0.0, 0.0, 1.0) ))) ) with Bitmap(SIZE, SIZE, PixelFormat.Format64bppArgb) as small_image: with Graphics.FromImage(small_image) as g: # draw image in greyscale in a tiny square # see: https://www.memonic.com/user/aengus/folder/coding/id/1qVeq g.CompositingQuality = CompositingQuality.HighQuality g.SmoothingMode = SmoothingMode.HighQuality g.InterpolationMode = InterpolationMode.HighQualityBicubic g.DrawImage(image, Rectangle(0, 0, SIZE, SIZE), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attr) # convert image pixels into bits, where 1 means pixel is greater # than image average, and 0 means pixel is less than average. # return bits as a single long value pixels = [ small_image.GetPixel(x, y).R for x in range(SIZE) for y in range(SIZE) ] 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)
def __init__(self): """ContextMenuStripSample class init function.""" # set up form self.Text = "ContextMenuStrip control" # set up menu items sample_dir = sys.path[0] image_path = os.path.join(sample_dir, "apple-red.png") self.toolstrip_menuitem1 = ToolStripMenuItem("Apple") self.toolstrip_menuitem1.Click += self.cms_click self.toolstrip_menuitem1.Image = Bitmap.FromFile(image_path) self.toolstrip_menuitem1a = ToolStripMenuItem("Macintosh") self.toolstrip_menuitem1b = ToolStripMenuItem("Delicious") self.toolstrip_menuitem2 = ToolStripMenuItem("Banana") self.toolstrip_menuitem2.Click += self.cms_click self.toolstrip_menuitem3 = ToolStripMenuItem("Watermelon") self.toolstrip_menuitem3.Click += self.cms_click self.toolstrip_menuitem4 = ToolStripMenuItem("Orange") self.toolstrip_menuitem4.Click += self.cms_click self.toolstrip_menuitem5 = ToolStripMenuItem("Peach") self.toolstrip_menuitem5.Click += self.cms_click # set up context_menu_strip self.context_menu_strip = ContextMenuStrip() self.toolstrip_menuitem1.DropDownItems.Add(self.toolstrip_menuitem1a) self.toolstrip_menuitem1.DropDownItems.Add(self.toolstrip_menuitem1b) self.context_menu_strip.Items.Add(self.toolstrip_menuitem1) self.context_menu_strip.Items.Add(self.toolstrip_menuitem2) self.context_menu_strip.Items.Add(self.toolstrip_menuitem3) self.context_menu_strip.Items.Add(self.toolstrip_menuitem4) self.context_menu_strip.Items.Add(self.toolstrip_menuitem5) # set up label self.label = Label() self.label.Text = "Right Click on me to see ContextMenuStrip" self.label.Width = 200 self.label.Height = 50 self.label.ContextMenuStrip = self.context_menu_strip self.label.BackColor = Color.Cyan self.label.BorderStyle = BorderStyle.FixedSingle # add controls self.Controls.Add(self.label)
def __init__(self, buttonList, imagePathTuple): ToolBar.__init__(self) self.Appearance = ToolBarAppearance.Flat self.Dock = DockStyle.Top self.HandlerList = [] self.ImageList = ImageList() for bParams in buttonList: button = ToolBarButton() if bParams: handler, button.Text, imageName, button.ToolTipText = bParams self.ImageList.Images.Add( Bitmap.FromFile(imageName.join(imagePathTuple))) button.ImageIndex = self.ImageList.Images.Count - 1 self.HandlerList.append(handler) button.Tag = len(self.HandlerList) - 1 else: button.Style = ToolBarButtonStyle.Separator self.Buttons.Add(button) self.ButtonClick += self.__OnButtonClick
def __init__(self, moduleManager, contents): ListBox.__init__(self) self.moduleManager = moduleManager # behaviour self.LabelEdit = False self.MultiSelect = False # appearance self.Dock = DockStyle.Fill self.ScrollAlwaysVisible = True self.TabIndex = 0 self.HideSelection = False # Keep selected item grey when lost focus self.textBrush = SolidBrush(SystemColors.WindowText) self.icon = Bitmap(UIGlobal.ModuleIcon) self.DrawMode = DrawMode.OwnerDrawVariable self.DrawItem += self.OnDrawItem self.MeasureItem += self.OnMeasureItem self.UpdateAllItems(contents)
def on_print(sender, event): # Get screenshot bmp = Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, event.Graphics) event.Graphics.CopyFromScreen(0, 0, 0, 0, bmp.Size)
def __init__(self, file): self._file = file self._bitmap = Bitmap(file)
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 = [] n = 0 for i in c: LPy.append(n*PixelWidth) n=n+1 LPx2=[] n=len(LPy)
def __getDimensions(self): if self.__dims is None: origImage = Bitmap.FromFile(self.filename, False) self.__dims = (origImage.Width, origImage.Height) origImage.Dispose() return self.__dims