Mike
Mike

Reputation: 91

Writing repeated values in array quickly

I have a quick question on writing to a file quickly using C++. I am working with a grayscale color image, thus I store a single 8-bit value (ranging from 0-255) in an array for each x,y position of the image.

However, after I've read in these, values, I need to write them out as an RGB format, thus storing 3, 8 bit values for each x,y position. The intuitive thing to do is then just write each value 3 times in a row before moving to the next value.

Here is an example code of what I am doing:

for(int f = 0; f < totalFrames; f++){
    for(int i = 0; i < imageSize; i++){
        int index = i +(f*320*240);
        myFile << pixelBuffer[index];
        myFile << pixelBuffer[index];
        myFile << pixelBuffer[index];
    }
}

If the values in the array were all stored contiguously, I could simply use:

myFile.write((const char*)pixelBuffer, totalFrames * imageSize); 

But that is not the case, so I wonder if there is a way I can offset where I am writing each value to, so I can just make three write calls per frame, rather than imageSize*3 writes.

Upvotes: 0

Views: 100

Answers (2)

Galik
Galik

Reputation: 48635

You could try something like this.

Write your pixels to a memory buffer std::stringstream and then dump that to a file:

std::stringstream ss;

for(int f = 0; f < totalFrames; f++){
    for(int i = 0; i < imageSize; i++){
        int index = i +(f*320*240);
        ss << pixelBuffer[index];
        ss << pixelBuffer[index];
        ss << pixelBuffer[index];
    }
}

std::ofstream myFile("myfile.pix");

myfile << ss.rdbuf();

EDIT:

You can also set the size of the internal buffer to avoid reallocation:

char buffer[size_of_image];
ss.rdbuf()->pubsetbuf(buffer, size_of_image);

Upvotes: 2

kfsone
kfsone

Reputation: 24269

Either transfer the data into a for-writing array, or use memory-mapped IO (if you're working with Windows CreateFileMapping and MapViewOfFileEx, Linux/Mac uses mmap).

using pixel_t = /* what type is your data? */;
pixel_t* writeBuffer = new pixel_t[imageSize];
pixel_t* writePtr = writeBuffer;

for(size_t f = 0; f < totalFrames; f++){
    for(size_t i = 0; i < imageSize; i++){
        const size_t index = i + (f * 320 * 240);
        const pixel_t data = pixelBuffer[index];
        *writePtr++ = data;
        *writePtr++ = data;
        *writePtr++ = data;
    }
    myFile.write((const char*)writeBuffer, imageSize); 
}

delete[] writeBuffer;

Using the memory mapped IO, you'd do very much the same thing, you just wouldn't need the "write" statement.

Upvotes: 4

Related Questions