0

I need to convert QImage to an array where each pixel is represented by three integers(channels). So I'm trying to achieve this with fillowing code:

void Processor::init(QImage *image){
QColor* c = new QColor();

int i,j;
int local_ind;

x = image->width();
y = image->height();

if(this->img!=NULL)
    delete [] this->img;
this->img = new int[ x * y * 3];

for( i = 0 ; i < y ; i++ )
    for( j = 0 ; j < x ; j++ ){
        c->setRgb(image->pixel(j, i));
        local_ind = i * x + j * 3;
        this->img[local_ind + 0] = c->red();
        this->img[local_ind + 1] = c->green();
        this->img[local_ind + 2] = c->blue();
    }
delete c;
}

void Processor::flush(QImage *image){

QColor* c = new QColor();
QRgb color;

int i, j;
int local_ind;

for( i = 0 ; i < y ; i++ )
    for( j = 0 ; j < x ; j++ ){

        local_ind = i * x + j * 3;
        color = qRgb(this->img[local_ind + 0],
                     this->img[local_ind + 1],
                     this->img[local_ind + 2]);

        image->setPixel(j, i, color);
    }

delete c;
}

Both functions are seem to work fine, as I can see via debugger, but when I call them one after the other (just copy info from QImage to array and backwards), result is a bit wierd. Whole image consists of three repeated images: a third of original image (blue, green and red channels of source image). I guess I just used setPixel in a wrong way so the format of QImage is not observed or smth.

I use QImage RGB32 format, if it really important here.

PS. Sorry for my English, corrections are welcome)

Roman
  • 1,396
  • 4
  • 15
  • 39
  • Are you aware that QImage already has this functionality? `QImage ( uchar * data, int width, int height, Format format )` and `const uchar * QImage::constBits () const` – kfunk Feb 12 '13 at 00:03
  • I am now. Thanks a lot. I'm gonna try it later and see if it is what I really need. But anyway, why do I get the result I described? Just out of curiosity. – Roman Feb 12 '13 at 04:52

1 Answers1

1

The issue is that you are using

 local_ind = i * x + j * 3;

But in your buffer each pixel take 3 bytes. So the you need to use instead

 ( i * x + j ) * 3

btw: Why are you using x for height and y for width? This is not intuitive.

UmNyobe
  • 22,539
  • 9
  • 61
  • 90