[Qt-interest] memory control in QImage bits() function
Mehmet Kaplan
mehmetkpln at gmail.com
Wed Mar 17 13:54:57 CET 2010
Mehmet Kaplan wrote:
> Hi to all,
> I'm trying to copy the image data in QImage image class to another
> pointer like given below:
>
>
> uchar* newData = qImage->bits();
>
>
> in definition of bits() function it is written that:
> "Note that QImage uses implicit data sharing. This function performs a
> deep copy of the shared pixel data, thus ensuring that this QImage is
> the only one using the current return value."
>
> For example when i use a big image like 300 mb, in the lines above
> memory usage is increased by totally 600 mb, which proves the
> definiton of bits() function.
> But after a statement like this
> for(int i=0;i<100000;i++)
> newData [i]=0;
>
> original QImage is also changes (first few lines become black because
> of zero value).
>
> To solve this problem i changed the code like this:
> uchar * newData = new uchar[qImage->numBytes];
> uchar* uc = qImage->bits();
> memcpy ( newData, uc, qImage->numBytes );
>
> But with these lines memory usage increases 600 mb (300 mb each for
> first and second line).
> Isn't there any solution for creating new data (new pointer) and spend
> 300 mb for this operation.
It seems likely that you have two QImages sharing the same internal
data, so that the call to bits() causes a deep copy, and then obviously
you are allocating your own memory on top of that.
The easiest way to get the behavior you want would be to have a const
QImage so that bits() does not cause a deep copy. So:
const QImage *qImage = ...
const uchar *bits = qImage->bits();
uchar *newData = new uchar[qImage->numBytes()];
memcpy( newData, bits, qImage->numBytes() );
>> thanks a lot, this suggestion solves the problem.
It would also probably be a better idea not to manually allocate the new
memory and use a QByteArray or some other container instead.
Dan
More information about the Qt-interest-old
mailing list