【问题标题】:Upscale an SVG image in python without losing its quality在 python 中放大 SVG 图像而不损失其质量
【发布时间】:2021-11-29 04:26:27
【问题描述】:

我有一个 svg 格式的图像,高度和宽度为 45,我想将其放大到 75,是否可以在不损失 pygame 质量的情况下做到这一点。

调整大小前的图片:

调整大小后的图像:

我用来调整大小的代码:

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

【问题讨论】:

  • @Rabbid76 在这种情况下,源是 SVG 格式,即矢量。如果您在转换为光栅之前调整它的大小,它应该是完美的。
  • @Mark Ransom,我该怎么做?
  • 不确定,我以前从未在 Python 中使用过 SVG。
  • 使用 pygame.image.load 对我有用
  • @JohanJomy 我明白了。这似乎是一个新的但未记录的功能。

标签: python image svg pygame resize


【解决方案1】:

这应该有助于放大,因为它使用双线性过滤器:

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

【讨论】:

  • 不是最好但比以前更好
【解决方案2】:

Scalable Vector Graphics 的格式是文本格式。您可以编辑 SVG 文件并添加全局比例(请参阅SVG/Transformationen)。例如:

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

自 2.0.2 起,SDL Image 支持 SVG 文件(请参阅 SDL_image 2.0)。因此,对于 pygame 2.0.1 版,pygame.image.load() 支持 SVG 文件。
当 Scalable Vector Graphic 在 pygame.Surface 中呈现时,必须进行缩放。在pygame.image.load() 中有一个scalesize 参数会很好。然而,这样的事情还没有记录在案。


解决方法是加载 SVG 文本并添加缩放 (transform="scale(2)")。可以使用io module 将字符串加载到二进制 I/O 缓冲区中。最后,这个缓冲和缩放的 SVG 可以用pygame.image.laod 加载:

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 2015-03-04
    • 2013-10-18
    • 1970-01-01
    • 2017-11-27
    • 2014-03-22
    • 1970-01-01
    相关资源
    最近更新 更多