簡體   English   中英

縮放時PIL圖像到Pygame圖像錯誤

[英]PIL image to Pygame image error when scaling

所以我有一張圖片(16x16):

image = Image.open("image.png")

我將其轉換為 pygame 圖像:

mode = image.mode
data = image.tobytes()
py_image = pygame.image.fromstring(data, (64, 64), mode)

它給了我這個錯誤:

ValueError: String length does not equal format and resolution size

問題是fromstring()沒有做你認為它做的事情,它沒有縮放圖像。 它只能將數據流源化為原始數據流大小。 因此,如果您輸入16x16像素的數據,那么fromstring()將需要從字符串/字節 stream 創建圖像的大小。

這就是 function 旨在 function 的方式:

from PIL import Image
print(Image.open("test.png"))

它應該給你:

<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=64x64 at 0x2FCB6B8>

尺寸和模式很重要。 您還應該將其用作fromstring()的輸入向量,因為大小可能會改變。

以下對我來說非常好:

from PIL import Image
import pygame

pygame.init()

gameDisplay = pygame.display.set_mode((800, 600))

image = Image.open("test.png")
mode = image.mode
data = image.tobytes('raw', mode)
py_image = pygame.image.fromstring(data, image.size, mode)

exit = False
while not exit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit = True

    gameDisplay.fill((255, 255, 255))
    gameDisplay.blit(py_image, (10, 10))

    pygame.display.update()

pygame.quit()

並產生:

在此處輸入圖像描述


如果要將小圖像轉換為更大的圖像。 您首先需要創建一個空白模板,您可以在其中讀取數據。 在這里,我將創建一個64x64像素的空白(白色)圖像,並將較小的16x16圖像移植/合並到 position 0, 0處的較大圖像中。

source = Image.open("test.png")
canvas = Image.new('RGB', (64,64), (255, 255, 255))
canvas.paste(source, (0, 0))

然后,您可以繼續照常使用圖像。 盡管如此,這不會擴展它,它只會給你一個更大的 canvas 來使用。 如果要縮放圖像,則應使用pygame.transform.scalePIL 縮放圖像。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM