开发者

Writing Bitmap to string insted of FILE* or XImage to PNG

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

fwrite(&bmpFileHeader, sizeof(bmpFileHeader), 1, fp);
fwrite(&bmpInfoHeader, sizeof(bmpInfoHeader), 1, fp);
fwrite(p开发者_StackOverflow中文版Image->data, 4*pImage->width*pImage->height, 1, fp);

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

thanks;


Use memcpy instead of fwrite

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 update code, thaks @bdk for pointing out


For the in-memory copy, use memcpy as DReJ says, but if you want to save an image as a PNG, you could do worse than looking into a nice simple PNG library like LodePNG:

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

I wouldn't waste time re-doing the compression side of things myself if there was an easy alternative -- there are more important problems you can be working on.


EDIT - For what it's worth, my code to save PNGs using LodePNG looks like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜