Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

How to determine the image format ?

Hi, i'm currently learning to do image resize with OpenCV java and i notice that i need to imencode to MatOfByte, beofre calling toArray. I tried resize into MatOfByte directly, but calling toArray causes exception.

With imencode, i need to specify the image format, and i want a jpg to be resized into jpg, a png into png, etc. So is there any ways i can detect the image type with opencv, so i can pass the correct format extension to the imencode ?

    Mat image = Highgui.imread("h:/opencv.jpg");
    Mat converted = new Mat();
    Imgproc.resize(image, converted, new Size(1140, 1140), 0, 0, Imgproc.INTER_AREA);
    Highgui.imwrite("h:/opencv_1140.jpg", converted);
    MatOfByte byteMat = new MatOfByte();
    String fileFormat = ...// detect file format from source image, but how ? ex ".jpg"
    Highgui.imencode(fileFormat, converted, byteMat);
    byte[] array = byteMat.toArray();
click to hide/show revision 2
retagged

updated 2014-05-04 04:12:04 -0600

berak gravatar image

How to determine the image format ?

Hi, i'm currently learning to do image resize with OpenCV java and i notice that i need to imencode to MatOfByte, beofre calling toArray. I tried resize into MatOfByte directly, but calling toArray causes exception.

With imencode, i need to specify the image format, and i want a jpg to be resized into jpg, a png into png, etc. So is there any ways i can detect the image type with opencv, so i can pass the correct format extension to the imencode ?

    Mat image = Highgui.imread("h:/opencv.jpg");
    Mat converted = new Mat();
    Imgproc.resize(image, converted, new Size(1140, 1140), 0, 0, Imgproc.INTER_AREA);
    Highgui.imwrite("h:/opencv_1140.jpg", converted);
    MatOfByte byteMat = new MatOfByte();
    String fileFormat = ...// detect file format from source image, but how ? ex ".jpg"
    Highgui.imencode(fileFormat, converted, byteMat);
    byte[] array = byteMat.toArray();