How to draw an image in (pygame) - python

I want to replace this draw rectangle function, and instead let it produce an image.
Rectangle Function:
pygame.draw.rect(pygame.display.set_mode((800,600)), black, [0,0, 100, 100])
Looking for something on the lines of this:
pygame.draw.image(**coordinatesX**, **coordinatesY**, **imagefile.jpg**)

To load an image, you need the file stored, and you load it using:
pygame.image.load('example.png')
Now your code should look like:
pygame.image.load('example.png')
pygame.display.set_mode((800, 600))

so first you have to load the image using image = pygame.image.load() and then use screen.blit(image) to draw it on the screen. For this to work you should define the screen at the beginning not in the draw function like you have done above. Just screen = pygame.display.set_mode((800,600)) should work.

Related

How to take screenshot of entire display pygame

I am creating a painter software and want the user to be able to save their image after they have finished creating it, so I tried pygame.image.save(pygame.display.get_surface(), "/home/user/screenshot.png"). I made a quick drawing and pressed the key I set which would save the image. I look at the image, and it's only saved the blank display surface, not the pygame.draw.rect()s of the actual drawing. I looked at the following links: How to capture pygame screen? https://gamedev.stackexchange.com/questions/118372/how-can-i-take-a-screenshot-of-a-certain-part-of-the-screen-in-pygame Can python get the screen shot of a specific window? and much more. How would I take a screenshot of the entire display screen along with the drawing? This is my mainloop:
running = True
while running:
updateWindow() # Updates window
clearWindow() # Clears window
checkEvents() # Checks events
redrawItems() # Redraws your drawing
pygame.event.pump()
pygame.display.quit()
pygame.quit()
Try pygame.Surface.copy on the display surface. See docs here.
So if display is your screen, then:
screencopy = display.copy()
should get you a copy of the display image in screencopy. Remember because of double buffering it will give you a copy of what you would see on the screen if you did an display.update() right then, which might be different that what is showing on the screen if you have done things that have not yet been pushed to the screen yet by an update().
You can do this using pygame.image.save(Surface, filename), which you can read more about
here
Below is a simple function that will save a portion of the display as an image.
def Capture(display,name,pos,size): # (pygame Surface, String, tuple, tuple)
image = pygame.Surface(size) # Create image surface
image.blit(display,(0,0),(pos,size)) # Blit portion of the display to the image
pygame.image.save(image,name) # Save the image to the disk**
What this function does is created a pygame surface named image. Then the area (pos,size) is blitted to image at its origin. Finally, pygame.image.save(Surface, filename) will be called and save image to the disk.
For example, if we want to save a 100x100 image named "Capture.png" at the pos 50x50 on the display, name would equal "Capture.png", pos would equal (50,50), and size would equal (100,100), and the function call would look as such:
Capture(display,"Capture.png",(50,50),(100,100))

Make the background of an image transparent in Pygame with convert_alpha

I am trying to make the background of an image transparent in a Pygame script. Now the background in my game is black, instead of transparent. I read somewhere else that I could use convert_alpha, but it doesn't seem to work.
Here is (the relevant part of) my code:
import PIL
gameDisplay = pygame.display.set_mode((display_width, display_height))
img = pygame.image.load('snakehead1.bmp').convert_alpha(gameDisplay)
What am I doing wrong? Thanks in advance!
To make an image transparent you first need an image with alpha values. Be sure that it meets this criteria! I noticed that my images doesn't save the alpha values when saving as bmp. Apparently, the bmp format do not have native transparency support.
If it does contain alpha you should be able to use the method convert_alpha() to return a Surface with per-pixel alpha. You don't need to pass anything to this method; if no arguments are given the new surface will be optimized for blitting to the current display.
Here's an example code demonstrating this:
import pygame
pygame.init()
screen = pygame.display.set_mode((100, 100))
image = pygame.image.load("temp.png").convert_alpha()
while True:
screen.fill((255, 255, 255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
screen.blit(image, (0, 0))
pygame.display.update()
And my image ("temp.png"):
If it doesn't contain alpha there are two easy fixes.
Save the image with a different file format, like png.
Use colorkeys. This works if you only need to remove the background. It is as easy as putting the line of code image.set_colorkey((0, 0, 0)), which will make all black colors transparent.

How to make the background of a pygame sprite transparent

This is supposed to just load a sprite onto the screen, but the background of the image is this black box, and i don't want to see that. How do I make the background of the image transparent?
from Tkinter import *
import pygame
from livewires import games
#Creating screen window
games.init(screen_width = 700, screen_height = 650, fps = 50)
#creating background image for the screen
screen_background = games.load_image('resized_stars background.png', transparent = False)
games.screen.background = screen_background
#Creating a sprite
spaceship_image = games.load_image('pixel_spaceship.png')
spaceship = games.Sprite(image = spaceship_image, x=350, y=235)
games.screen.add(spaceship)
#main loop at the end of the program just as in tkinter
games.screen.mainloop()
Your image needs to be a png. Open Preview, for example, and use the alpha tool to remove the background, thus adding transparency.
Before png:
After png:
Look here for a tool on making your picture transparent.
When loading the png image, you have to convert it:
image = pygame.image.load("yourImage.png").convert_alpha()
This should get rid of that black box that should be the transparent alpha.

How to blit an image, in python, inside the area of a specific image?

I'm making a game and I need to blit my objects inside the area of a specific image. I don't want to need my surface to blit these images. Is it possible? (I'm using pygame)
It would be better in the future if you would explain what you are trying to do a bit better since it would give you more answers :)
From what I have understood you want to blit an image onto another image:
For this code to work the following premises are set:
The folder which contains the program also contains the arbritary images named testimage.png and testimage0.jpg
PyGame is installed
I have written the following piece of code which you can run if you follow the above premises:
import pygame
screen = pygame.display.set_mode([800, 800], 0, 32)
#initiates screen
image1 = pygame.image.load('testimage0.jpg')
#testimage0.jpg is loaded into the variable image1
image2 = pygame.image.load('testimage.png').convert_alpha()
#testimage.png is loaded into the variable image2
while True:
screen.fill([0, 0, 0])
#screen is filled with a black background
screen.blit(image1, [200, 200])
#here image1 is blitted onto screen at the coordinates (200,200)
image1.blit(image2, [0, 0])
#here image2 is blitted onto image1 at the coordinates (0,0) which starts at the upper left of image1
pygame.display.update()
#updates display, which you can just ignore
Images are just surfaces with a sprite or picture on. The coordinate system of a surface always starts at the upper left (0,0), which is why (0,0) of image1 isn't the same as the (0,0) of screen.
I took a picture of the program and edited some arrows in to explain my point:
Hope this was a help and remember to accept as the answer if you find it acceptable.

Transparent Sprites in Pygame

I'm working on some Python code that uses Pygame, trying to display a small sprite (a ball) on top of a background. I have that part working, but I'm trying to get the background of the ball sprite to be transparent so it doesn't show up as a "ball within a black square" sprite, but instead shows up with the black pixels not being blitted to the display surface.
Here is my code:
# For sys.exit()
import sys
# Pygame imports
import pygame
from pygame.locals import *
# Initialize all the Pygame Modules
pygame.init()
# Build a screen (640 x 480, 32-bit color)
screen = pygame.display.set_mode((640,480))
# Create and Convert image files
# Use JPG files for lots of color, and use conver()
# Use PNG files for transparency, and use convert_alpha()
background = pygame.image.load("bg.jpg").convert()
ball = pygame.image.load("ball.png").convert_alpha()
ball.set_colorkey(-1, RLEACCEL) # Use the upper-left pixel color as transparent
# The main loop
while True:
# 1 - Process all input events
for event in pygame.event.get():
# Make sure to exit if the user clicks the X box
if event.type == QUIT:
pygame.quit()
sys.exit()
# 2 - Blit images to screen (main display window)
screen.blit(background, (0,0))
x,y = pygame.mouse.get_pos()
x = x - ball.get_width()/2
y = y - ball.get_height()/2
screen.blit(ball, (x,y))
# 3 - Update the main screen (redraw)
pygame.display.update()
I must be making an obvious mistake, but I can't figure it out. Calling ball.set_colorkey(-1, RLEACCEL) should pick up the color of the upper-left corner of the ball sprite (which happens to be black) and use that as the pixel color "not to blit". Am I missing a step?
Thanks for your help.
There's per-pixel alpha, colorkey alpha, and per-surface alpha. You're asking for colorkey.
When you call convert_alpha() it creates a new surface for per-pixel alpha.
And from set_colorkey
The colorkey will be ignored if the Surface is formatted to use per pixel alpha values.
So: Load image with .convert() Since you want to use a color key. Then call set_colorkey.
Also, I saw nothing in the docs about passing "-1" as first argument to set_colorkey.
That's probably from a tutorial, which has a load_image function to grab the topleft pixel's color value.
How is your image created?
Pygame transparecy for blitting should work if your "ball.png" file i s a ball on transparent background, and not a ball on a black square.
That said, from Pygame's surface documentation for "set_colorkey":
"The colorkey will be ignored if the Surface is formatted to use per pixel alpha values. The colorkey can be mixed with the full Surface alpha value."
So, the idea of colorkey is to use it when yiour image does not have per pixel alpha - and you are just ensuring it does have when you call "convert alpha". Also, I saw nothing in the docs about passing "-1" as first argument to set_colorkey.
In short: My advice is to use proper transparent images to start with - and forget about "convert", "convert_alpha", "set_colorkey" and so on. If you have some reason for not using per pixel alpha from the PNG file, then check this answer a the right way to do it (and even for one reason not to want per pixel alpha when blitting to the screen):
PyGame: Applying transparency to an image with alpha?

Categories