Keep Alpha in Pygame PixelArray - python

I wan't to change every colors in my image to grey;but I don't wan't to make any changes to my image alpha.I wan't to keep transparent pixels of my image.this is my code:
from pygame import *
init()
screen = display.set_mode([640, 640])
r = image.load('g.png')
r = transform.scale(r,(640,640))
ar = PixelArray (r)
ar.replace ((255, 255, 255), (110, 110, 110), 0.15)
del ar
screen.blit(r, (0,0))
display.update()

Here's a workaround: Paint all transparent pixels of your image-file g.png with a color you're never going to use, like magic-pink or pitch-black. Then just change ever color of the image but you're transparent color - and then, before you blit, convert your array to a surface and set the colorkey to your transparent color, like this: surface.set_colorkey((225, 0, 225))

Related

How do I make the screen ignore the background color of some image?

I'm using python 2.7, and I am currently working on a basic game in pyagme for my school work. I downloaded an image from google, and it has a background color and I know it's RGB. I remember that there is a method that makes the screen ignore this RGB for the picture (the picture will appear without the background color) but I don't remember it.
import pygame
WINDOW_WIDTH = 1200
WINDOW_LENGTH = 675
IMAGE = r'C:\Users\omero\Downloads\BattleField.jpg'
PISTOL_IMAGE = r'C:\Users\omero\Downloads\will.jpg'
RED = (255,0,0)
BLACK = (0,0,0)
WHITE = (255,255,255)
pygame.init()
size = (WINDOW_WIDTH, WINDOW_LENGTH)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Game")
clock = pygame.time.Clock()
img = pygame.image.load(IMAGE)
screen.blit(img, (0,0))
pygame.display.flip()
pistol_img = pygame.image.load(PISTOL_IMAGE)
colorkey = pistol_img.get_at((0,0))
screen.blit(pistol_img,(50,50))
pygame.display.flip()
finish = False
while not finish:
for event in pygame.event.get():
if event.type == pygame.QUIT:
finish = True
pygame.quit()
When I run the above I get the background color with pistol_img, how do I make the screen ignore it without editing the image?
The white artifacts you can see in the picture are caused because the JPG format is a compressed format.
The compression is not lossless. This means the colors around the weapon are not exactly white (255, 255, 255). The color appear to be white for the human eye, but actually the color channels have a value lass than 255, but near to 255.
You can try to correct this manually. Ensure that format of the image has an alpha channel by pygame.Surface.convert_alpha(). Identify all the pixel, which have a red green and blue color channel above a certain threshold (e.g. 230). Change the color channels and the alpha channel of those pixels to (0, 0, 0, 0):
img = pygame.image.load(IMAGE).convert_alpha()
threshold = 230
for x in range(img.get_width()):
for y in range(img.get_height()):
color = img.get_at((x, y))
if color.r > threshold and color.g > threshold and color.b > threshold:
img.set_at((x, y), (0, 0, 0, 0))
Of course you are in danger to change pixels which you don't want to change to. If the weapon would have some very "bright" areas, then this areas my become transparent, too.
Note, an issue like this can be avoided by using a different image format like BMP or PNG.
With this formats the pixel can be stored lossless.
You can try to "photo shop" the image. Manually change the pixel around the weapon and store the image with a different format.

Transparent Image in Pygame

I have a sprite in Pygame that is a blue circle. I want this image to be drawn to the screen "faded", e.g. translucent. However, I don't want a translucent rectangle to be drawn over it; instead, I want the actual image to be modified and made translucent. Any help is greatly appreciated!
Right now I have:
Class Circle(pygame.sprite.Sprite):
self.image = self.image = pygame.image.load("circle.png")
circle = Circle()
and eventually...
window.blit(pygame.transform.scale(circle.image, (zoom, zoom)), (100, 100))
How the circle.png looks:
How I want the image to look after making it transparent:
I am blitting the image onto the window, which is a white background.
First, your image/surface needs to use per-pixel alpha, therefore call the convert_alpha() method when you load it. If you want to create a new surface (as in the example), you can also pass pygame.SRCALPHA to pygame.Surface.
The second step is to create another surface (called alpha_surface here) which you fill with white and the desired alpha value (the fourth element of the color tuple).
Finally, you have to blit the alpha_surface onto your image and pass pygame.BLEND_RGBA_MULT as the special_flags argument. That will make
the opaque parts of the image translucent.
import pygame as pg
pg.init()
screen = pg.display.set_mode((800, 600))
clock = pg.time.Clock()
BLUE = pg.Color('dodgerblue2')
BLACK = pg.Color('black')
# Load your image and use the convert_alpha method to use
# per-pixel alpha.
# IMAGE = pygame.image.load('circle.png').convert_alpha()
# A surface with per-pixel alpha for demonstration purposes.
IMAGE = pg.Surface((300, 300), pg.SRCALPHA)
pg.draw.circle(IMAGE, BLACK, (150, 150), 150)
pg.draw.circle(IMAGE, BLUE, (150, 150), 130)
alpha_surface = pg.Surface(IMAGE.get_size(), pg.SRCALPHA)
# Fill the surface with white and use the desired alpha value
# here (the fourth element).
alpha_surface.fill((255, 255, 255, 90))
# Now blit the transparent surface onto your image and pass
# BLEND_RGBA_MULT as the special_flags argument.
IMAGE.blit(alpha_surface, (0, 0), special_flags=pg.BLEND_RGBA_MULT)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
screen.fill((50, 50, 50))
pg.draw.rect(screen, (250, 120, 0), (100, 300, 200, 100))
screen.blit(IMAGE, (150, 150))
pg.display.flip()
clock.tick(60)
pg.quit()
Create a new Surface with per-pixel alpha.
surf = pygame.Surface((circle_width, circle_height), pygame.SRCALPHA)
Make the surface transparent
surf.set_alpha(128) # alpha value
Draw the circle to that surface at (x=0, y=0)
surf.blit(pygame.transform.scale(circle.image, (zoom, zoom)), (0, 0))
Draw the surface to the window
window.blit(surf, (circle_x, circle_y))
As the Surface.set_alpha() documentation says, you can have surfaces with "homogeneous alpha" or per pixel alpha, but not both, wich I believe is what you want. It might work with colorkey transparency, but I'm not sure (I didn't tested that yet). Any non RGBA (without active alpha channel) pixel format might work if you use set_colorkey() and set_alpha() before blitting.
So, the code might look like:
class Circle(pygame.sprite.Sprite):
def __init__(self)
self.image = pygame.image.load("circle.png")
# get the surface's top-left pixel color and use it as colorkey
colorkey = self.image.get_at((0, 0))
self.image.set_colorkey(colorkey)
At some point in your code (immediately before rendering) you might want to set the transparency by calling:
circle.image.set_alpha(some_int_val)
And then you can scale and blit it as intended.

pygame.error: Couldn't allocate memory for PNG file or incompatible PNG dll [duplicate]

I'm trying to blit a PNG image onto a surface, but the transparent part of the image turns black for some reason, here's the simple code:
screen = pygame.display.set_mode((800, 600), pygame.DOUBLEBUF, 32)
world = pygame.Surface((800, 600), pygame.SRCALPHA, 32)
treeImage = pygame.image.load("tree.png")
world.blit(treeImage, (0,0), (0,0,64,64))
screen.blit(world, pygame.rect.Rect(0,0, 800, 600))
What do I have to do to solve the problem?
The image has alpha transparency, I've opened it up in PhotoShop and the background turns transparent, not black or white or any other color.
Thank you for your support :)
http://www.pygame.org/docs/ref/image.html recommends:
For alpha transparency, like in .png images use the convert_alpha() method after loading so that the image has per pixel transparency.
You did not flip the doublebuffer.
import pygame
from pygame.locals import Color
screen = pygame.display.set_mode((800, 600))
treeImage = pygame.image.load("tree.png").convert_alpha()
white = Color('white')
while(True):
screen.fill(white)
screen.blit(treeImage, pygame.rect.Rect(0,0, 128, 128))
pygame.display.flip()
This should work for your problem.
Images are represented by "pygame.Surface" objects. A Surface can be created from an image with pygame.image.load:
my_image_surface = pygame.load.image('my_image.jpg')
However, the pygame documentation notes that:
The returned Surface will contain the same color format, colorkey and alpha transparency as the file it came from. You will often want to call convert() with no arguments, to create a copy that will draw more quickly on the screen.
For alpha transparency, like in .png images, use the convert_alpha() method after loading so that the image has per pixel transparency.
Use the convert_alpha() method for best performance:
alpha_image_surface = pygame.load.image('my_icon.png').convert_alpha()
A Surface can be drawn on or blended with another Surface using the blit method. The first argument to blit is the Surface that should be drawn. The second argument is either a tuple (x, y) representing the upper left corner or a rectangle. With a rectangle, only the upper left corner of the rectangle is taken into account. It should be mentioned that the window respectively display is also represented by a Surface. Therefore, drawing a Surface in the window is the same as drawing a Surface on a Surface:
window_surface.blit(image_surface, (x, y))
window_surface.blit(image_surface,
image_surface.get_rect(center = window_surface.get_rect().center))
Minimal example: repl.it/#Rabbid76/PyGame-LoadTransparentImage
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
pygameSurface = pygame.image.load('Porthole.png').convert_alpha()
background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (160, 160, 160), (192, 192, 192)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
pygame.draw.rect(background, color, rect)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.blit(background, (0, 0))
window.blit(pygameSurface, pygameSurface.get_rect(center = window.get_rect().center))
pygame.display.flip()
pygame.quit()
exit()
Your code looks like it should be correct. The SDL library does not support alpha to alpha blitting like this, but Pygame added support for it awhile ago. In Pygame 1.8 support was added for custom blending modes, and I wonder if that removed Pygame's internal alpha-to-alpha blitter?
Alas, further investigation will be required.

Drawn surface transparency in pygame?

I'm writing a predator-prey simulation using python and pygame for the graphical representation. I'm making it so you can actually "interact" with a creature (kill it, select it and follow it arround the world, etc). Right now, when you click a creature, a thick circle(made of various anti-aliased circles from the gfxdraw class) sorrounds it, meaning that you have succesfully selected it.
My goal is to make that circle transparent, but according to the documentation you can't set an alpha value for drawn surface. I have seen solutions for rectangles (by creating a separate semitransparent surface, blitting it, and then drawing the rectangle on it), but not for a semi-filled circle.
What do you suggest? Thank's :)
Have a look at the following example code:
import pygame
pygame.init()
screen = pygame.display.set_mode((300, 300))
ck = (127, 33, 33)
size = 25
while True:
if pygame.event.get(pygame.MOUSEBUTTONDOWN):
s = pygame.Surface((50, 50))
# first, "erase" the surface by filling it with a color and
# setting this color as colorkey, so the surface is empty
s.fill(ck)
s.set_colorkey(ck)
pygame.draw.circle(s, (255, 0, 0), (size, size), size, 2)
# after drawing the circle, we can set the
# alpha value (transparency) of the surface
s.set_alpha(75)
x, y = pygame.mouse.get_pos()
screen.blit(s, (x-size, y-size))
pygame.event.poll()
pygame.display.flip()

How do I blit a PNG with some transparency onto a surface in Pygame?

I'm trying to blit a PNG image onto a surface, but the transparent part of the image turns black for some reason, here's the simple code:
screen = pygame.display.set_mode((800, 600), pygame.DOUBLEBUF, 32)
world = pygame.Surface((800, 600), pygame.SRCALPHA, 32)
treeImage = pygame.image.load("tree.png")
world.blit(treeImage, (0,0), (0,0,64,64))
screen.blit(world, pygame.rect.Rect(0,0, 800, 600))
What do I have to do to solve the problem?
The image has alpha transparency, I've opened it up in PhotoShop and the background turns transparent, not black or white or any other color.
Thank you for your support :)
http://www.pygame.org/docs/ref/image.html recommends:
For alpha transparency, like in .png images use the convert_alpha() method after loading so that the image has per pixel transparency.
You did not flip the doublebuffer.
import pygame
from pygame.locals import Color
screen = pygame.display.set_mode((800, 600))
treeImage = pygame.image.load("tree.png").convert_alpha()
white = Color('white')
while(True):
screen.fill(white)
screen.blit(treeImage, pygame.rect.Rect(0,0, 128, 128))
pygame.display.flip()
This should work for your problem.
Images are represented by "pygame.Surface" objects. A Surface can be created from an image with pygame.image.load:
my_image_surface = pygame.load.image('my_image.jpg')
However, the pygame documentation notes that:
The returned Surface will contain the same color format, colorkey and alpha transparency as the file it came from. You will often want to call convert() with no arguments, to create a copy that will draw more quickly on the screen.
For alpha transparency, like in .png images, use the convert_alpha() method after loading so that the image has per pixel transparency.
Use the convert_alpha() method for best performance:
alpha_image_surface = pygame.load.image('my_icon.png').convert_alpha()
A Surface can be drawn on or blended with another Surface using the blit method. The first argument to blit is the Surface that should be drawn. The second argument is either a tuple (x, y) representing the upper left corner or a rectangle. With a rectangle, only the upper left corner of the rectangle is taken into account. It should be mentioned that the window respectively display is also represented by a Surface. Therefore, drawing a Surface in the window is the same as drawing a Surface on a Surface:
window_surface.blit(image_surface, (x, y))
window_surface.blit(image_surface,
image_surface.get_rect(center = window_surface.get_rect().center))
Minimal example: repl.it/#Rabbid76/PyGame-LoadTransparentImage
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
pygameSurface = pygame.image.load('Porthole.png').convert_alpha()
background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (160, 160, 160), (192, 192, 192)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
pygame.draw.rect(background, color, rect)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.blit(background, (0, 0))
window.blit(pygameSurface, pygameSurface.get_rect(center = window.get_rect().center))
pygame.display.flip()
pygame.quit()
exit()
Your code looks like it should be correct. The SDL library does not support alpha to alpha blitting like this, but Pygame added support for it awhile ago. In Pygame 1.8 support was added for custom blending modes, and I wonder if that removed Pygame's internal alpha-to-alpha blitter?
Alas, further investigation will be required.

Categories