Writing a bitmap to the string specified in the FILE * or XImage file in PNG

i converted the output XImage of my code to Bitmap, but the output file is massive, so I thought about compressing it with lzrw, I use this code to write a bitmap to a file

fwrite(&bmpFileHeader, sizeof(bmpFileHeader), 1, fp);
fwrite(&bmpInfoHeader, sizeof(bmpInfoHeader), 1, fp);
fwrite(pImage->data, 4*pImage->width*pImage->height, 1, fp);

anyway, I could write it to (char *) insted (FILE *), so can I use lzrw compression on it? or even better, a way to convert XImage to PNG directly ...

thank

+2
source share
2 answers

Use memcpyinsteadfwrite

char* tmp = buf;
memcpy(tmp, &bmpFileHeader, sizeof(bmpFileHeader));
tmp += sizeof(bmpFileHeader);
memcpy(tmp, &bmpInfoHeader, sizeof(bmpInfoHeader));
tmp += sizeof(bmpInfoHeader);
memcpy(tmp, pImage->data, 4*pImage->width*pImage->height);

EDIT: I am updating the code, thaks @bdk to indicate

+1
source

memcpy, DReJ, PNG, , PNG-, LodePNG:

http://members.gamedev.net/lode/projects/LodePNG/

, - , .


EDIT - , PNG LodePNG :

void PNGSaver::save_image24(const std::string& filename, const Image24_CPtr& image)
{
    std::vector<unsigned char> buffer;
    encode_png(image, buffer);
    LodePNG::saveFile(buffer, filename);
}

void PNGSaver::encode_png(const Image24_CPtr& image, std::vector<unsigned char>& buffer)
{
    int width = image->width();
    int height = image->height();
    const int pixelCount = width*height;

    // Construct the image data array.
    std::vector<unsigned char> data(pixelCount*4);
    unsigned char *p = &data[0];
    for(int y=0; y<height; ++y)
        for(int x=0; x<width; ++x)
        {
            Pixel24 pixel = (*image)(x,y);
            *p      = pixel.r();
            *(p+1)  = pixel.g();
            *(p+2)  = pixel.b();
            *(p+3)  = 255;
            p += 4;
        }

    // Encode the PNG.
    LodePNG::encode(buffer, &data[0], width, height);
}
0

All Articles