def main(): args = parse_cmdline() screen_width = args.width screen_height = args.height square_width = screen_width / args.cols square_height = screen_height / args.rows image = wand.image.Image(width=screen_width, height=screen_height, background=wand.color.Color('#fff')) with wand.drawing.Drawing() as draw: draw.fill_color = wand.color.Color('#000') for r in range(args.rows): for c in range(args.cols): if not (c + r) % 2: continue x = square_width * c y = square_height * r logger.debug("%s %s %s %s", x, y, square_width, square_height) draw.rectangle(x, y, width=square_width, height=square_height) draw.draw(image) image.save(filename=args.filename) exit(0)
async def minecraft(self, ctx, *text): try: if len(text) == 0: text = "Насрал в штаны" else: text = " ".join(text) symbols = ( u"абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ", u"abvgdeejzijklmnoprstufhzcss_y_euaABVGDEEJZIJKLMNOPRSTUFHZCSS_Y_EUA" ) tr = {ord(a): ord(b) for a, b in zip(*symbols)} url = "https://mcgen.herokuapp.com/a.php?i=1&h=%s&t=%s" % ( text.capitalize().translate(tr), str( ctx.message.author.name).translate(tr)) response = requests.get(url) image = Image.open(BytesIO(response.content)) image.save("Images/Temp/minecraft.png", "PNG") await ctx.send(file=discord.File("Images/Temp/minecraft.png")) os.remove("Images/Temp/minecraft.png") except Exception as err: await ctx.send(tr("I pooped myself", ctx=ctx, err=err))
def open(url, mode='Pillow'): if hasattr(url, 'read') or isinstance(url, Image.Image): stream = url elif not urlutil.isurl(url): stream = io.open(url, 'rb') else: try: # wrap BytesIO for rewind stream stream = io.BytesIO(urlopen(url).read()) except: warning(u("Could not retrieve: %s"), url) raise IOError image = pillow_open(url, stream) if mode.lower() == 'pillow': # stream will be closed by GC return image else: # mode == 'png' try: png_image = io.BytesIO() image.save(png_image, 'PNG') if hasattr(stream, 'close'): # close() is implemented on Pillow stream.close() except: warning(u("Could not convert image: %s"), url) raise IOError png_image.seek(0) return png_image
def get_decipher_image(gene_name): dec_filename = os.path.join(cache_path, 'decipher_image_{}.png'.format(gene_name)) dec_url = 'https://decipher.sanger.ac.uk/search?q=%s#consented-patients/results' % gene_name if os.path.isfile(dec_filename): return dec_filename # 1- retrieve image convert_html(dec_url, '{}_source.png'.format(dec_filename), 3000) # 2- crop image if os.path.isfile(dec_filename + '_source.png'): with open(dec_filename + '_source.png', 'rb') as f: with wand.image.Image(file=f) as image: w = image.width - 10 h = image.height - 315 - 360 image.crop(5, 315, width=w, height=h) image.save(filename=dec_filename) os.remove(dec_filename + '_source.png') return dec_filename else: war('Unable to retrieve image from Decipher for the gene {}'. format(gene_name)) return None
def get_and_merge_images(dirs, best_auc, outfile, iteration=None): image = None for d in dirs: # Sort by the iteration number and pick the last one names = os.listdir(os.path.join(d, 'predictions')) names = list(filter(lambda name: re.search('_(\d+)[\._]', name) is not None, names)) if iteration is not None: names = list(filter( lambda name: re.findall('_(\d+)[\._]', name)[0] in [ str(iteration), str(iteration+1) ], names )) names = sorted( names, key=lambda name: int(re.findall('_(\d+)[\._]', name)[0]) ) if best_auc: names = list(filter(lambda s: '_best_auc' in s, names)) image_name = os.path.join(d, 'predictions', names[-1]) print('\t{}'.format(image_name)) if image is None: image = np.array(Image.open(image_name)) else: image += np.array(Image.open(image_name)) image = Image.fromarray(image) image.save(outfile)
def pil_to_wand(image): """ :param image: PIL.Image object """ filelike = io.BytesIO() image.save(filelike, "JPEG") filelike.seek(0) magick = wand.image.Image(blob=filelike) filelike.close() return magick
def thumbnail(image_data: io.BytesIO, max_size=(128, 128)) -> None: """Resize an image in place to no more than max_size pixels, preserving aspect ratio.""" with wand.image.Image(blob=image_data) as image: new_resolution = scale_resolution((image.width, image.height), max_size) image.resize(*new_resolution) image_data.truncate(0) image_data.seek(0) image.save(file=image_data) # allow resizing the original image more than once for memory profiling image_data.seek(0)
async def resize(imgurl : str, width : int, height : int): """Make an image swole or smoll, ?resize [url] [width] [height]""" imgid = str(randint(1,100)) imgname = "image" + imgid + imgurl[-4:] imgnamer = "image" + imgid + "_r" + imgurl[-4:] await bot.say("Resizing...") #urllib.request.urlretrieve(imgurl, imgname) with aiohttp.ClientSession() as session: async with session.get(imgurl) as resp: with open(imgname, 'wb') as image_file: image_file.write(await resp.content.read()) image_file.close() #await bot.send_file(ctx.message.channel, image_name) #d = urllib.request.urlopen(imgurl) #image_file = io.BytesIO(fd.read()) #im = Image.open(image_file) #imgfile = open(imgname, 'wb') #shutil.copyfileobj(im, imgfile) # with open(imgname, 'r+b') as f: with Image.open(f) as image: image = image.resize((width, height), PIL.Image.NEAREST) image.save(imgnamer) #cover.save(imgnamer, image.format) #output = open(imgname,"wb") #img = Image.open(output) #img = img.resize((int(size), int(size)), PIL.Image.ANTIALIAS) #imgb = img.tobytes() #output.write(imgb) #output.close() await bot.send_file(generalChannel, imgnamer) os.remove(imgname) os.remove(imgnamer)
def draw_grid(filename, grid, width, height, xoff, yoff): image = wand.image.Image(width=width, height=height, background=wand.color.Color('#fff')) with wand.drawing.Drawing() as draw: draw.fill_color = wand.color.Color('#f00') for r in range(len(grid)): # draw.fill_color = wand.color.Color('#{0:x}{0:x}{0:x}'.format(r*2)) for c in range(len(grid[r])): #logger.info("r: %s, c: %s", r, c) x = grid[r][c][0] + xoff y = grid[r][c][1] + yoff draw_point(draw, x, y) draw.draw(image) image.save(filename=filename)
def thumbnail(image_data: io.BytesIO, max_size=(128, 128)) -> io.BytesIO: """Resize an image in place to no more than max_size pixels, preserving aspect ratio. Return the new image. """ # Credit to @Liara#0001 (ID 136900814408122368) # https://gitlab.com/Pandentia/element-zero/blob/47bc8eeeecc7d353ec66e1ef5235adab98ca9635/element_zero/cogs/emoji.py#L243-247 with wand.image.Image(blob=image_data) as image: new_resolution = scale_resolution((image.width, image.height), max_size) image.resize(*new_resolution) # we create a new buffer here because there's wand errors otherwise. # specific error: # MissingDelegateError: no decode delegate for this image format `' @ error/blob.c/BlobToImage/353 out = io.BytesIO() image.save(file=out) # allow resizing the original image more than once for memory profiling image_data.seek(0) # allow reading the resized image data out.seek(0) return out
def get_decipher_image(gene_name): dec_filename = os.path.join(cache_path, 'decipher_image_{}.png'.format(gene_name)) dec_url = 'https://decipher.sanger.ac.uk/search?q=%s#consented-patients/results' % gene_name if os.path.isfile(dec_filename) : return dec_filename # 1- retrieve image convert_html(dec_url, '{}_source.png'.format(dec_filename), 3000) # 2- crop image if os.path.isfile(dec_filename + '_source.png'): with open(dec_filename + '_source.png', 'rb') as f: with wand.image.Image(file=f) as image: w = image.width - 10 h = image.height - 315 - 360 image.crop(5, 315, width=w, height=h) image.save(filename=dec_filename) os.remove(dec_filename + '_source.png') return dec_filename else: war('Unable to retrieve image from Decipher for the gene {}'.format(gene_name)) return None
week_number += 1 # Year numbers drawing for year in range(1, years + 1): xpos = (xoffs + (year * (box_width + box_margin))) * mm ypos = (yoffs + 2) * mm dwg.add( dwg.text(str(year), insert=(xpos, ypos), stroke='none', fill='black', font_size='2mm', font_weight="bold", font_family="Monospace")) # Week numbers drawing? for week in range(1, weeks_per_year + 1): pass svgstring = dwg.tostring() svg_blob = svgstring.encode('utf-8') # print(svgstring) # dwg.save() with wand.image.Image() as image: with wand.color.Color('transparent') as background_color: library.MagickSetBackgroundColor(image.wand, background_color.resource) image.read(blob=svg_blob) image.format = 'png' image.save(filename=filename)
async def shitup(imgurl : str, amount : int): """F**k shit up, ?shitup [image url] [amount] (smaller values = more f****d)""" imgid = str(randint(1,100)) imgname = "image" + imgid + imgurl[-4:] imgnamer = "image" + imgid + "_r" + imgurl[-4:] imgnamer1 = "image" + imgid + "_r2" + imgurl[-4:] await bot.say("Resizing...") #urllib.request.urlretrieve(imgurl, imgname) with aiohttp.ClientSession() as session: async with session.get(imgurl) as resp: with open(imgname, 'wb') as image_file: image_file.write(await resp.content.read()) image_file.close() #await bot.send_file(ctx.message.channel, image_name) #d = urllib.request.urlopen(imgurl) #image_file = io.BytesIO(fd.read()) #im = Image.open(image_file) #imgfile = open(imgname, 'wb') #shutil.copyfileobj(im, imgfile) # with open(imgname, 'r+b') as f: with Image.open(f) as image: origwidth = image.width origheight = image.height image2 = image.resize((amount, amount), PIL.Image.NEAREST) image2.save(imgnamer) with open(imgnamer, 'r+b') as f2: with Image.open(f2) as image: image = image.resize((origwidth, origheight), PIL.Image.NEAREST) image.save(imgnamer1) #cover.save(imgnamer, image.format) #output = open(imgname,"wb") #img = Image.open(output) #img = img.resize((int(size), int(size)), PIL.Image.ANTIALIAS) #imgb = img.tobytes() #output.write(imgb) #output.close() await bot.send_file(generalChannel, imgnamer1) os.remove(imgname) os.remove(imgnamer) os.remove(imgnamer1)