The write() method of the Imgcodecs class is used to write an image using OpenCV. To write an image, repeat the first three steps from the previous example.
To write an image, you need to invoke the imwrite() method of the Imgcodecs class.
Following is the syntax of this method.
imwrite(filename, mat)
This method accepts the following parameters −
filename − A String variable representing the path where to save the file.
mat − A Mat object representing the image to be written.
Following program is an example to write an image using Java program using OpenCV library.
import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; public class WritingImages { public static void main(String args[]) { //Loading the OpenCV core library System.loadLibrary(Core.NATIVE_LIBRARY_NAME); //Instantiating the imagecodecs class Imgcodecs imageCodecs = new Imgcodecs(); //Reading the Image from the file and storing it in to a Matrix object String file ="C:/EXAMPLES/OpenCV/sample.jpg"; Mat matrix = imageCodecs.imread(file); System.out.println("Image Loaded .........."); String file2 = "C:/EXAMPLES/OpenCV/sample_resaved.jpg"; //Writing the image imageCodecs.imwrite(file2, matrix); System.out.println("Image Saved ............"); } }
On executing the above program, you will get the following output −
Image Loaded .......... Image Saved ...........
If you open the specified path, you can observe the saved image as shown below −