def convert_img(state, itype, url): if not url: return None svgpath = Path("us/img/svg") / Path(urlparse(url).path).name pngpath = Path("us/img/png") / f"{name_to_id(state)}_{itype}.png" if not svgpath.is_file(): svgblob = rq.get(url).content with svgpath.open("wb") as outfile: outfile.write(svgblob) if pngpath.is_file(): return pngpath with wand.image.Image() as image: with wand.color.Color("transparent") as background_color: wandlib.MagickSetBackgroundColor(image.wand, background_color.resource) image.read(blob=svgpath.read_bytes()) image.transform(resize="x128") with pngpath.open("wb") as outfile: outfile.write(image.make_blob("png32")) return pngpath
def sample_stroke(): [strokes, params] = model.sample(sample_args.sample_length) draw_strokes(strokes, factor=sample_args.scale_factor, svg_filename=sample_args.filename + '.normal.svg') draw_strokes_random_color(strokes, factor=sample_args.scale_factor, svg_filename=sample_args.filename + '.color.svg') draw_strokes_random_color(strokes, factor=sample_args.scale_factor, per_stroke_mode=False, svg_filename=sample_args.filename + '.multi_color.svg') draw_strokes_eos_weighted(strokes, params, factor=sample_args.scale_factor, svg_filename=sample_args.filename + '.eos_pdf.svg') draw_strokes_pdf(strokes, params, factor=sample_args.scale_factor, svg_filename=sample_args.filename + '.pdf.svg') with wand.image.Image() as image: with open(sample_args.filename + '.normal.svg', 'rb') as svg_file: image.read(blob=svg_file.read()) png_image = image.make_blob("png32") with open(sample_args.filename + '.png', "wb") as out: out.write(png_image) img = imageio.imread(sample_args.filename + '.png') return [strokes, params], img
def vd2png(self, input, output, scale): svg = self.vd2svg(input) 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, resolution=480) png_image = image.make_blob("png32") output.write(png_image)
def trans(name, src, dst): print name, os.getpid() svg_file = open(src + "\\" + name) print svg_file svg_id = name[0:len(name) - 4] with wand.image.Image() as image: with wand.color.Color('snow') as background_color: library.MagickSetBackgroundColor(image.wand, background_color.resource) image.read(blob=svg_file.read()) png_image = image.make_blob("png32") with open(dst + '\\' + svg_id + ".png", "wb") as out: out.write(png_image)
def Svg2Png(svgfile): output_filename = svgfile+'.png' input_filename = svgfile+'.svg' svg_file = open(input_filename,"r") 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_file.read()) png_image = image.make_blob("png32") with open(output_filename, "wb") as out: out.write(png_image)
def trans(name, src, dst): print name, os.getpid() svg_file = open(src + "\\" + name) print svg_file svg_id = name[0 : len(name) - 4] with wand.image.Image() as image: with wand.color.Color('snow') as background_color: library.MagickSetBackgroundColor(image.wand, background_color.resource) image.read(blob=svg_file.read()) png_image = image.make_blob("png32") with open(dst + '\\' + svg_id + ".png", "wb") as out: out.write(png_image)
def convert_image(source_dir, svg_file, img_format, width=None, height=None): """ Convert the svg to png or jpg and scale as directed """ if DEBUG: print(source_dir, svg_file, img_format, str(width), str(height)) if img_format not in IMAGE_FORMATS.keys(): return None if (width and width > MAX_DIMENSION) or (height and height > MAX_DIMENSION): return None real_width = width real_height = height image_result = None if not width or not height: try: doc = minidom.parse(os.path.join(source_dir, svg_file)) except FileNotFoundError: return None svg_width = int(round(float(re.sub("[^0-9.]", "", [path.getAttribute('width') for path in doc.getElementsByTagName('svg')][0])))) svg_height = int(round(float(re.sub("[^0-9.]", "", [path.getAttribute('height') for path in doc.getElementsByTagName('svg')][0])))) doc.unlink() if width and not height: real_height = int(round((float(width) * float(svg_height)/float(svg_width)))) elif height and not width: real_width = int(round((float(height) * float(svg_width)/float(svg_height)))) else: real_width = svg_width real_height = svg_height try: with wand.image.Image() as image: with wand.color.Color('transparent') as background_color: library.MagickSetBackgroundColor(image.wand, background_color.resource) image.read(filename=os.path.join(source_dir, svg_file)) if real_width and real_height: image.resize(real_width, real_height) image_result = image.make_blob(IMAGE_FORMATS[img_format]) except wand.exceptions.BlobError: return None return image_result
def build(self, env=None, force=None, output=None, disable_cache=None): """Build this bundle, meaning create the file given by the ``output`` attribute, applying the configured filters etc. If the bundle is a container bundle, then multiple files will be built. Unless ``force`` is given, the configured ``updater`` will be used to check whether a build is even necessary. If ``output`` is a file object, the result will be written to it rather than to the filesystem. The return value is a list of ``FileHunk`` objects, one for each bundle that was built. """ version = None output_filename = self.resolve_output(self.env, version=version) # If it doesn't exist yet, create the target directory. output_dir = path.dirname(output_filename) if not path.exists(output_dir): os.makedirs(output_dir) resolved_contents = self.resolve_contents(self.env, force=True) from wand.api import library import wand.color import wand.image with wand.image.Image() as image: with wand.color.Color('transparent') as background_color: library.MagickSetBackgroundColor(image.wand, background_color.resource) image.read(filename=resolved_contents[0][1]) png_image = image.make_blob("png32") with open(output_filename, "wb") as out: # out.write(png_image) try: proc = subprocess.Popen(["pngquant", "255"], stdin=subprocess.PIPE, stdout=out) proc.communicate(png_image) except OSError as e: raise Exception("Failed to execute pngquant: %s" % e) return [FileHunk(output_filename)]
def createPNG(name): """ Create a PNG from the generated SVG file """ try: from wand.api import library import wand.color import wand.image except: return False # Do the conversion with wand.image.Image() as image: with wand.color.Color('white') as background_color: library.MagickSetBackgroundColor(image.wand, background_color.resource) image.read(filename=name + ".svg") image.transform(resize='620x620>') png_image = image.make_blob("png32") with open(name + ".png", "wb") as out: out.write(png_image) return True
def _generate_pil(text, size='100', ec_level='L', style='default', style_color='#000000', inner_eye_style='default', inner_eye_color='#000000', outer_eye_style='default', outer_eye_color='#000000', bg_color='#FFFFFF'): generated_svg = qrsvg.generate_QR_for_text(text, size=size, ec_level=ec_level, style=style, style_color=style_color, inner_eye_style=inner_eye_style, inner_eye_color=inner_eye_color, outer_eye_style=outer_eye_style, outer_eye_color=outer_eye_color, bg_color=bg_color) converted_file = io.StringIO() #cairosvg.svg2png(bytestring=generated_svg.getvalue(), write_to=converted_file) #image = pyvips.Image.new_from_file(generated_svg.getvalue(), dpi=300) #image.write_to_file(converted_file) with wand.image.Image() as image: with wand.color.Color('transparent') as background_color: library.MagickSetBackgroundColor(image.wand, background_color.resource) image.read(blob=generated_svg.getvalue(), format="svg") png_image = image.make_blob("png32") with open(converted_file, "wb") as out: out.write(png_image) converted_file.seek(0) qr_pil = Image.open(converted_file) return qr_pil
def make_png(svg_file_path, png_file_path): svg_file = open(svg_file_path, 'r') 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_file.read(), format="svg") image.read(blob=svg_file.read(), resolution=431) # colorize image.level(white=0) with wand.image.Image() as colorImage: colorImage.read(filename='recipes/color.png') colorImage.composite_channel(channel='opacity', image=image, left=0, top=0, operator='multiply') png_image = colorImage.make_blob("png32") with open(png_file_path, "wb") as out: out.write(png_image)
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)
def create_bbox( height=200, width=200, outer_border_color="#1f6a31", inner_border_color="#299b5d", border_color="#000000", save_path=os.path.expanduser("~"), save_prefix="", ): # We have to init an empty box with stroke width 2 to start at 1, 1. boundaries = [ { "stroke_width": 1 }, { "stroke_width": 2, "color": border_color, "r": 5, "id": "outer_border" }, { "stroke_width": 4, "color": outer_border_color, "r": 3, "id": "outer_outer_border", }, { "stroke_width": 4, "color": inner_border_color, "r": 0, "id": "inner" }, { "stroke_width": 4, "color": outer_border_color, "r": 0, "id": "inner_outer_border", }, { "stroke_width": 2, "color": border_color, "r": 0, "id": "inner_border" }, ] stroke_width_sum = (sum([b["stroke_width"] for b in boundaries]) - 2) # minus the init bounding_boxes_total_size = 2 * stroke_width_sum svg_height = height + bounding_boxes_total_size svg_width = width + bounding_boxes_total_size _xml = f"""<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink= "http://www.w3.org/1999/xlink" width="{svg_width}px" height="{svg_height}px">""" h, w, x, y = svg_height, svg_width, 0, 0 rect_list = [] for idx in range(1, len(boundaries)): h, w, x, y, txt = create_inner_bbox( box_height=h, box_width=w, box_x=x, box_y=y, box_stroke_width=boundaries[idx - 1]["stroke_width"], bbox_stroke_width=boundaries[idx]["stroke_width"], bbox_color=boundaries[idx]["color"], bbox_r=boundaries[idx]["r"], xml_id=boundaries[idx]["id"], ) rect_list.append(txt) # Inner has to be first to get overlapped. # This may not work for any more than N=5 borders. # TODO: Maybe make this cleaner. inner_bd = rect_list.pop(int(math.ceil(len(rect_list) / 2))) _xml += (inner_bd + "\n" + "\n".join(rect_list)) + "</svg>" file_name = ( f"{height}h_{width}w_{outer_border_color[1:]}out_{inner_border_color[1:]}in.svg" ) if save_prefix: file_name = save_prefix + "_" + file_name file_loc = os.path.join(save_path, file_name) new_file_loc = os.path.splitext(file_loc)[0] + ".png" with open(file_loc, "w+") as f: f.write(_xml) # Render pngs. with open(file_loc, "r") as svg_file: with wand.image.Image() as image: with wand.color.Color("transparent") as background_color: library.MagickSetBackgroundColor(image.wand, background_color.resource) svg_blob = svg_file.read().encode("utf-8") image.read(blob=svg_blob) png_image = image.make_blob("png32") with open(new_file_loc, "wb") as out: out.write(png_image)
width = '500' height = 'x500' heights = [] # List svg files folder = 'wiki_flags/' svg_files = os.listdir(folder) for file in svg_files: svg_file = open(folder + file, "rb") future_name = file.replace('.svg', '.png') future_name = future_name.replace('flag-', '') try: with wand.image.Image() as image: with wand.color.Color('white') as background_color: library.MagickSetBackgroundColor(image.wand, background_color.resource) image.read(blob=svg_file.read()) image.transform(resize=str(height)) heights.append(image.height) png_image = image.make_blob("png32") with open(folder_png + future_name, "wb") as out: out.write(png_image) except : print('Problem with: ' + future_name) print(heights)
</svg> """ from wand.api import library import wand.color import wand.image from PIL import Image name = 'chelsea' file_object = open(name + '.svg', 'r') with wand.image.Image() as image: with wand.color.Color('transparent') as background_color: library.MagickSetBackgroundColor(image.wand, background_color.resource) image.read(blob=file_object.read()) png_image = image.make_blob("png32") with open(name + '.png', "wb") as out: out.write(png_image) img = Image.open(name + '.png').convert('LA') img.save('greyscale.png') im = Image.open(name + '.png') foreground = Image.open('greyscale.png') bg = Image.new("RGB", im.size, (255,255,255)) bg.paste(im, (0, 0), im) bg.save("test.png")
# encoding: utf-8 import os from wand.api import library import wand.color import wand.image base_dir = '/Users/gree2/Downloads/glyph-iconset-master/svg/' file_n = 'si-glyph-abacus.svg' file_i = os.path.join(base_dir, file_n) file_o = os.path.join(base_dir, file_i.replace('.svg', '.png')) with wand.image.Image() as image: with wand.color.Color('transparent') as background_color: library.MagickSetBackgroundColor(image.wand, background_color.resource) with open(file_i) as svg_file: image.read(filename=file_i) # image.read(blob=svg_file.read(), format="svg") image.resize(1024, 1024) png_image = image.make_blob("png32") with open(file_o, "wb") as out: out.write(png_image)
import numpy import xml.etree.ElementTree as ET # TODO make these command line parameters input = "besieged-theme.svg" output = "besieged-theme.png" theme_file = "besieged-theme.txt" # Texture Generation with open(input, "rb") as svg_file: 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_file.read(), format="svg") png_image = image.make_blob("png32") root = ET.fromstring(png_image.decode("utf-8")) image = list(root.iterfind("{http://www.w3.org/2000/svg}image")) raw_data = image[0].get("href").replace("data:image/png;base64,", "") with open(output, "wb") as out: out.write(base64.b64decode(raw_data)) # Theme Generation # TODO support other types of SVG element transformations. # They should likely all produce a matrix, to make the calculation part consistent.