示例#1
0
    def compile(self, prop):
        if not os.path.exists(prop['value']):
            print("Image '{}' not found.".format(prop['value']))

        else:
            # Convert SVG to PNG
            m = re.search("\.svg$", prop['value'])
            if m:
                from wand.image import Image
                from wand.color import Color
                from wand.api import library
                dest = self.stat['icons_dir'] + "/" + prop['value'].replace(
                    '/', '_') + ".png"
                print("svg icon detected. converting '{0}' to '{1}'".format(
                    prop['value'], dest))

                with Image() as img:
                    with Color('transparent') as bg_color:
                        library.MagickSetBackgroundColor(
                            img.wand, bg_color.resource)
                    img.read(blob=open(prop['value'], 'rb').read())
                    dest_img = img.make_blob('png32')

                    with open(dest, 'wb') as out:
                        out.write(dest_img)

                return repr(dest)

        return repr(prop['value'])
示例#2
0
def rasterise(source: str, target: str):
    print("""
CONVERTING SVG at   %s
                   |   |
                   |   |
                   |   |
                   |   |
                   |   |
                 __!   !__,
                 \       / \O
                  \     / \/|
                   \   /    |
                    \ /    / \ 
                     Y   _/  _\ 
        to PNG at   %s
    """ % (source, target))

    with open(source, "r") as f:
        sourceFile = f.read().encode('utf-8')
    with wand.image.Image(blob=sourceFile, format="svg") as image:
        with wand.color.Color('transparent') as background_color:
            library.MagickSetBackgroundColor(image.wand,
                                             background_color.resource)
            png_image = image.make_blob("png32")
            with open(target, "wb") as out:
                out.write(png_image)
示例#3
0
    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
示例#4
0
def load_svg_as_image_plane(filepath, dpi):
    infile = filepath
    image_name = "".join(ntpath.basename(filepath).split(".")[:-1])
    with Image(resolution=dpi) as image:
        # Load SVG
        with Color("transparent") as background_color:
            library.MagickSetBackgroundColor(image.wand, background_color.resource)

        # Convert SVG to image
        image.read(filename=infile, resolution=dpi)

        # Import image data into Blender
        array = np.array(image)
        print(array.shape)
        print(array.dtype)

        size = array.shape[1], array.shape[0]
        bpy_image = bpy.data.images.new(image_name, width=size[0], height=size[1])
        bpy_image.pixels = array.flatten()

        # Create new empty Bmesh in which to build our new textured quad
        bm = bmesh.new()

        # add vertices and uvs before creating the new face
        # ASSUMPTION: Blender units are set to 1 unit = 1 meter (SI)
        inch_to_meter = 0.0254
        w, h = size[0] * inch_to_meter / dpi, size[1] * inch_to_meter / dpi
        vertices = [(0, 0, 0), (w, 0, 0), (w, h, 0), (0, h, 0)]
        uv_list = [(0, 1.0, 0), (1.0, 1.0, 0), (1.0, 0.0, 0), (0, 0.0, 0)]
        for vert in vertices:
            bm.verts.new((vert[0], vert[1], vert[2]))
        bm.faces.new((i for i in bm.verts))

        # add uvs to the new face
        uv_layer = bm.loops.layers.uv.verify()
        # bm.faces.layers.uv.verify()

        bm.faces.ensure_lookup_table()
        face = bm.faces[-1]
        # TODO: this here is bug
        face.material_index = 0
        for i, loop in enumerate(face.loops):
            uv = loop[uv_layer].uv
            uv[0] = uv_list[i][0]
            uv[1] = uv_list[i][1]

        # create mesh
        new_mesh = bpy.data.meshes.new(image_name)
        bm.to_mesh(new_mesh)
        bm.free()

        # make object from mesh
        new_object = bpy.data.objects.new(image_name, new_mesh)

        # assign material
        mat_id = add_material(image_name, bpy_image)
        new_object.data.materials.append(mat_id)

        # add object to scene collection
        bpy.context.scene.collection.objects.link(new_object)
def svg2png(input_path, output_path):
    with Image() as img:
        with Color('transparent') as bg_color:
            library.MagickSetBackgroundColor(img.wand, bg_color.resource)
        img.read(blob=open(input_path, 'rb').read())
        dest_img = img.make_blob('png')
        with open(output_path, 'wb') as out:
            out.write(dest_img)
示例#6
0
文件: pcbdraw.py 项目: Vman45/PcbDraw
def svg_to_png(infile, outfile, dpi=300):
    with Image(resolution=300) as image:
        with Color('transparent') as background_color:
            library.MagickSetBackgroundColor(image.wand,
                                             background_color.resource)
        image.read(filename=infile, resolution=300)
        png_image = image.make_blob("png32")
        with open(outfile, "wb") as out:
            out.write(png_image)
示例#7
0
 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)
示例#8
0
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)
示例#9
0
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)
示例#10
0
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
示例#11
0
def svg_to_bitmap(infile, outfile, dpi=300):
    with Image(resolution=dpi) as image:
        with Color('transparent') as background_color:
            library.MagickSetBackgroundColor(image.wand,
                                             background_color.resource)
        image.read(filename=infile, resolution=dpi)
        _, ext = os.path.splitext(outfile)
        if ext.lower() == ".png":
            type = "png32"
        elif ext.lower() in [".jpg", ".jpeg"]:
            type = "jpeg"
        else:
            raise RuntimeError(f"Unsupported output image type {ext}")
        bin_blob = image.make_blob(type)
        with open(outfile, "wb") as out:
            out.write(bin_blob)
示例#12
0
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
示例#13
0
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
示例#14
0
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)
示例#15
0
    def previewSVG(self):
        try:
            """drawing = svg2rlg(self.chosenFile.UTF8String())
            new_bites = io.BytesIO()
            renderPM.drawToFile(drawing,new_bites,fmt='png')"""
            with wand.image.Image() as imag:
                with wand.color.Color('transparent') as background_color:
                    library.MagickSetBackgroundColor(imag.wand,
                                                     background_color.resource)
                imag.read(filename=self.chosenFile.UTF8String())
                new_bites = io.BytesIO(imag.make_blob("png32"))

            im = Image.open(new_bites)
            im = im.crop(im.getbbox())
            im = im.resize((im.width * 3, im.height * 3))
            #im.thumbnail((133,133),Image.ANTIALIAS)
            im.save(join(expanduser("~"), ".GGD2_prev.png"), format='PNG')

            img = NSImage.alloc().initWithContentsOfFile_(
                join(expanduser("~"), ".GGD2_prev.png"))
            self.imagePreview.setImage_(img)
        except Exception, e:
            print(e)
示例#16
0
        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)
示例#17
0
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)