FAQ - Image Transparency
Q: How to display images with transparent backgrounds?
A: It is possible in PTB to display PNG images with transparent backgrounds. For example, when adding a curved or irregularly shaped image on top of another texture where you want to eliminate the white pixels that form a box around your image. To do this, follow these steps:
- Save your image with a transparent background in PNG format (appears that this method will not work with other file formats that support transparency such as GIF and TIFF).
- When loading your image, use the following command:
- [imagename map alpha] = imread('filename.png');
- -> Here, imagename is the usual m-by-n-by-3 colour matrix with the RGB layers
- -> alpha is an m-by-n matrix with the transparency (alpha) channel
- Next, append the alpha layer as a 4th layer to your image matrix like this:
- imagename(:,:,4) = alpha(:,:);
- Next, you need to enable alpha blending, so the tranparency layer gets used, by adding the following statement somewhere after Screen('OpenWindow') and before your drawing command:
- Screen('BlendFunction', win, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- Finally, use the usual Screen('MakeTexture', ...) and Screen('DrawTexture', ...) commands (or similar) to blit your image onto the screen
For more info, try > help imread, or search the Matlab documentation for PNG
Many thanks to Mario Kleiner for this solution.