【问题标题】:Sampling an Image in C# with a TextureBrush repeatedly在 C# 中使用 TextureBrush 重复采样图像
【发布时间】:2013-02-15 18:53:36
【问题描述】:

所以我在 C# 中创建了一个程序,它获取图像并将其拆分为图块。我正处于想要拍摄大图像并将其切成不同的图块并保存每个图块的地步。我遇到的问题是它适用于第一个图块,但所有其他图块都是空白的,我不知道为什么。这是我正在砍的代码。

Graphics g;
Image tempTile;
TextureBrush textureBrush;
int currRow = 1;
int currCol = 1;
int currX = 0; //Used for splitting. Initialized to origin x.
int currY = 0; //Used for splitting. Initialized to origin y.

//Sample our new image
textureBrush = new TextureBrush(myChopImage);

while (currY < myChopImage.Height)
{
    while (currX < myChopImage.Width)
    {
        //Create a single tile
        tempTile = new Bitmap(myTileWidth, myTileHeight);
        g = Graphics.FromImage(tempTile);

        //Fill our single tile with a portion of the chop image
        g.FillRectangle(textureBrush, new Rectangle(currX, currY, myTileWidth, myTileHeight));

        tempTile.Save("tile_" + currCol + "_" + currRow + ".bmp");

        currCol++;
        currX += myTileWidth;

        g.Dispose();
   }

   //Reset the current column to start over on the next row.
   currCol = 1;
   currX = 0;

   currRow++;
   currY += myTileHeight;
}

【问题讨论】:

    标签: c# gdi+ gdi bmp windows-applications


    【解决方案1】:

    你有空白瓷砖的原因是这一行:

    g.FillRectangle(textureBrush, new Rectangle(currX, currY, myTileWidth, myTileHeight));

    坐标currX, currY 指定在图块上开始绘制的位置。在循环的第一次迭代之后,这些值超出了 tile 的范围。

    更好的方法可能是尝试使用Bitmap.Clone 裁剪图像

    while (currY < myChopImage.Height)
    {
        while (currX < myChopImage.Width)
        {
            tempTile = crop(myChopImage, new Rectangle(currX, currY, myTileWidth, myTileHeight));
            tempTile.Save("tile_" + currCol + "_" + currRow + ".bmp");
    
            currCol++;
            currX += myTileWidth;
       }
    
       //Reset the current column to start over on the next row.
       currCol = 1;
       currX = 0;
    
       currRow++;
       currY += myTileHeight;
    }
    

    crop 方法可能如下所示:

    private Bitmap crop(Bitmap bmp, Rectangle cropArea)
    {
       Bitmap bmpCrop = bmp.Clone(cropArea, bmp.PixelFormat);
       return bmpCrop;
    }
    

    【讨论】:

    • 是的,效果很好,非常感谢你给我一个解决问题的方法。
    【解决方案2】:

    是不是你的:

        g.FillRectangle(textureBrush, new Rectangle(currX, currY, myTileWidth, myTileHeight));
    

    call 正在尝试填充超出其范围的坐标?

    例如,tile 是 10x10,首先调用: g.FillRectangle(textureBrush, new Rectangle(0, 0, 10, 10));

    在第二次通话中,你正在有效地做

        g.FillRectangle(textureBrush, new Rectangle(10, 0, 10, 10));
    

    哪个在 tempTile 的范围之外?

    fillRectangle 调用应始终为0,0,myTileWidth,myTileHeight,它是您要更改的textureBrush 中的源位置。不知道你会怎么做,也许使用翻译变换来翻译它的相反方向?

    【讨论】:

    • 我不相信它超出了界限。抱歉,您的回答对我有帮助。
    • 你不相信?作为测试,在该调用中尝试 currx/2, curry/2,看看它是否在您保存的图像中绘制了 1/4 的图块。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 2011-04-19
    • 1970-01-01
    • 2011-07-27
    相关资源
    最近更新 更多