In this post we will learn how to re-size an image stored on file or in memory. Cascades provide Image class to perform loading of images but it do not have any support for manipulating the image especially re-sizing of image. But we have a class QImage from Qt that support re-sizing of images. So first lets see how we can load image through QImage class
Loading from file
We will use a constructor that takes file name (QString) as a parameter. We can optionally pass format as a char* parameter but its better to skip that so QImage will detect format from the filename
Loading from in memory data
QImage provides another constructor to load image data stored in memory .It takes pointer to data (as uchar*) , width ,height and format as parameter. We will load RGB32 image data
After re-sizing you can save the image like this
For the complete reference of QImage refer to the following link
http://qt-project.org/doc/qt-4.8/qimage.html
Loading image
QImage has many overloaded constructors for loading images from different sources or just create an empty QImage of given height and width. We will cover two constructors here, one for loading image from file and other to load image from image data in memory.Loading from file
We will use a constructor that takes file name (QString) as a parameter. We can optionally pass format as a char* parameter but its better to skip that so QImage will detect format from the filename
QImage img("asset:///testimage.jpg");
Loading from in memory data
QImage provides another constructor to load image data stored in memory .It takes pointer to data (as uchar*) , width ,height and format as parameter. We will load RGB32 image data
uchar* myImageData=getImageData(&width,&height);
QImage img(myImageData,width,height,QImage::Format_RGB32);
Re-sizing image
Now we have image data loaded in QImage instance. We can use scaled method of QImage to re-size the image.It has two overloads we will use the one that accepts width,height,aspect ratio (optional).QImage resizedImage=img.scaled(250,250,Qt::KeepAspectRatio);As we have used Qt::KeepAspectRatio the height is not guaranteed to be 250 (as we have passed) instead it will be calculated by QImage to not mess up the aspect ratio.
After re-sizing you can save the image like this
resizedImage.save("file:///path_to_your_file");
For the complete reference of QImage refer to the following link
http://qt-project.org/doc/qt-4.8/qimage.html
Comments
Post a Comment
Share your wisdom