How to Write Image in MATLAB: Save Images Easily
In MATLAB, you write an image to a file using the
imwrite function. You provide the image data and the filename with the desired format, like imwrite(imageMatrix, 'filename.png') to save an image as PNG.Syntax
The basic syntax to write an image in MATLAB is:
imwrite(A, filename): Saves image dataAto the file namedfilename.Ais the image matrix (grayscale, RGB, or indexed).filenameis a string with the file name and extension (like '.png', '.jpg').- You can also specify the format explicitly:
imwrite(A, filename, fmt).
matlab
imwrite(A, filename) imwrite(A, filename, fmt)
Example
This example creates a simple red square image and saves it as a PNG file named 'red_square.png'.
matlab
A = uint8(zeros(100, 100, 3)); A(:, :, 1) = 255; % Red channel set to max imwrite(A, 'red_square.png');
Output
A file named 'red_square.png' is created in the current folder containing a 100x100 red square image.
Common Pitfalls
- Not converting image data to an appropriate type like
uint8oruint16can cause unexpected results or errors. - For RGB images, the matrix must be 3D with size MxNx3.
- Using an unsupported file extension or format will cause
imwriteto fail. - Overwriting important files by using the same filename without backup.
matlab
% Wrong: Using double without scaling A = rand(100, 100); imwrite(A, 'random.png'); % May produce a black image % Right: Convert to uint8 A_uint8 = uint8(255 * A); imwrite(A_uint8, 'random_correct.png');
Quick Reference
Remember these tips when writing images in MATLAB:
- Use
imwritewith image matrix and filename. - Ensure image data type matches format requirements (usually
uint8). - Specify file extension to set image format.
- Check current folder for saved files.
Key Takeaways
Use imwrite(imageMatrix, 'filename.ext') to save images in MATLAB.
Convert image data to uint8 or uint16 before saving for correct output.
Include the file extension to specify the image format automatically.
Ensure RGB images have three color channels in the third dimension.
Avoid overwriting files by checking filenames before saving.