PYGAME - image convert

图像转换

为了是pygame高效的使用图片需要调用convert()进行转换.

Pygame.image.load().convert() --- 像素格式的转换(不是surface对象的转换)

在每次blit的时候(图片盖在另一图片上)的时候python会自动强制进行像素格式转换,效率低不如先转换

Pygame.image.convert_alpha(200) --- 包含透明的需要使用alpha解析,jpg不支持透明,通常用png和gif,转换后的图片只能用pixal alpha修改

Pygame 三种透明方式:set_colorkey(#RGB) / set_alpha(200 整体做alpha) / pixal alpha(每个像素都有alpha通道)

import pygame
import sys
from pygame.locals import *

pygame.init()
size = width, height = 1000, 800
bg = (0, 0, 0)

screen = pygame.display.set_mode(size)
pygame.display.set_caption('Color Convert Test')
clock = pygame.time.Clock()

minions = pygame.image.load('minions.jpg').convert_alpha()
bg_pic = pygame.image.load('bg.jpg').convert()
position = minions.get_rect()
position.center = width//2, height//2

# method1 - setcolorkey
#minions.set_colorkey((255,255,255))
# method2 - set_alpha(0-200) for opacity
#minions.set_alpha(200)

# method3 - set_at for pixl alpha
'''
for i in range(position.width):
    for j in range(position.height):
        temp = minions.get_at((i, j))
        if temp[3] != 0:
            temp[3] = 200
        minions.set_at((i, j), temp)
'''
# method4 - build a transparent screen with pic and then paste back to target screen
def blit_opac(target, source, location, opacity):
    x = location[0]
    y = location[1]
    temp = pygame.Surface((source.get_width(), source.get_height())).convert()
    temp.blit(target, (-x, -y))
    temp.blit(source, (0, 0))
    temp.set_alpha(opacity)
    target.blit(temp, position)

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

    screen.blit(bg_pic, (0,0))
    #screen.blit(minions, position)
    blit_opac(screen, minions, position, 200)

    pygame.display.flip()
    clock.tick(30)

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值