在 python 中升级 SVG 图像而不损失其质量

Upscale an SVG image in python without losing its quality

我有一个 svg 格式的图像,高度和宽度为 45 我想将它放大到 75 是否可以在 pygame 中不损失质量。

调整大小前的图片:

调整后的图片:

我用来调整大小的代码:

pygame.transform.scale(pygame.image.load('bP.svg'),(75,75))

这应该有助于升级,因为它使用双线性滤波器:

pygame.transform.smoothscale(pygame.image.load('bP.svg'),(75,75))

Scalable Vector Graphics is a text format. You can edit the SVG file and add a global scale (see SVG/Transformationen) 的格式。例如:

<svg
    transform="scale(2)"
    ...
>

从 2.0.2 开始,SDL Image 支持 SVG 文件(参见 SDL_image 2.0). Therefore with pygame version 2.0.1, pygame.image.load() 支持 SVG 文件。
pygame.Surface 中渲染可缩放矢量图形时必须进行缩放。在 pygame.image.load() 中有一个 scalesize 参数会很好。然而,类似这样的事情还没有记录在案。


解决方法是加载 SVG 文本并添加缩放比例 (transform="scale(2)")。可以使用 io module. Finally, this buffered and scaled SVG can be loaded with pygame.image.laod:

将字符串加载到二进制 I/O 缓冲区中
import io

def load_and_scale_svg(filename, scale):
    svg_string = open(filename, "rt").read()
    start = svg_string.find('<svg')    
    if start > 0:
        svg_string = svg_string[:start+4] + f' transform="scale({scale})"' + svg_string[start+4:]
    return pygame.image.load(io.BytesIO(svg_string.encode()))

bP_surface = load_and_scale_svg('bP.svg', 2)

最小示例:

import pygame
import io

def load_and_scale_svg(filename, scale):
    svg_string = open(filename, "rt").read()
    start = svg_string.find('<svg')    
    if start > 0:
        svg_string = svg_string[:start+4] + f' transform="scale({scale})"' + svg_string[start+4:]
    return pygame.image.load(io.BytesIO(svg_string.encode()))

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

pygame_surface = load_and_scale_svg('Ice.svg', 0.4)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.fill((127, 127, 127))
    window.blit(pygame_surface, pygame_surface.get_rect(center = window.get_rect().center))
    pygame.display.flip()

pygame.quit()
exit()