resize and save transparent PNG file in matlab
49 views (last 30 days)
Show older comments
Mohsen Farjami
on 11 Oct 2018
Commented: Walter Roberson
on 8 Apr 2021
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
2 Comments
Walter Roberson
on 11 Oct 2018
Edited: Walter Roberson
on 4 Nov 2019
You are not reading the alpha correctly
Accepted Answer
Guillaume
on 11 Oct 2018
Edited: Guillaume
on 11 Oct 2018
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.
6 Comments
Ronan da Silva
on 7 Apr 2021
In the sample code above, you do not pass the resized alpha2 to imwrite .
I don't assume MATLAB assigns it automatically?
Ronan
Walter Roberson
on 8 Apr 2021
In https://www.mathworks.com/matlabcentral/answers/423418-resize-and-save-transparent-png-file-in-matlab#comment_620927 Guillaume does pass the resized alpha2 to imwrite, on the line
imwrite(im2, 'image2.png', 'Alpha', alpha2);
^^^^^^^
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

