inserting image.png in gui with transparent background

16 views (last 30 days)
I have this code that allow me to inserting an image.png with a transparent background.
When I do the test with the picture below:
I get the desired result:
But when I try with other pictures.png, I get the image with black background:
I don't know why the backgroung is black. Can you help me too solve this.
f = figure(); % create a figure with an axes on it
%ax = axes('Units','pixels', 'Position',[0 0 560 420], 'XTick',[], 'YTick',[], ...
% 'Nextplot','add', 'YDir','reverse');
% read the big logo image - background of the figure
%bigImage = imread('Matlab_Logo.png');
%image(bigImage, 'parent', ax); % Display the image in the axes
% read a smaller image - background of button
img = imread('batterie.png');
s = size(img);
pos = [10 10 s(2) s(1)]; %Position of the button
% Extract the portion of the image where the button will be.
%F = getframe(ax,pos); % take a screenshot of the parent figure
pb = uicontrol('Style','pushbutton', 'Position',pos, 'CData', img,...
'Callback',@(a,b)disp('push button'));
% as before - calculate where the button image is white.
img = double(img)/255;
index1 = img(:,:,1) == 1;
index2 = img(:,:,2) == 1;
index3 = img(:,:,3) == 1;
indexWhite = index1+index2+index3==3;
% for each pixel, replace the white portion with the parent image data
for idx = 1 : 3
rgb = img(:,:,idx); % To make the picture quirky change the RGB
%pImage = double(F.cdata(:,:,idx))/255; % extract part of the image
rgb(indexWhite) = NaN; % set the white portion of the image to the parent
img(:,:,idx) = rgb; % substitute the update values
set(pb, 'CData', img)
set(f, 'Color', get(pb,'BackgroundColor'))

Answers (1)

DGM on 11 Jan 2023
Your images have alpha content, but you're not reading any of it or using it. Instead of blindly trying to reconstruct the alpha content based on a false assumption that it's defined by the color content, just use the alpha content.
UI controls that support CData don't support RGBA content, so you'll have to precompose the image with some fixed background color. The resulting image is not transparent.
f = figure(); % create a figure with an axes on it
% read a logo image and its associated alpha
%[logopict,~,alpha] = imread('logo.png');
[logopict,~,alpha] = imread('battery.png');
% create pushbutton
s = size(logopict);
pos = [10 10 s(2) s(1)]; % Position of the button
pb = uicontrol('Style','pushbutton','Position',pos, ...
'Callback',@(a,b)disp('push button'));
% composite the image with the background color
bgcolor = [1 0.7 0]; % or whatever color you choose
logopict = im2double(logopict);
alpha = im2double(alpha);
safepict = logopict.*alpha + permute(bgcolor,[1 3 2]).*(1-alpha);
% put the image on the button


Find more on Display Image in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!