MATLAB: Resize and save transparent PNG file in matlab

alpha channelimage processingpngtransparency

I have an transparent png file(colored image not black and white).I want to resize this png file and save that with transparent background.but i cant save that with transparent background.file saved with dark background.
[im,map]=imread('image.png');
im=ind2rgb(im,map);
im2=imresize(im,[200,200]);
imwrite(im2,'image2.png');
in above code image2.png saved with black background and not transparent

Best Answer

For a start you never retrieve the transparency information so it's no wonder it's not preserved.
PNG images have two ways to specify transparency. For grayscale and true colour images, the transparency can be specified as an additional alpha channel the same size as the image. You get that in matlab from the 3rd output of imread (not the 2nd). Indexed images in PNG cannot have an alpha channel
For all types of images (so grayscale, true colour and indexed), PNG also allows you to specify a specific colour as transparent. To get that transparent colour in matlab you have to use at the SimpleTransparencyData field of imfinfo.
Assuming your image is actually true colour and that your code is a mistake, then:
[im, ~, alpha] = imread('image.png'); %transparency not valid for index images, so no point in getting map
im2 = imresize(im, [200, 200]);
alpha2 = imresize(alpha, [200 200]);
imwrite(im2, 'image2.png');
If the transparency is actually the second type ( imfinfo will have 'simple' for the Transparency field, then:
fileinfo = imfinfo('image.png');
assert(strcmp(fileinfo.Transparency, 'simple'), 'This file does not have simple transparency')
im = imread('image.png'); %if image is actually indexed, you also need to retrieve the colour map
im2 = imresize(im, [200 200]);
imwrite(im2, 'image2.png', 'Transparency', fileinfo.SimpleTransparencyData);
However, in that second case, note that because of the default interpolation, some transparent pixel may get assigned a colour that is no longer transparent. Using the non-default 'nearest' interpolation option in imresize would solve that problem.