QImage Basic

QImage is the Qt class for image I/O. It conveniently supports a few usual image formats. The following is about some basic usage of QImage.

First include the header:

#include <QtGui/QImage.h>

To compile it on Mac, better use -framework flag like:

g++ -o test main.cpp -framework QtCore -framework QtGui

QtCore.framework and QtGui.framework should be found in /Library/Frameworks/

To load an image:

QImage in_img( “foo.tif” );

If it failed to open the image, result will be null:
if(in_img.isNull())
{
cout<<“failed to load image, do nothing”<<endl;
return 0;
}
A few properties about the image:

cout<<”  size: “<<in_img.width()<<” x “<<in_img.height()<<endl;
cout<<”  depth: “<<in_img.depth()<<” bits-per-pixel”<<endl;

Any 8-bit Tiff image with alpha channel should return format as ARGB32:
if(in_img.format() == QImage::Format_ARGB32)
cout<<”  format: ARGB32″<<endl;

if(in_img.hasAlphaChannel())
cout<<”  alpha channel: yes”<<endl;
else
cout<<”  alpha channel: no”<<endl;

Get the pixels from the image:

const uchar *imgbits = in_img.bits();

Because it is unsigned char, I think QImage only supports 8-bit images.

Create a RGB image from pixels:

uchar* image_data = new uchar[img_w*img_h*3];

// set the pixel colors

QImage out_img(image_data, img_w, img_h, QImage::Format_RGB888);

And save it in Jpeg:

out_img.save(“foo.jpg”);

There should be enough bits in correct order. For RGB888 format, 3 char for each pixel as RED|GREEN|BLUE. For ARGB32, 4 char as BLUE|GREEN|RED|ALPHA.

Advertisements

Leave a comment

Filed under Qt

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s