コード例 #1
0
ファイル: gl.py プロジェクト: lxnt/fgtestbed
 def __init__(self, w = None, h = None, data_ptr = None, surface = None,
                 filename = None, filedata = None):
     self.do_free = True
     if filedata is not None:
         if type(filedata) is bytes:
             imagedata = bytearray(filedata)
         if type(filedata) is bytearray:
             rwops = sdlrwops.rw_from_mem(bar2voidp(filedata).value, len(filedata))
         elif hasattr(filedata, "seek"):
             rwops = sdlrwops.rw_from_object(filedata)
         else:
             raise TypeError("unusable data type {}", str(type(filedata)))
         self._surf = sdlimage.load_rw(rwops, 1)
     elif isinstance(filename, str):
         self._surf = sdlimage.load(filename)
     elif isinstance(w, int) and isinstance(h, int):
         masks = list(sdlpixels.pixelformat_enum_to_masks(self.sdl_pixel_fmt))
         bpp = masks.pop(0)
         if data_ptr is None:
             self._surf = sdlsurface.create_rgb_surface(w, h, bpp, *masks)
         else: # data_ptr == ABGR8888
             self._surf = sdlsurface.create_rgb_surface_from(data_ptr, w, h, bpp, w*4, *masks)
     elif isinstance(surface, SDL_Surface):
         self.do_free = False
         self._surf = surface
     else:
         raise TypeError("Crazy shit in parameters: ({} {} {} {} {})".format(type(w),
                 type(h), type(data_ptr), type(surface), type(filename)))
         
     sdlsurface.set_surface_blend_mode(self._surf, sdlvideo.SDL_BLENDMODE_NONE)
コード例 #2
0
ファイル: sdlimage_test.py プロジェクト: gdos/pgreloaded
 def test_load(self):
     fname = "surfacetest.%s"
     for fmt in formats:
         filename = RESOURCES.get_path(fname % fmt)
         sf = sdlimage.load(filename)
         self.assertIsInstance(sf, surface.SDL_Surface)
         surface.free_surface(sf)
     self.assertRaises(sdl.SDLError, sdlimage.load, RESOURCES.get_path("rwopstest.txt"))
     self.assertRaises(sdl.SDLError, sdlimage.load, None)
     self.assertRaises(sdl.SDLError, sdlimage.load, 1234)
コード例 #3
0
ファイル: surface_blit.py プロジェクト: gdos/pgreloaded.sdl12
def run ():
    blittypes = [ blit_solid, blit_min, blit_max, blit_add, blit_sub,
                  blit_mult, blit_and, blit_or, blit_xor, blit_diff,
                  blit_screen, blit_avg,
                  blit_rgba, blit_rgba_min, blit_rgba_max, blit_rgba_add,
                  blit_rgba_sub, blit_rgba_mult, blit_rgba_and, blit_rgba_or,
                  blit_rgba_xor, blit_rgba_diff, blit_rgba_screen,
                  blit_rgba_avg ]
    curtype = 0
    video.init ()
    screen = video.set_mode (640, 480, 32)
    color = white
    imgdir = os.path.dirname (os.path.abspath (__file__))
    logo = None
    if hassdlimage:
        logo = image.load (pygame2.examples.RESOURCES.get ("logo.gif"))
    else:
        logo = image.load_bmp (pygame2.examples.RESOURCES.get ("logo.bmp"))
    
    screen.fill (color)
    screen.blit (logo, (-10, 140))
    blit_solid (screen)
    screen.flip ()

    okay = True
    while okay:
        for ev in event.get ():
            if ev.type == sdlconst.QUIT:
                okay = False
            if ev.type == sdlconst.KEYDOWN and ev.key == sdlconst.K_ESCAPE:
                okay = False
            if ev.type == sdlconst.MOUSEBUTTONDOWN:
                curtype += 1
                if curtype >= len (blittypes):
                    curtype = 0
                    if color == black:
                        color = white
                    else:
                        color = black

                screen.fill (color)
                screen.blit (logo, (-10, 140))
                blittypes[curtype] (screen)
                screen.flip ()
    video.quit ()
コード例 #4
0
ファイル: hello_world.py プロジェクト: gdos/pgreloaded.sdl12
def run():
    video.init()

    surface = None
    if hassdlimage:
        surface = image.load(pygame2.examples.RESOURCES.get("logo.gif"))
    else:
        surface = image.load_bmp(pygame2.examples.RESOURCES.get("logo.bmp"))

    screen = video.set_mode(surface.w + 10, surface.h + 10)
    screen.fill(pygame2.Color(255, 255, 255))
    screen.blit(surface, (5, 5))
    screen.flip()

    okay = True
    while okay:
        for ev in event.get():
            if ev.type == constants.QUIT:
                okay = False
            if ev.type == constants.KEYDOWN and ev.key == constants.K_ESCAPE:
                okay = False
    video.quit()
コード例 #5
0
    def test_pygame2_sdl_video_Surface_save(self):

        # __doc__ (as of 2009-05-15) for pygame2.sdl.video.Surface.save:

        # save (file[, type]) -> None
        # 
        # Saves the Surface to a file.
        # 
        # Saves the Surface to a file. The file argument can be either a
        # file name or a file-like object to save the Surface to. The
        # optional type argument is required, if the file type cannot be
        # determined by the suffix.
        # 
        # Currently supported file types (suitable to pass as string for
        # the type argument) are:
        # 
        # * BMP
        # * TGA
        # * PNG
        # * JPEG (JPG)
        # 
        # If no type information is supplied and the file type cannot be
        # determined either, it will use TGA.
        modes = [32, 24, 16, 8]
        for bpp in modes:
            sf1 = video.Surface (16, 16, bpp)
            if bpp == 8:
                sf1.set_palette (CGAPALETTE)
            sf1.fill (pygame2.Color ("red"))
            bufcreat = None
            if sys.version_info[0] >= 3:
                bufcreat = stringio.BytesIO
            else:
                bufcreat = stringio.StringIO
            buf = bufcreat ()
        
            sf1.save (buf, "bmp")
            buf.seek (0)
            sf2 = image.load_bmp (buf).convert (sf1.format)
            self.assertEqual (sf1.size, sf2.size)
            self._cmppixels (sf1, sf2)
        
            buf.seek (0)
            sf2 = sdlimage.load (buf, "bmp").convert (sf1.format)
            self.assertEqual (sf1.size, sf2.size)
            self._cmppixels (sf1, sf2)

            buf = bufcreat ()
            sf1.save (buf, "jpg")
            buf.seek (0)
            sf2 = sdlimage.load (buf, "jpg").convert (sf1.format)
            self.assertEqual (sf1.size, sf2.size)

            buf = bufcreat ()
            sf1.save (buf, "png")
            buf.seek (0)
            sf2 = sdlimage.load (buf, "png").convert (sf1.format)
            self.assertEqual (sf1.size, sf2.size)
            self._cmppixels (sf1, sf2)

            buf = bufcreat ()
            sf1.save (buf, "tga")
            buf.seek (0)
            sf2 = sdlimage.load (buf, "tga").convert (sf1.format)
            self.assertEqual (sf1.size, sf2.size)
            self._cmppixels (sf1, sf2)
コード例 #6
0
ファイル: image.py プロジェクト: gdos/pgreloaded
def load_image(fname, enforce=None):
    """Creates a SDL_Surface from an image file.

    If assurface is True, a SDL_Surface will be returned instead of a
    Sprite or SoftSprite object. If renderer is set to a SDL_Renderer, a
    Sprite will be returned.

    This function makes use of the Python Imaging Library, if it is available
    on the target execution environment. The function will try to load the
    file via pygame2.sdlimage first. If the file could not be loaded, it will
    try to load it via PIL.

    You can force the function to use only one of them, by passing the enforce
    as either "PIL" or "SDL".

    Note: This will call pygame2.sdlimage.init() implicitly with the
    default arguments, if the module is available.
    """
    if enforce is not None and enforce not in ("PIL", "SDL"):
        raise ValueError("enforce must be either 'PIL' or 'SDL', if set")

    if enforce == "PIL" and not _HASPIL:
        raise UnsupportedError("PIL loading")
    if enforce == "SDL" and not _HASSDLIMAGE:
        raise UnsupportedError("SDL loading")

    surface = None
    if enforce != "PIL" and _HASSDLIMAGE:
        try:
            sdlimage.init()
            surface = sdlimage.load(fname)
        except:
            # An error occured - if we do not try PIL, break out now
            if not _HASPIL or enforce == "SDL":
                raise

    if enforce != "SDL" and _HASPIL and surface is None:
        image = Image.open(fname)
        mode = image.mode
        width, height = image.size
        rmask = gmask = bmask = amask = 0
        if mode in ("1", "L", "P"):
            # 1 = B/W, 1 bit per byte
            # "L" = greyscale, 8-bit
            # "P" = palette-based, 8-bit
            pitch = width
            depth = 8
        elif mode == "RGB":
            # 3x8-bit, 24bpp
            if SDL_BYTEORDER == SDL_LIL_ENDIAN:
                rmask = 0x0000FF
                gmask = 0x00FF00
                bmask = 0xFF0000
            else:
                rmask = 0xFF0000
                gmask = 0x00FF00
                bmask = 0x0000FF
            depth = 24
            pitch = width * 3
        elif mode in ("RGBA", "RGBX"):
            # RGBX: 4x8-bit, no alpha
            # RGBA: 4x8-bit, alpha
            if SDL_BYTEORDER == SDL_LIL_ENDIAN:
                rmask = 0x000000FF
                gmask = 0x0000FF00
                bmask = 0x00FF0000
                if mode == "RGBA":
                    amask = 0xFF000000
            else:
                rmask = 0xFF000000
                gmask = 0x00FF0000
                bmask = 0x0000FF00
                if mode == "RGBA":
                    amask = 0x000000FF
            depth = 32
            pitch = width * 4
        else:
            # We do not support CMYK or YCbCr for now
            raise TypeError("unsupported image format")

        pxbuf = image.tostring()
        surface = sdlsurface.create_rgb_surface_from(pxbuf, width, height,
                                                     depth, pitch, rmask,
                                                     gmask, bmask, amask)

        if mode == "P":
            # Create a SDL_Palette for the SDL_Surface
            def _chunk(seq, size):
                for x in range(0, len(seq), size):
                    yield seq[x:x + size]

            rgbcolors = image.getpalette()
            sdlpalette = sdlpixels.alloc_palette(len(rgbcolors) // 3)
            SDL_Color = sdlpixels.SDL_Color
            for idx, (r, g, b) in enumerate(_chunk(rgbcolors, 3)):
                sdlpalette.colors[idx] = SDL_Color(r, g, b)

            try:
                sdlsurface.set_surface_palette(surface, sdlpalette)
            except:
                sdlsurface.free_surface(surface)
                raise
            finally:
                # This will decrease the refcount on the palette, so it gets
                # freed properly on releasing the SDL_Surface.
                sdlpixels.free_palette(sdlpalette)
    return surface