MATLAB: How to export .png image made by “imagesc” with specific size of 32*32 pixels

imagescplot

I had a 32*32 matrix and applied "imagesc" to plot an image with code below:
imagesc(double(matrix)) % 32*32 matrix
axis off, axis image
Presently, I need to export this image with 32*32 pixels without any white space around it. I search this question a lot, but cannot find any solutions.
Please help me. Thanks a lot. 🙂

Best Answer

I = im2uint8(mat2gray(matrix));
cmap = colormap;
imwrite(I, cmap, 'YourFileName.png')
With newer MATLAB versions, you can use rescale() instead of the obscurely-named mat2gray().
For greater control you can ind2rgb instead of having imwrite create an indexed image:
I = im2uint8(mat2gray(matrix));
cmap = colormap;
Irgb = ind2rgb(I, cmap);
imwrite(Irgb, 'YourFileName.png')