QA: How to save a bitmap into jpeg file?
October 28th, 2004 by Andrey Yatsyk
Question
I want to create a jpeg file in my program. How can I save a bitmap into a jpeg file?
Answer
In Using IJG JPEG library article I have described how to read jpeg files on Pocket PC using IJG library. It is recommended to take a look at that article where jpeg lib porting discussed.
In order to write jpeg files link your projects with IJG jpeg library. I have provided a test project (408 Kb) that writes jpegs. You can compile and run this application. When you press “Write Jpeg” button on this application a bitmap from application resources will be saved as a jpeg file in \My Documents directory.
If you want to use saving code in your application insert STScreenBuffer.cpp, STScreenBuffer.h, JpegWriter.h, JpegWriter.cpp files into your project and link it with the jpeg library. In JpegWriter.h you can find definitions of the following 3 functions:
BOOL WriteRGBBytesIntoJpegFile(const CString& strOutFileName,
const int nWidth, const int nHeight, const int nQuality, BYTE* pBuffer);
This function destined for saving an array of RGB data pointed by pBuffer to a jpeg file named strOutFileName. The array of data is supposed to be a nWidth*nHeight*3 bytes length. The nQuality is jpeg quality in range of 1..100.
BOOL WriteBitmapIntoJpegFile(const CString& strOutFileName,
const int nQuality, HBITMAP hBitmap);
hBitmap is a handle for standard windows bitmap. Both functions return FALSE when error occurred and TRUE otherwice. If you want to get string representation of last error you should call following method:
CString GetJpegWriterError();
Provided functions are far from to be optimal in order to save simplicity. WriteBitmapIntoJpegFile can be rewritten without using WriteRGBBytesIntoJpegFile if you do so you can avoid extra memory allocation. If you want use this functions in more critical applications or you want save extremely large files please observe example.c in jpeglib destribution. This file contains well-commented jpeg saving and loading code. My code is based on that functions and I have tried to leave same variable names.
Test project contains CSTScreenBuffer class for bitmap data grabbing. You can read about this class there.
Related resources:
Section: Images
Article: Using IJG JPEG library
QA: How can I get bitmap bits?
Library: LibPng
Library: VOImage
Library: STScreenBuffer
Library: DIBSection
Control: PictureBox
Article: Developing with an Enhanced PictureBox
Article: Displaying GIF, JPEG, and Other Graphics in Your C++ Applications
Article: A DIBSection wrapper for Win32 and WinCE
