Page 1 of 1

Save camera's image into a bitmap file(in local folder)

Posted: Mon Apr 09, 2018 9:51 pm
by thepbac
Hello, this is a short code to save image from a camera into bitmap file (worked with MJPEG Viewer project). I have its after a long time research and test many times.
I hope it will make you happy when use it.

Code: Select all

void CaptureScreen(int w,int h, unsigned char *image)
{
	BITMAPFILEHEADER bf;
	BITMAPINFOHEADER bi;

	//unsigned char *image = (unsigned char*)malloc(sizeof(unsigned char)*Width*Height * 3);
	FILE *file = fopen("C:/a.bmp", "wb");

	if (image != NULL)
	{
		if (file != NULL)
		{
			glReadPixels(0, 0, w, h, GL_BGR_EXT, GL_UNSIGNED_BYTE, image);

			memset(&bf, 0, sizeof(bf));
			memset(&bi, 0, sizeof(bi));

			bf.bfType = 'MB';
			bf.bfSize = sizeof(bf) + sizeof(bi) + w * h * 3;
			bf.bfOffBits = sizeof(bf) + sizeof(bi);
			bi.biSize = sizeof(bi);
			bi.biWidth = w;
			bi.biHeight = h;
			bi.biPlanes = 1;
			bi.biBitCount = 24;
			bi.biSizeImage = w * h * 3;

			fwrite(&bf, sizeof(bf), 1, file);
			fwrite(&bi, sizeof(bi), 1, file);
			fwrite(image, sizeof(unsigned char), w*h * 3, file);
			fclose(file);
		}		
	}
}
Use

Code: Select all

 Surface  Texture(cameraWidth, cameraHeight);
....
//In main method, on while method  :o 
CaptureScreen(cameraWidth, cameraHeight, Texture.GetBuffer());
:shock:

Re: Save camera's image into a bitmap file(in local folder)

Posted: Sun Aug 08, 2021 7:27 am
by nirvik
Thanks a lot for this code! Was really helpful for my project. For completeness, I would like to add that to be able to use the glReadPixels function we need to:

Code: Select all

 #define GL_GLEXT_PROTOTYPES
#include <GL/gl.h>