I am using portable Octave 5.1.0 under Win 10. I mean to write a plot to png with transparent background.
Disclaimer: This question is similar to the two linked below. I
The imwrite
option seems to work. First create the image file img_fname
, then create an alpha layer for it.
It would be interesting to know if one could avoid the intermediate non-transparent file.
EDIT: I managed to create the image directly from my plot, instead of requiring the intermediate file.
x = -10:0.1:10;
plot (x, sin (x));
# Print figure directly to image instead of file
im = print(gcf, '-RGBImage');
tcolor = [255 255 255];
alpha(:,:) = 255 * ( 1 - (im(:,:,1) == tcolor(1)) .* (im(:,:,2) == tcolor(2)) .* (im(:,:,3) == tcolor(3)) );
imwrite(im, 'temp.png', 'Alpha', alpha);
Notes:
With a little simple algebra one could add transparency for any number of colors, and any opacity level for each color. Moreover, one could move this into a function.
The multiplication of im
and tcolor
could be possibly vectorized as well.
Related:
https://www.mathworks.com/matlabcentral/answers/57664-how-to-add-alpha-channel-to-the-image-and-convert-that-image-into-png-format