Python pygame 模块,image() 实例源码
我们从Python开源项目中,提取了以下36个代码示例,用于说明如何使用pygame.image()。
def test_save_colorkey(self):
""" make sure the color key is not changed when saving.
"""
s = pygame.Surface((10,10), pygame.SRCALPHA, 32)
s.fill((23,23,23))
s.set_colorkey((0,0,0))
colorkey1 = s.get_colorkey()
p1 = s.get_at((0,0))
temp_filename = "tmpimg.png"
try:
pygame.image.save(s, temp_filename)
s2 = pygame.image.load(temp_filename)
finally:
os.remove(temp_filename)
colorkey2 = s.get_colorkey()
# check that the pixel and the colorkey is correct.
self.assertEqual(colorkey1, colorkey2)
self.assertEqual(p1, s2.get_at((0,0)))
def todo_test_frombuffer(self):
# __doc__ (as of 2008-08-02) for pygame.image.frombuffer:
# pygame.image.frombuffer(string,size,format): return Surface
# create a new Surface that shares data inside a string buffer
#
# Create a new Surface that shares pixel data directly from the string
# buffer. This method takes the same arguments as
# pygame.image.fromstring(),but is unable to vertically flip the
# source data.
#
# This will run much faster than pygame.image.fromstring,since no
# pixel data must be allocated and copied.
self.fail()
def update(self):
from datetime import datetime, timedelta
import pygame.image
while self.on:
start = datetime.Now()
if self.cam.query_image():
# snapshot = self.cam.get_image()
# self.frame = list(pygame.image.tostring(snapshot,"RGB",False))
snapshot = self.cam.get_image()
snapshot1 = pygame.transform.scale(snapshot, self.resolution)
self.frame = pygame.surfarray.pixels3d(pygame.transform.rotate(pygame.transform.flip(snapshot1, True, False), 90))
stop = datetime.Now()
s = 1 / self.framerate - (stop - start).total_seconds()
if s > 0:
time.sleep(s)
self.cam.stop()
def __init__(self, path_mask='~/d2/data/**/*.jpg'):
self.image_filenames = glob.glob(os.path.expanduser(path_mask), recursive=True)
def get_image_index(fnm):
sl = os.path.basename(fnm).split('_')
return int(sl[0])
'''
I feel like sorting by modified time is almost always
what you want. but if you tared and moved your data around,
sometimes it doesn't preserve a nice modified time.
so,sorting by image index works better,but only with one path.
'''
self.image_filenames.sort(key=get_image_index)
#self.image_filenames.sort(key=os.path.getmtime)
self.num_images = len(self.image_filenames)
print('%d images loaded.' % self.num_images)
print( self.image_filenames[:10])
self.i_frame = 0
self.frame = None
self.update()
def loadFromrpkg(self, path):
"""
Laden des Raums
Parameter: str Dateiname/Pfad des zuladenen Raums
Rückgabewerte: -
"""
try:
room = Pickle.load(open(path, "rb"))
except Exception as e:
print e
self.name = room[0]
self.col = room[1]
self.bg = pygame.image.fromstring(room[2], room[3], "RGB")
self.equippables = room[4]
self.doors = room[5]
def __init__(self):
self.coor = [0, 0]
self.direction = [0, 1]
self.img = pygame.image.load('res/robot.png')
self.img = pygame.transform.scale(
self.img, (2 * Maze.GRID_LEN, 2 * Maze.GRID_LEN))
self.loop = 0
self.moves = 0
self.movetime = 1
self.numExplored = 0
self.mark_explored()
self.short_path_cmd = [-1]
self.prev = False
self.stage = 0
self.uncalibrateMove = 0
self.is_goal_reach=0
def __init__(self):
self.coor = [0, 2 * Maze.GRID_LEN))
self.loop = 0
self.moves = 0
self.movetime = 1
self.numExplored = 0
# comm=Com()
self.mark_explored()
self.short_path_cmd = [-1]
self.prev = False
self.stage = 0
self.uncalibrateMove = 0
self.actions=[]
self.is_goal_reach=0
def testLoadIcon(self):
""" see if we can load the pygame icon.
"""
f = pygame.pkgdata.getResource("pygame_icon.bmp")
self.assertEqual(f.mode, "rb")
surf = pygame.image.load_basic(f)
self.assertEqual(surf.get_at((0,0)),(5, 4, 5, 255))
self.assertEqual(surf.get_height(),32)
self.assertEqual(surf.get_width(),32)
def testLoadJPG(self):
""" see if we can load a jpg.
"""
f = example_path('data/alien1.jpg') # normalized
# f = os.path.join("examples","data","alien1.jpg")
surf = pygame.image.load(f)
f = open(f, "rb")
# f = open(os.path.join("examples","alien1.jpg"),"rb")
surf = pygame.image.load(f)
# surf = pygame.image.load(open(os.path.join("examples","rb"))
def testSavePNG32(self):
""" see if we can save a png with color values in the proper channels.
"""
# Create a PNG file with kNown colors
reddish_pixel = (215, 0, 255)
greenish_pixel = (0, 225, 255)
bluish_pixel = (0, 235, 255)
greyish_pixel = (115, 125, 135, 145)
surf = pygame.Surface((1, 4), 32)
surf.set_at((0, 0), reddish_pixel)
surf.set_at((0, 1), greenish_pixel)
surf.set_at((0, 2), bluish_pixel)
surf.set_at((0, 3), greyish_pixel)
f_path = tempfile.mktemp(suffix='.png')
pygame.image.save(surf, f_path)
# Read the PNG file and verify that pygame saved it correctly
width, height, pixels, Metadata = png.Reader(filename=f_path).asRGBA8()
pixels_as_tuples = []
for pixel in pixels:
pixels_as_tuples.append(tuple(pixel))
self.assertEquals(pixels_as_tuples[0], reddish_pixel)
self.assertEquals(pixels_as_tuples[1], greenish_pixel)
self.assertEquals(pixels_as_tuples[2], bluish_pixel)
self.assertEquals(pixels_as_tuples[3], greyish_pixel)
os.remove(f_path)
def test_save(self):
s = pygame.Surface((10,10))
s.fill((23,23))
magic_hex = {}
magic_hex['jpg'] = [0xff, 0xd8, 0xff, 0xe0]
magic_hex['png'] = [0x89 ,0x50 ,0x4e ,0x47]
magic_hex['tga'] = [0x0, 0x0, 0xa]
magic_hex['bmp'] = [0x42, 0x4d]
formats = ["jpg", "png", "tga", "bmp"]
# uppercase too... JPG
formats = formats + [x.upper() for x in formats]
for fmt in formats:
try:
temp_filename = "%s.%s" % ("tmpimg", fmt)
pygame.image.save(s, temp_filename)
# test the magic numbers at the start of the file to ensure they are saved
# as the correct file type.
self.assertEqual((1, fmt), (test_magic(open(temp_filename, "rb"), magic_hex[fmt.lower()]), fmt))
# load the file to make sure it was saved correctly.
# Note load can load a jpg saved with a .png file name.
s2 = pygame.image.load(temp_filename)
#compare contents,might only work reliably for png...
# but because it's all one color it seems to work with jpg.
self.assertEquals(s2.get_at((0, s.get_at((0,0)))
finally:
#clean up the temp file,comment out to leave tmp file after run.
os.remove(temp_filename)
pass
def test_to_string__premultiplied(self):
""" test to make sure we can export a surface to a premultiplied alpha string
"""
def convertRGBAtoPremultiplied(surface_to_modify):
for x in xrange_(surface_to_modify.get_width()):
for y in xrange_(surface_to_modify.get_height()):
color = surface_to_modify.get_at((x, y))
premult_color = (color[0]*color[3]/255,
color[1]*color[3]/255,
color[2]*color[3]/255,
color[3])
surface_to_modify.set_at((x, y), premult_color)
test_surface = pygame.Surface((256, 256), 32)
for x in xrange_(test_surface.get_width()):
for y in xrange_(test_surface.get_height()):
i = x + y*test_surface.get_width()
test_surface.set_at((x,y), ((i*7) % 256, (i*13) % 256, (i*27) % 256, y))
premultiplied_copy = test_surface.copy()
convertRGBAtoPremultiplied(premultiplied_copy)
self.assertPremultipliedAreEqual(pygame.image.tostring(test_surface, "RGBA_PREMULT"),
pygame.image.tostring(premultiplied_copy, "RGBA"),
pygame.image.tostring(test_surface, "RGBA"))
self.assertPremultipliedAreEqual(pygame.image.tostring(test_surface, "ARGB_PREMULT"), "ARGB"), "ARGB"))
no_alpha_surface = pygame.Surface((256, 24)
self.assertRaises(ValueError, pygame.image.tostring, no_alpha_surface, "RGBA_PREMULT")
def todo_test_get_extended(self):
# __doc__ (as of 2008-08-02) for pygame.image.get_extended:
# pygame.image.get_extended(): return bool
# test if extended image formats can be loaded
#
# If pygame is built with extended image formats this function will
# return True. It is still not possible to determine which formats
# will be available,but generally you will be able to load them all.
self.fail()
def todo_test_load_extended(self):
# __doc__ (as of 2008-08-02) for pygame.image.load_extended:
# pygame module for image transfer
self.fail()
def todo_test_save_extended(self):
# __doc__ (as of 2008-08-02) for pygame.image.save_extended:
# pygame module for image transfer
self.fail()
def draw_background(imgName):
bg_image = pygame.image.load(imgName).convert()
bg_data = pygame.image.tostring(bg_image, 'RGBX', 1)
width, height = bg_image.get_size()
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glEnable(GL_TEXTURE_2D)
glGT = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, glGT)
glTexImage2D(GL_TEXTURE_2D, GL_RGBA, width, GL_UNSIGNED_BYTE, bg_data)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glBegin(GL_QUADS)
glTexCoord2f(0.0,0.0); glVertex3f(-1.0,-1.0,-1.0)
glTexCoord2f(1.0,0.0); glVertex3f( 1.0,1.0); glVertex3f( 1.0, 1.0,-1.0)
glTexCoord2f(0.0,1.0); glVertex3f(-1.0,-1.0)
glEnd()
glDeleteTextures(1)
return glGT
def __init__(self, resolution=(160, 120), image=None):
if image is not None:
self.frame = image
else:
self.frame = Image.new('RGB', resolution)
def checkdependencies():
"only returns if everything looks ok"
msgs = []
#make sure this looks like the right directory
if not os.path.isdir(CODEDIR):
msgs.append('Cannot locate SolarWolf modules')
if not os.path.isdir('data'):
msgs.append('Cannot locate SolarWolf data files')
#first,we need python >= 2.1
if int(sys.version[0]) < 2:
errorBox('Requires Python-2.1 or Greater')
#is correct pygame found?
try:
import pygame
if pygame.ver < '1.5.6':
msgs.append('Requires Pygame-1.5.6 or Greater,You Have ' + pygame.ver)
except ImportError:
msgs.append("Cannot import Pygame,install version 1.5.6 or higher")
pygame = None
#check that we have FONT and IMAGE
if pygame:
if not pygame.font:
msgs.append('Pygame requires the SDL_ttf library,not available')
if not pygame.image or not pygame.image.get_extended():
msgs.append('Pygame requires the SDL_image library,not available')
if msgs:
msg = '\n'.join(msgs)
errorBox(msg)
#Pretty Error Handling Code...
def load_raw(name):
file = game.get_resource(name)
img = pygame.image.load(file)
return img
def testLoadIcon(self):
""" see if we can load the pygame icon.
"""
f = pygame.pkgdata.getResource("pygame_icon.bmp")
self.assertEqual(f.mode,32)
def test_save(self):
s = pygame.Surface((10,comment out to leave tmp file after run.
os.remove(temp_filename)
pass
def test_to_string__premultiplied(self):
""" test to make sure we can export a surface to a premultiplied alpha string
"""
def convertRGBAtoPremultiplied(surface_to_modify):
for x in xrange_(surface_to_modify.get_width()):
for y in xrange_(surface_to_modify.get_height()):
color = surface_to_modify.get_at((x, "RGBA_PREMULT")
def todo_test_get_extended(self):
# __doc__ (as of 2008-08-02) for pygame.image.get_extended:
# pygame.image.get_extended(): return bool
# test if extended image formats can be loaded
#
# If pygame is built with extended image formats this function will
# return True. It is still not possible to determine which formats
# will be available,but generally you will be able to load them all.
self.fail()
def todo_test_load_basic(self):
# __doc__ (as of 2008-08-02) for pygame.image.load_basic:
# pygame.image.load(filename): return Surface
# pygame.image.load(fileobj,namehint=): return Surface
# load new image from a file
self.fail()
def todo_test_load_extended(self):
# __doc__ (as of 2008-08-02) for pygame.image.load_extended:
# pygame module for image transfer
self.fail()
def todo_test_save_extended(self):
# __doc__ (as of 2008-08-02) for pygame.image.save_extended:
# pygame module for image transfer
self.fail()
def savetoRpkg(self):
"""
Speichern des Raums
Parameter: -
Rückgabewerte: -
"""
print type(self.bg)
room = (self.name, self.col, pygame.image.tostring(self.bg, "RGB"), self.bg.get_size(), self.equippables, self.doors)
#room = (self.name,self.col,"placeholder",self.equippables,self.doors)
try:
Pickle.dump(room, open(self.name + ".rpkg", "wb"), 2)
except Exception as e:
print e
def random_bytes(self, min_bytes=1):
generated_bytes = []
self.cam.start()
while len(generated_bytes) < min_bytes:
raw = self._get_image_raw(ensure_fresh=True) # each subsequent image must be different
chunk_size = self.chunk_size
extracted_bytes = self._extract_randomness_sha(raw, chunk_size)
generated_bytes.extend(extracted_bytes)
self.cam.stop()
return generated_bytes
def load_image(path, transparent):
path = os.path.join(main_dir, path)
if not pygame.image:
return None
try:
data = pygame.image.load(path)
except pygame.error:
print("Couldn't load image file " + path+ " " + pygame.get_error())
if transparent:
corner = data.get_at((0,0))
data.set_colorkey(corner, RLEACCEL)
return data.convert()
def testLoadpnG(self):
""" see if we can load a png with color values in the proper channels.
"""
# Create a PNG file with kNown colors
reddish_pixel = (210, 220, 230, 255)
greyish_pixel = (110, 120, 130, 140)
pixel_array = [reddish_pixel + greenish_pixel,
bluish_pixel + greyish_pixel]
f_descriptor, f_path = tempfile.mkstemp(suffix='.png')
f = os.fdopen(f_descriptor, 'wb')
w = png.Writer(2, 2, alpha=True)
w.write(f, pixel_array)
f.close()
# Read the PNG file and verify that pygame interprets it correctly
surf = pygame.image.load(f_path)
pixel_x0_y0 = surf.get_at((0, 0))
pixel_x1_y0 = surf.get_at((1, 0))
pixel_x0_y1 = surf.get_at((0, 1))
pixel_x1_y1 = surf.get_at((1, 1))
self.assertEquals(pixel_x0_y0, reddish_pixel)
self.assertEquals(pixel_x1_y0, greenish_pixel)
self.assertEquals(pixel_x0_y1, bluish_pixel)
self.assertEquals(pixel_x1_y1, greyish_pixel)
# Read the PNG file obj. and verify that pygame interprets it correctly
f = open(f_path, 'rb')
surf = pygame.image.load(f)
f.close()
pixel_x0_y0 = surf.get_at((0, greyish_pixel)
os.remove(f_path)
def testSaveJPG(self):
""" JPG equivalent to issue #211 - color channel swapping
Make sure the SDL surface color masks represent the rgb memory format
required by the JPG library. The masks are machine endian dependent
"""
from pygame import Color, Rect
# The source image is a 2 by 2 square of four colors. Since JPEG is
# lossy,there can be color bleed. Make each color square 16 by 16,
# to avoid the significantly color value distorts found at color
# boundaries due to the compression value set by Pygame.
square_len = 16
sz = 2 * square_len, 2 * square_len
# +---------------------------------+
# | red | green |
# |----------------+----------------|
# | blue | (255,128,64) |
# +---------------------------------+
#
# as (rect,color) pairs.
def as_rect(square_x, square_y):
return Rect(square_x * square_len, square_y * square_len,
square_len, square_len)
squares = [(as_rect(0, Color("red")),
(as_rect(1, Color("green")),
(as_rect(0, Color("blue")), Color(255, 128, 64))]
# A surface format which is not directly usable with libjpeg.
surf = pygame.Surface(sz, 32)
for rect, color in squares:
surf.fill(color, rect)
# Assume pygame.image.Load works correctly as it is handled by the
# third party SDL_image library.
f_path = tempfile.mktemp(suffix='.jpg')
pygame.image.save(surf, f_path)
jpg_surf = pygame.image.load(f_path)
# Allow for small differences in the restored colors.
def approx(c):
mask = 0xFC
return pygame.Color(c.r & mask, c.g & mask, c.b & mask)
offset = square_len // 2
for rect, color in squares:
posn = rect.move((offset, offset)).topleft
self.assertEqual(approx(jpg_surf.get_at(posn)), approx(color))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。