def generate_image(args): # do format lexer = get_lexer_by_name(args['lexer'], stripall=True) formatter = ImageFormatter(image_format='png', font_name=args['font_name'], font_size=args['font_size'], style=args['style'], line_number_chars=3, image_pad=24, linenos=True) ## generate formatted image result = highlight(args['code'], lexer, formatter) file_link, file_path = get_image_path(args) # attach watermark image = Image.open(StringIO(result)) mark = Image.open(setting['watermark']) mark_pos = (image.size[0] - mark.size[0], 0) out = watermark(image, mark, mark_pos, 0.5) # make directories if not exist if not exists(dirname(file_path)): makedirs(dirname(file_path)) # write file to disk out.save(file_path) return file_link, file_path
async def coder_print(event): cmd = event.text a = await event.get_reply_message() coder = "" if len(cmd) > 7: coder = " ".join(cmd[7:]) elif event.reply_to_msg_id and len(cmd) == 6: coder = a.message elif len(cmd) == 6: await event.reply("`No text Given`") await asyncio.sleep(2) await event.delete() return pygments.highlight( f"{coder}", Python3Lexer(), ImageFormatter(font_name="LiberationMono-Regular.ttf", line_numbers=True), "out.png", ) await event.client.send_file(event.chat_id, "out.png", force_document=False) await event.delete() os.remove("out.png")
def main(): highligth_marker = re.compile("\#\#\s*$") if sys.argv[1:]: path = sys.argv[1] else: path = "." for f in glob.glob(os.path.join(path, "*.py")): code = open(f).readlines() # collect the lines to be highlighted highlights = [] for i, line in enumerate(code): line = line.rstrip() if highligth_marker.search(line): code[i] = highligth_marker.sub("", line) highlights.append(i + 1) else: code[i] = line data = highlight( "\n".join(code), PythonLexer(), ImageFormatter(font_size=24, style=PYGMENTS_STYLE, hl_lines=highlights, hl_color=HIGHLIGHT_COLOR)) open(f + '.png', 'wb').write(data)
def main(new_width=n): # attempt to open image from user-input d = down try: image = PIL.Image.open(d) except: pass # convert image to ascii new_image_data = pixels_to_ascii(grayify(resize_image(image))) # format pixel_count = len(new_image_data) ascii_image = "\n".join([ new_image_data[index:(index + new_width)] for index in range(0, pixel_count, new_width) ]) # save result to "ascii_image.txt" with open("ascii_image.txt", "w") as f: f.write(ascii_image) s = open("ascii_image.txt", 'r') c = s.read() s.close() pygments.highlight( f"{c}", Python3Lexer(), ImageFormatter(font_name="DejaVu Sans Mono", line_numbers=False), "ascii.png") imgs = "ascii.png" shvm = PIL.Image.open(imgs) sh1, vam = image.size img = shvm.resize((int(sh1), int(vam))) img.save("asci.png", format="PNG", optimize=True)
async def mkc(event): a = await event.client.download_media(await event.get_reply_message(), Config.TMP_DOWNLOAD_DIRECTORY) s = open(a, "r") c = s.read() s.close() pygments.highlight( f"{c}", Python3Lexer(), ImageFormatter(font_name="LiberationMono-Regular.ttf", line_numbers=True), "out.png", ) res = await event.client.send_message( event.chat_id, "**Pasting this code on my page...**", reply_to=event.reply_to_msg_id, ) await event.client.send_file(event.chat_id, "out.png", force_document=True, reply_to=event.reply_to_msg_id) await event.client.send_file(event.chat_id, "out.png", force_document=False, reply_to=event.reply_to_msg_id) await res.delete() await event.delete() os.remove(a) os.remove("out.png")
async def coder_print(event): a = await event.client.download_media(await event.get_reply_message(), Var.TEMP_DOWNLOAD_DIRECTORY) s = open(a, 'r') c = s.read() s.close() pygments.highlight( f"{c}", Python3Lexer(), ImageFormatter(font_name="DejaVu Sans Mono", line_numbers=True), "out.png") res = await event.client.send_message( event.chat_id, "**Pasting this code on my page pls weit🤓...**", reply_to=event.reply_to_msg_id) await event.client.send_file(event.chat_id, "out.png", force_document=True, reply_to=event.reply_to_msg_id) await event.client.send_file(event.chat_id, "out.png", force_document=False, reply_to=event.reply_to_msg_id) await res.delete() await event.delete() os.remove(a) os.remove('out.png')
async def coder_print(event): input = event.pattern_match.group(1) a = await event.client.download_media(await event.get_reply_message(), Var.TEMP_DOWNLOAD_DIRECTORY) s = open(a, 'r') c = s.read() s.close() pygments.highlight( f"{c}", Python3Lexer(), ImageFormatter(font_name="DejaVu Sans Mono", line_numbers=True), "out.png") if 'doc' in input: await event.client.send_file(event.chat_id, "out.png", force_document=True) await event.delete() os.remove(a) os.remove('out.png') else: await event.client.send_file(event.chat_id, "out.png", force_document=False) await event.delete() os.remove(a) os.remove('out.png')
async def coder_print(event): if not event.reply_to_msg_id: return await eod(event, "`Reply to a file or message!`", time=5) msg = await event.get_reply_message() if msg.document: a = await event.client.download_media(await event.get_reply_message(), "ncode.png") with open(a, "r") as s: c = s.read() else: a = None c = msg.text pygments.highlight( c, Python3Lexer(), ImageFormatter(line_numbers=True), "result.png", ) res = await event.client.send_message( event.chat_id, "**Pasting this code on my page...**", reply_to=event.reply_to_msg_id, ) await event.client.send_file(event.chat_id, "result.png", force_document=True, reply_to=event.reply_to_msg_id) await res.delete() await event.delete() if a: os.remove(a) os.remove("result.png")
def imagecode(line, cell): "pygments magic cell for Jupyter noebook" lexer = PythonLexer() return Image(highlight( cell, lexer, ImageFormatter(image_format='PNG'), ))
def get_formatter(self): style = DefaultStyle style.background_color = self.background_color return ImageFormatter(font_name="Liberation Mono", line_pad=10, line_numbers=False, style=style, font_size=25)
def __init__(self, lexer, style='default', **kwargs): self.lexer = get_lexer_by_name(lexer) self.code_style = get_style_by_name(style) if 'window_frame_color' in kwargs.keys(): if bool(kwargs['window_frame_color']): self.window_frame_color = kwargs['window_frame_color'] if 'bg_from_color' in kwargs.keys(): if bool(kwargs['bg_from_color']): self.bg_from_color = kwargs['bg_from_color'] if 'bg_to_color' in kwargs.keys(): if bool(kwargs['bg_to_color']): self.bg_to_color = kwargs['bg_to_color'] if 'close_circle' in kwargs.keys(): if bool(kwargs['close_circle']): self.close_circle = kwargs['close_circle'] if 'maximize_circle' in kwargs.keys(): if bool(kwargs['maximize_circle']): self.maximize_circle = kwargs['maximize_circle'] if 'minimize_circle' in kwargs.keys(): if bool(kwargs['minimize_circle']): self.minimize_circle = kwargs['minimize_circle'] if 'font_size' in kwargs.keys(): if bool(kwargs['font_size']): self.font_size = kwargs['font_size'] if 'font_name' in kwargs.keys(): if bool(kwargs['font_name']): self.font_name = kwargs['font_name'] if 'line_pad' in kwargs.keys(): if bool(kwargs['line_pad']): self.line_pad = kwargs['line_pad'] if 'line_numbers' in kwargs.keys(): self.line_numbers = kwargs['line_numbers'] if 'background_color' in kwargs.keys(): if bool(kwargs['background_color'].strip()): self.code_style.background_color = kwargs['background_color'] if 'highlight_color' in kwargs.keys(): if bool(kwargs['highlight_color'].strip()): self.code_style.highlight_color = kwargs['highlight_color'] self.formatter = ImageFormatter( font_size=self.font_size, font_name=self.font_name, line_pad=self.line_pad, line_numbers=self.line_numbers, style=self.code_style, )
def render_code(self, code, lang): formatter = ImageFormatter(font_size=FONT_SIZE, line_numbers=False, style=CODE_STYLE) image = pygame.image.load( BytesIO(highlight(code, get_lexer_by_name(lang), formatter)), 'code.png') image.convert() return image
def paste_img_all(id): data = query_db("select * from pastes where id = ?", [id], one=True) try: Lexer = get_lexer_by_name(data["syntaxhighlight"].lower()) except: Lexer = get_lexer_by_name("python") return Response(highlight(data["text"], Lexer, ImageFormatter(linenos=True)), mimetype="image/png")
def get_formatter(self): style = DefaultStyle style.background_color = self.code_bg return ImageFormatter( font_size=self.font_size, font_name=self.font_name, line_pad=self.line_pad, line_numbers=self.line_numbers, style=style, )
def save(self, *args, **kwargs): lexer = get_lexer_by_name(self.language) formatter = ImageFormatter(style=self.style, line_numbers=self.linenos, font_size=32, image_format='PNG', image_pad=20) image_file = highlight(self.source, lexer, formatter) self.highlighted = base64.b64encode(image_file).decode() print(len(self.highlighted)) super(Snippet, self).save(*args, **kwargs)
def generate(inpath, outpath=None, style='autumn'): outpath = outpath or inpath.rsplit('.')[0] + '.png' with open(inpath) as infile: with open(outpath, 'w') as outfile: lexer = get_lexer_for_filename(inpath) formatter = ImageFormatter(style=style, line_numbers=False, font_size=42, font_name='dejavu sans mono') highlight(infile.read(), lexer, formatter, outfile) resize(outpath) return outpath
def on_get_img(bot, update: Update, user_data): query: CallbackQuery = update.callback_query if query.data != 'get_img': return State.task_process code = user_data['solution'] img = highlight(code, PythonLexer(), ImageFormatter()) msg: Message = query.message msg.reply_photo(BytesIO(img)) return State.task_process
async def paste_img(event): "To paste text to image." reply_to = await reply_id(event) d_file_name = None catevent = await edit_or_reply(event, "`Pasting the text on image`") input_str = event.pattern_match.group(1) reply = await event.get_reply_message() ext = re.findall(r"-f", input_str) extension = None try: extension = ext[0].replace("-", "") input_str = input_str.replace(ext[0], "").strip() except IndexError: extension = None text_to_print = "" if input_str: text_to_print = input_str if text_to_print == "" and reply.media: mediatype = media_type(reply) if mediatype == "Document": d_file_name = await event.client.download_media( reply, Config.TEMP_DIR) with open(d_file_name, "r") as f: text_to_print = f.read() if text_to_print == "": if reply.text: text_to_print = reply.raw_text else: return await edit_delete( catevent, "`Either reply to text/code file or reply to text message or give text along with command`", ) pygments.highlight( text_to_print, Python3Lexer(), ImageFormatter(font_name="DejaVu Sans Mono", line_numbers=True), "out.png", ) try: await event.client.send_file( event.chat_id, "out.png", force_document=bool(extension), reply_to=reply_to, ) await catevent.delete() os.remove("out.png") if d_file_name is not None: os.remove(d_file_name) except Exception as e: await edit_delete(catevent, f"**Error:**\n`{str(e)}`", time=10)
def get(self): try: paste, lang = self._get_paste(["paste", "lang"]) except KeyError: self.clear() self.set_status(404) self.finish("<html><body>Not found</body></html>") return lexer = pygments.lexers.get_lexer_by_name(lang) formatter = ImageFormatter(font_name="DroidSansMono", font_size=15) paste = highlight(paste, lexer, formatter) self.set_header("Content-Type", 'text/plain; charset="utf-8"') self.finish(paste)
def code(key, value, format, _): if key == 'CodeBlock': [[ident, classes, keyvals], code] = value caption, typef, keyvals = get_caption(keyvals) # outfile = get_filename4code("pandoc_code", code) # dest = f"{outfile}.png" lexer = get_lexer_by_name(classes[0], stripall=True) code_img = highlight(code, lexer, ImageFormatter(image_format="PNG", font_size=18)) # with open(dest, "wb") as f: # f.write(code_img) code_img = base64.b64encode(code_img).decode("ascii") return RawBlock("html", f'<img src="data:image/png;base64,{code_img}">')
def generate_image(self, params): filepath = params.filepath try: lexer = get_lexer_for_filename(filepath) except ClassNotFound as e: log.error(e) raise SourceError(str(e)) if lexer is None: raise SourceError('cannot find a lexer for %s' % filepath) self._trace.add_step('source file', filepath) self._trace.add_step('detected language', lexer.name.lower()) formatter = ImageFormatter(font_name=params.font_name, font_size=params.font_size, line_numbers=False) code = None with open(filepath, 'r') as f: code = f.read() output = BytesIO(highlight(code, lexer, formatter)) im = PILImage.open(output) dt = get_desktop() dw, dh = dt.get_size() if im.height > dh: im = im.crop((0, 0, im.width, dh)) image = Image() image.i_width, image.i_height = im.width, im.height fn, temp_filepath = tempfile.mkstemp() f = os.fdopen(fn, 'wb') im.save(f, 'png') f.close() im.close() image.ext = image.type = 'png' image.temp_filepath = temp_filepath return image
async def pypngcmd(self, message): """reply to text code or py file""" message.edit("<b>Py to PNG</b>") reply = await message.get_reply_message() if not reply: await message.edit("<b>reply to file.py</b>") return media = reply.media if not media: await message.edit("<b>reply to file.py</b>") return file = await message.client.download_file(media) text = file.decode('utf-8') pygments.highlight(text, Python3Lexer(), ImageFormatter(font_name='DejaVu Sans Mono', line_numbers=True), 'out.png') await message.client.send_file(message.to_id, 'out.png', force_document=True) os.remove("out.png") await message.delete()
def generate_code_image(code, save_image=False, qname=None): # Generate file name from question name Path('img').mkdir(parents=True, exist_ok=True) if save_image and qname != None: fname = "img/" + qname.replace(" ", "-") + ".png" else: fname = "img/out.png" # Use pygments to highlight the code and generate image with open(fname, "wb") as png_file: highlight(code, CLexer(), ImageFormatter(line_pad=4, image_pad=5, line_numbers=False), png_file) # Encode image as a base64 string with open(fname, 'rb') as image_file: encoded_str = base64.b64encode(image_file.read()).decode('UTF-8') img_str = '<img alt="code-fig" src="data:image/png;base64,{}">'.format( encoded_str) return img_str
def __init__(self, **kwargs): super(Code2Image, self).__init__() self.code_bg = kwargs.get('code_bg', '#661A0A') self.font_size = kwargs.get('font_size', 16) self.font_name = kwargs.get('font_name', 'Liberation Mono') self.line_pad = kwargs.get('line_pad', 5) self.line_numbers = kwargs.get('line_numbers', False) self.formatter = ImageFormatter( font_size=self.font_size, font_name=self.font_name, line_pad=self.line_pad, line_numbers=self.line_numbers, style=DefaultStyle, ) self.lexer = PythonLexer() for name, attr in kwargs.items(): setattr(self, name, attr)
def create_text_thumb(gio_file, size=None, threshold=2): """ tries to use pygments to get a thumbnail of a text file """ if pygments is None: return None try: lexer = get_lexer_for_mimetype(gio_file.mime_type) except pygments.util.ClassNotFound: lexer = get_lexer_for_mimetype("text/plain") if chardet: lexer.encoding = "chardet" thumb = tempfile.NamedTemporaryFile() formatter = ImageFormatter(font_name="DejaVu Sans Mono", line_numbers=False, font_size=10) # to speed things up only highlight the first 20 lines content = "\n".join(gio_file.get_content().split("\n")[:20]) try: content = highlight(content, lexer, formatter) except (UnicodeDecodeError, TypeError): # we can't create the pixbuf return None thumb.write(content) thumb.flush() thumb.seek(0) try: pixbuf = gtk.gdk.pixbuf_new_from_file(thumb.name) except glib.GError: return None # (LP: #743125) thumb.close() if size is not None: new_height = None new_width = None height = pixbuf.get_height() width = pixbuf.get_width() if width > threshold * size[0]: new_width = threshold * size[0] if height > threshold * size[1]: new_height = threshold * size[1] if new_height is not None or new_width is not None: pixbuf = __crop_pixbuf(pixbuf, 0, 0, (new_width or width, new_height or height)) return pixbuf
async def code_print(event): if event.fwd_from: return reply_to = await reply_id(event) catevent = await edit_or_reply(event, "`Printing the text on blank page...`") input_str = event.pattern_match.group(1) reply = await event.get_reply_message() text_to_print = "" if reply: mediatype = media_type(reply) if mediatype == "Document": d_file_name = await event.client.download_media(reply, "./temp/") f = open(d_file_name, "r") text_to_print = f.read() if text_to_print == "": if input_str: text_to_print = input_str elif event.reply_to_msg_id: text_to_print = reply.message else: await edit_delete( catevent, "`Either reply to document or reply to text message or give text along with command`", ) pygments.highlight( text_to_print, Python3Lexer(), ImageFormatter(font_name="DejaVu Sans Mono", line_numbers=True), "out.png", ) try: await event.client.send_file(event.chat_id, "out.png", force_document=False, reply_to=reply_to) except Exception as e: await edit_delete(catevent, str(e), parse_mode=parse_pre) await catevent.delete() os.remove("out.png") os.remove(d_file_name)
def convert_code_image_base64(lexer_name, code): """Converts a code snippet to an image in base64 format.""" from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import ImageFormatter from pygments.lexers import ClassNotFound import tempfile if not lexer_name: lexer_name = 'pascal' try: lexer = get_lexer_by_name(lexer_name) except ClassNotFound: lexer = get_lexer_by_name('pascal') imgBytes = highlight(code, lexer,\ ImageFormatter(font_size=CONFIG['pygments.font_size'],\ line_numbers = CONFIG['pygments.line_numbers'])) if CONFIG['pygments.dump_image']: img_id = CONFIG['pygments.dump_image_id'] imgFile = './' + str(img_id) + '.png' with open(imgFile, 'wb') as imageOut: imageOut.write(imgBytes) img_id += 1 CONFIG['pygments.dump_image_id'] = img_id temp = tempfile.NamedTemporaryFile() temp.write(imgBytes) temp.seek(0) extension = 'png' base64_image = (base64.b64encode(temp.read())).decode('utf-8') src_part = 'data:image/' + extension + ';base64,' + base64_image temp.close() return '<img style="display:block;" src="' + src_part + '" />'
def view(paste_id): try: paste_id = int(paste_id) except: abort(404) else: user_id, user = None, None if 'user' in session: user_id = session['user']['id'] model = db_session.query(Paste).get(paste_id) if user_id: user = db_session.query(User).get(user_id) if model: model.views = model.views + 1 lexer = get_lexer_by_name(model.syntax.syntax, stripall=True) output = request.args.get('output', 'html') if output == 'html': formatter = HtmlFormatter(linenos='table', cssclass="source") d['code'] = highlight(model.content, lexer, formatter) d['model'] = model d['user'] = user return render_template('pasteapp/view.html', **d) if output == 'image': formatter = ImageFormatter(image_format='png', font_name='DejaVu Sans MONO', line_numbers=True, unicodeoutput=True) f = StringIO() highlight(model.content, lexer, formatter, outfile=f) f.seek(0) if request.args.get('attachment', 'false').lower() == 'true': return send_file(f, mimetype="image/png", as_attachment=True, attachment_filename='davidpaste_%s.png' % model.id) return send_file(f, mimetype="image/png") else: abort(404)
def make_thumb(self, code, filename, hl_line_min, hl_line_max, height_px): if filename: lx = lexers.guess_lexer_for_filename(filename, code) else: lx = lexers.guess_lexer(code) png = highlight( code, lx, ImageFormatter( style=self.style, line_pad=0, # default: 2 line_numbers=False, image_pad=5, # default: 10 hl_lines=range(hl_line_min, hl_line_max + 1), font_size=3, font_name=self.font_name)) lines = sum(1 for _ in code.splitlines()) center_pos_ratio = ((hl_line_max + hl_line_min) / 2.0) / lines cropped = crop_image(png, center_pos_ratio, height_px) return base64.encodestring(cropped)
async def fileshotcmd(self, message): """Заскринить содержимое файла .py""" await message.edit("<b>Скриню...</b>") reply = await message.get_reply_message() if not reply: await message.edit("<b>Реплай на file.py</b>") return media = reply.media if not media: await message.edit("<b>Реплай на file.py</b>") return file = await message.client.download_file(media) text = file.decode('utf-8') pygments.highlight( text, Python3Lexer(), ImageFormatter(font_name='DejaVu Sans Mono', line_numbers=True), 'fileScreenshot.png') await message.client.send_file(message.to_id, 'fileScreenshot.png', force_document=True) os.remove("fileScreenshot.png") await message.delete()
import pygments from pygments import lexers from pygments import styles from pygments.formatters import ImageFormatter, JpgImageFormatter from PIL import ImageFilter if len(sys.argv) < 2: print 'Usage:', sys.argv[0], '<filename>' sys.exit(1) text = '' with open(sys.argv[1], 'r') as f: text = f.read() text = text + ' ' * 160 + '\n' lexer = lexers.get_lexer_for_filename(sys.argv[1]) style = styles.get_style_by_name('manni') opts = { "style": style, "line_numbers": False, "font_name": "Inconsolata", "font_size": 8, } formatter = ImageFormatter(**opts) img = formatter.format(lexer.get_tokens(text), "out.png")