【问题标题】:Create Image with repeating Existing Image使用重复现有图像创建图像
【发布时间】:2016-07-26 06:08:42
【问题描述】:

我有一个像素大小为 1024(宽)x 1024(高)像素的图像。假设用户想要重复该图像 2 次以创建另一个图像。所以,现在像素将是 2048 x 2048。我能够在代码中获取像素,但图像显示不完整。

如何使用 WPF 和 C# 做到这一点?

以上的更多场景 1)用户只想重复高度,而不是宽度,那么图像将是 1024 x 2048 2) 用户只想重复宽度 3 次,则图像为 3072 x 1024

【问题讨论】:

  • 但图像显示不完整。 你是什么意思?另外,请展示一些代码是如何完成的
  • @lok​​usking 的意思是,不是显示 1024*2048 的图像,而是仅显示 1024*1024 的图像。当然,我会发布代码。请给我一些时间。
  • 您只想显示“重复”的图像还是还想保存它?使用 ImageBrush 可以轻松实现仅显示。
  • @Clemens 我想保存它

标签: c# wpf


【解决方案1】:

做你想做的最简单的方法是创建一个具有所需大小的占位符图像:例如,如果你有一个图像 (Width, Height) 你可以创建 (n * Width, m * Height) 然后复制像素。

如果你需要的话,告诉我,我会给你一些代码。

private static Bitmap ResizeBitmap(Bitmap sourceBMP, Int32 widthMultiplier,
Int32 heightMultiplier)
    {
        var newWidth = sourceBMP.Width * widthMultiplier;
        var newHeight = sourceBMP.Height * heightMultiplier;
        var result = new Bitmap(newWidth, newHeight);
        using (Graphics g = Graphics.FromImage(result))
            g.DrawImage(sourceBMP, 0, 0, newWidth, newHeight);
        return result;
    }

    static void Main(string[] args)
    {
        var widthM = 2;
        var heightM = 2;

        var image = (Bitmap)Image.FromFile(@"E:\YOUR_IMAGE_HERE.png", true);

        var newImage = ResizeBitmap(image, widthM, heightM);
        for(var i=0; i<image.Width;++i)
            for(var j=0; j<image.Height;++j)
            {
                var pixelToCopy = image.GetPixel(i, j);
                for (var k = 0; k < widthM; ++k)
                    for (var l = 0; l < heightM; ++l)
                        newImage.SetPixel(k * image.Width + i,
                            l * image.Height + j,
                            pixelToCopy);
            }
        newImage.Save(@"E:\NEW_BIG_IMAGE_HERE.png", ImageFormat.Png);
    }
}

顺便说一下,GetPixel 和 SetPixel 很慢。所以你可能会采用一些不安全的代码并用它重写循环。参见MSDN的示例

【讨论】:

  • 这正是我的想法。能否请您提供一些代码。
  • 您可能还想使用画笔 (stackoverflow.com/questions/2675246/repeat-image-in-c-sharp),但对于您的问题,手写代码和画笔的作用方式相同。
  • 是的,等一两分钟)
  • 我为位图添加了一些代码。我不太确定这段代码是健壮的还是最优的。但如果你不需要闪电般的速度,你可以使用它。
  • 感谢您的快速帮助
猜你喜欢
  • 2017-09-13
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 2013-11-01
  • 1970-01-01
  • 2012-10-14
  • 2011-08-08
  • 1970-01-01
相关资源
最近更新 更多