解码位图时的CPU数高

问题描述 投票:0回答:1

背景

我正在使用LodePNG将位图DIB转换为内存中的PNG。 LodePNG提供以下功能:

bool decode_bitmap(std::vector<unsigned char>& image, unsigned& w, unsigned& h, const std::vector<unsigned char>& bmp)
{
    if (bmp.size() <= 54/*minimum BMP header size*/)
    {
        return false;
    }

    // read width and height from BMP header
    w = bmp[18] + bmp[19] * 256;
    h = bmp[22] + bmp[23] * 256;

    // get the channel from the BMP header (we are parsing a 24-bit image header)
    if (bmp[28] != 24)
    {
        return false;
    }

    unsigned num_channels = bmp[28] / 8, scan_line_bytes = w * num_channels;
    if (scan_line_bytes % 4 != 0)
    {
        scan_line_bytes = (scan_line_bytes / 4) * 4 + 4;
    }

    unsigned data_size = scan_line_bytes * h, pixel_offset = bmp[10] + 256 * bmp[11];
    if (bmp.size() < data_size + pixel_offset)
    {
        // BMP file too small to contain all pixels
        return false;
    }

    image.resize(w * h * 4);
    for (unsigned y = 0; y < h; y++)
    {
        for (unsigned x = 0; x < w; x++)
        {
            // pixel start byte position in the BMP
            unsigned bmpos = pixel_offset + (h - y - 1) * scan_line_bytes + num_channels * x;
            // pixel start byte position in the new raw image
            unsigned newpos = 4 * y * w + 4 * x;
            // 24-bit image doesnt contain alpha-channel, so we can add it manually (PNG requirement)
            image[newpos + 0] = bmp[bmpos + 2]; //R
            image[newpos + 1] = bmp[bmpos + 1]; //G
            image[newpos + 2] = bmp[bmpos + 0]; //B
            image[newpos + 3] = 255;            //A
        }
    }
    return true;
}

问题

我遇到的问题是此函数使用太多的CPU(30-40%),无法在我的应用程序的发行版中使用。有什么办法可以加快此功能的速度,特别是for循环部分,以免消耗太多CPU?

随时建议任何替代方法-感谢您提供所有帮助!

c++ winapi lodepng
1个回答
0
投票
一些显而易见的事情浮现在脑海。让我们从原始代码开始:https://godbolt.org/z/vVjfFF
© www.soinside.com 2019 - 2024. All rights reserved.