How to make a surface with a transparent background in pygame

Can someone give me some example code that creates a surface with a transparent background in pygame?


Asked by: Lucas225 | Posted: 05-10-2021






Answer 1

This should do it:

image = pygame.Surface([640,480], pygame.SRCALPHA, 32)
image = image.convert_alpha()

Make sure that the color depth (32) stays explicitly set else this will not work.

Answered by: Daniel314 | Posted: 06-11-2021



Answer 2

You can also give it a colorkey, much like GIF file transparency. This is the most common way to make sprites. The original bitmap has the artwork, and has a certain color as background that will not be drawn, which is the colorkey:

surf.set_colorkey((255,0,255)) // Sets the colorkey to that hideous purple

Surfaces that uses colorkey instead of alpha are a lot faster to blit since they don't require any blend math. The SDL surface uses a simple bitmask when it has a colorkey set, which blits practically without overhead.

Answered by: Chloe937 | Posted: 06-11-2021



Answer 3

You have 3 possibilities:

  • Set a transparent color key with set_colorkey()

    The color key specifies the color that is treated as transparent. For example, if you have an image with a black background that should be transparent, set a black color key:

    my_surface.set_colorkey((0, 0, 0))
    
  • You can enable additional functions when creating a new surface. Set the SRCALPHA flag to create a surface with an image format that includes a per-pixel alpha. The initial value of the pixels is (0, 0, 0, 0):

    my_surface = pygame.Surface((width, height), pygame.SRCALPHA)
    
  • Use convert_alpha() to create a copy of the Surface with an image format that provides alpha per pixel.

    However, if you create a new surface and use convert_alpha(), the alpha channels are initially set to maximum. The initial value of the pixels is (0, 0, 0, 255). You need to fill the entire surface with a transparent color before you can draw anything on it:

    my_surface = pygame.Surface((width, height))
    my_surface = my_surface.convert_alpha()
    my_surface.fill((0, 0, 0, 0))
    

Answered by: Tara277 | Posted: 06-11-2021



Similar questions

python - How can I make the background of a surface transparent in pygame

In pygame I draw a figure on a Surface. I want the Surface itself to be transparent but the image visible. I've tried to use set_alpha on the Surface, but the figure itself stays transparent. self.original_image = Surface((self.rect.w, self.rect.h)) self.original_image.set_alpha(0) pg.draw.polygon(self.original_image, self.color, [Vector2(gui...


django - python PIL - background displayed opaque instead of transparent

I want to generate 32x32 sized thumbnails from uploaded images (actually avatars). To prevent a thumbnail from being smaller than that size, I want to create a transparent 32x32 background and paste the thumbnail on it. The code below tries to do so. However, the avatar is displayed on a black and opaque background; I lose transparency information somewhere through the process. Where am I doing wrong?...


How do I create a Status Icon / System Tray Icon with custom text and transparent background using Python and GTK?

Here is the code that I have so far to define the icon: icon_bg = gtk.gdk.pixbuf_new_from_file('gmail.png') w, h = icon_bg.get_width(), icon_bg.get_height() cmap = gtk.gdk.Colormap(gtk.gdk.visual_get_system(), False) drawable = gtk.gdk.Pixmap(None, w, h, 24) drawable.set_colormap = cmap gc = drawable.new_gc() drawable.draw_pixbuf(gc, icon_bg, 0, 0, 0, 0, w, h) drawn_icon = gtk.gdk.Pixbuf(gtk.gdk.COLORSPAC...


python - How to get transparent background in window with PyGTK and PyCairo?

I've been trying really hard to create a window with no decoration and a transparent background using PyGTK. I would then draw the content of the window with Cairo. But I can't get it to work. I've tried a lot of different ways, they all failed, this is one of them #!/usr/bin/env python import pygtk pygtk.require('2.0') import gtk, sys, cairo win = None def expose (widget, event): cr = widget...


White background to transparent background using PIL python

How can i transform all white background and white elements of a png or jpg image in a transparent backgroun using PIL?


java - Detect if .swf has transparent background

Is there a way to do this programmatically in PHP, Python or Java? Use case: User uploads .swf through an upload form. Detect if it has a transparent background. If it does, change it to something else, e.g. white.


user interface - I want to make a transparent BACKGROUND frame with my python app (WxPython)

I've always wanted to make a app that's transparent, I love how it looks. I tried to make on of my apps transparent with the SetTransparent(alpha), but I bumped into a big problem. Yes it makes my app transparent (^。^), but it makes EVERYTHING transparent (=。=). I have no idea how to fix this problem. Hours of research didn't really help out. What I meant by background is, nothing el...


python - Transparent background file download from S3

I am trying to permit a python app to access various locations in a many-GB file stored in S3. I'd like to create a drop-in replacement file-like object that intelligently downloads chunks of data from S3 in a separate thread to meet seek() and read() requests. Is there a simple data structure I can use to store arbitrary intervals of the file? It must support O(log n) look-up and O(n) insertion (n=number o...


c++ - How to make wxPython, DC background transparent?

How can i make the default white DC background become invisible (transparent)? Run the following example, it shows a white background over a button. I would like to remove the white background of the DC. (to show only the red X) import wx class drawover(wx.Window): def __init__(self, parent): wx.Window.__init__(self, parent) self.Bind(wx.EVT_PAINT, self.OnPaint) self....


python - Merging background with transparent image in PIL

I have a png image as background and I want to add a transparent mesh to this background but this doesn't work as expected. The background image is converted to transparent on places where I apply transparent mesh. I am doing: from PIL import Image, ImageDraw map_background = Image.open(MAP_BACKGROUND_FILE).convert('RGBA') map_mesh = Image.new('RGBA', (width, height), (0, 0, 0, 0)) draw = ImageDraw...


python - Transparent background in gnuplot multiplot

I'd like to get a transparent background in my gnuplot figure. What I coded till now is: #! /usr/bin/python from numpy import * import Gnuplot as gp import Gnuplot.funcutils x = (1,2,3) y=(2,4,5) x1 = (3,6,8) g = gp.Gnuplot() g("set terminal svg size 200,400") g("set output 'filename.svg'") g("unset xtics") g("unset ytics") g("set multiplot layout 3,1 title 'Title here'") g("set object 1 rectangle from ...


python - How to use PIL to make all white pixels transparent?

I'm trying to make all white pixels transparent using the Python Image Library. (I'm a C hacker trying to learn python so be gentle) I've got the conversion working (at least the pixel values look correct) but I can't figure out how to convert the list into a buffer to re-create the image. Here's the code img = Image.open('img.png') imga = img.convert("RGBA") datas = imga.getdata() newData = list() for i...


pygame - Updating part of a surface in python, or transparent surfaces

I have an application written in python that's basically an etch-a-sketch, you move pixels around with WASD and arrow keys and it leaves a trail. However, I want to add a counter for the amount of pixels on the screen. How do I have the counter update without updating the entire surface and pwning the pixel drawings? Alternatively, can I make a surface that's completely transparent except for the text so you can se...


django - python PIL - background displayed opaque instead of transparent

I want to generate 32x32 sized thumbnails from uploaded images (actually avatars). To prevent a thumbnail from being smaller than that size, I want to create a transparent 32x32 background and paste the thumbnail on it. The code below tries to do so. However, the avatar is displayed on a black and opaque background; I lose transparency information somewhere through the process. Where am I doing wrong?...


python - Transparent FrameBuffer background in OpenGL

I want to use glClear and glClearColor to fill a frame buffer with a colour including alpha transparency. However the framebuffer always renders as opaque when binded to a texture which is rendered to the screen. I want everything which is rendered to the framebuffer to kept their transparency. I just want to change the background. See the following code: def create_texture(surface): surface...


How do I create a Status Icon / System Tray Icon with custom text and transparent background using Python and GTK?

Here is the code that I have so far to define the icon: icon_bg = gtk.gdk.pixbuf_new_from_file('gmail.png') w, h = icon_bg.get_width(), icon_bg.get_height() cmap = gtk.gdk.Colormap(gtk.gdk.visual_get_system(), False) drawable = gtk.gdk.Pixmap(None, w, h, 24) drawable.set_colormap = cmap gc = drawable.new_gc() drawable.draw_pixbuf(gc, icon_bg, 0, 0, 0, 0, w, h) drawn_icon = gtk.gdk.Pixbuf(gtk.gdk.COLORSPAC...


python - How to make cStringIO transparent to another function that expects a real local file

I came up with the following problem: CODE A works right now.. I am saving a png file called chart.png locally, and then I am loading it into the proprietary function (which I do not have access). However, in CODE B, am trying to use cStringIO.StringIO() so that I do not have to write the file "chart.png" to the disk. But I cannot find a way to pass it to the pproprietaryfunction because it is expecting a real fil...


python - PIL: How to make area transparent in PNG?

I've been using PIL to crop Images, now I also want to make certain rectangular areas transparent, say from PIL import Image im = Image.open("sample.png") transparent_area = (50,80,100,200) ...


python - Matplotlib transparent line plots

I am plotting two similar trajectories in matplotlib and I'd like to plot each of the lines with partial transparency so that the red (plotted second) doesn't obscure the blue. EDIT: Here's the image with transparent lines.


python - Transparent 3D bar graphs

I would like to generate 3D bar graphs with transparent surfaces so that I can see what is going on behind tall bars. The mplot3d API docs say that keywords are allowed for the bar3d function. I pass all the required parameters but can only output graphs with solid surfaces.


python - Partially transparent scatter plot, but with a solid color bar

In Python, with Matplotlib, how to simply do a scatter plot with transparency (alpha < 1), but with a color bar that represents their color value, but has alpha = 1? Here is what one gets, with from pylab import *; scatter(range(10), arange(0, 100, 10), c=range(10), alpha=0.2); color_bar = colorbar(): How can the color ba...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top