为什么这种Bitmap的使用更快?

时间:2017-01-05 20:22:39

标签: c# .net image-processing bitmap

在我的项目中,我有两个不同的类需要解析一个Bitmap。这些类在一个事物上解析Bitmaps,一个解析器剪切Bitmap,删除部分图像而另一个没有。我注意到两个解析器之间的速度差异很大。我发现原因是在快速解析器中我使用

Bitmap b = originalBitmap.Clone(clipBounds, originalBitmap.PixelFormat);

然后处理b。我尝试只将克隆部分添加到慢速解析器中,但没有效果。然而,将原始图像编辑为宽1像素,然后使用Clone()切割宽度,使慢速解析器和快速解析器一样快。使用秒表测量的差值为500 ms vs~20 ms。

如何使用Bitmap.Clone(Rectangle rect, PixelFormat format)使解析器更快?

完整代码: (以前很慢的解析器)

private void parseImage(string file, Size tileSize) {

        Console.WriteLine("Parsing palette (Single Threaded)...");
        Stopwatch sw = new Stopwatch();
        sw.Start();

        Bitmap bmp = TextureLoader.LoadTexture(file, TextureLoader.TextureType.Palette);

        //Cutting away the added 1 pixel width (161 to 160 wide)
        bmp = bmp.Clone(new Rectangle(0, 0, 160, 1024),bmp.PixelFormat);

        int tilesWide = bmp.Width / tileSize.Width;
        int tilesHigh = bmp.Height / tileSize.Height;
        tiles = new Bitmap[tilesWide * tilesHigh];
        int tileID = 0;

        Rectangle cloneRect;
        for (int y = 0; y < tilesHigh; y++) {
            for (int x = 0; x < tilesWide; x++) {
                cloneRect = new Rectangle(x * tileSize.Width, y * tileSize.Height, tileSize.Width, tileSize.Height);
                tiles[tileID++] = bmp.Clone(cloneRect, bmp.PixelFormat);
            }
        }
        NumTiles = tileID;
        sw.Stop();
        Console.WriteLine("\t-- Finished parsing palette. Loaded {0} tiles in {1} ms", tileID, sw.ElapsedMilliseconds);
    }

快速解析器:

private void parseSheet(string file, Vector2 spriteSize, Rectangle clip) {
        Console.WriteLine("Starting parse of spritesheet: {0}", file);
        Stopwatch sw = new Stopwatch();
        sw.Start();
        Bitmap bmp = TextureLoader.LoadTexture(file, TextureLoader.TextureType.Sprite);
        bmp = bmp.Clone(clip, bmp.PixelFormat);

        _spriteTileSize = spriteSize;
        _numTiles = new Size(
            (int)(bmp.Width / spriteSize.X),
            (int)(bmp.Height / spriteSize.Y)
            );
        _spriteTiles = new Bitmap[_numTiles.Width * _numTiles.Height];

        Rectangle r;
        int tileID = 0;
        for (int y = 0; y < _numTiles.Height; y++) {
            for (int x = 0; x < _numTiles.Width; x++) {
                r = new Rectangle((int)(x * spriteSize.X), (int)(y * spriteSize.Y), (int)(spriteSize.X), (int)(spriteSize.Y));
                _spriteTiles[tileID++] = bmp.Clone(r, bmp.PixelFormat);
            }
        }

        sw.Stop();
        Console.WriteLine("\t-- Finnished parsing. Loaded {0} sprite tiles in {1} ms", tileID, sw.ElapsedMilliseconds);
    }

0 个答案:

没有答案