【发布时间】:2011-01-20 23:04:49
【问题描述】:
作为我 ongoing quest 为实验生成刺激的一部分,我遇到了一个奇怪的问题。
这次想要的结果是通过将图像分成大小相等的片段然后随机交换这些片段来“洗牌”图像。这在最初的测试中运行良好,我很快就忘记了这个程序。然而,当我的同事用她的图像进行尝试时,这些片段突然变得比它们应该的要小。
为了说明问题,我用阴影画笔填充了每个分段矩形:
图像对 A 显示了我从测试图像(从 facebook 下载)的初始结果。图像对 B 显示了应用于我同事测试图像的相同操作;请注意,阴影区域之间有间隙。在我在 GIMP 中修改原始图像并重新保存后,第三对图像显示相同的效果。 (我最初这样做是为了看看方向是否有任何影响 - 它没有。)
在我看来,从 GIMP 导出图像的过程会影响图像的某些属性,从而导致尺寸被错误地解释。有什么方法可以检测和纠正这个问题吗?
我的代码(为您的理智而编辑):
this.original = Image.FromFile(this.filename);
Image wholeImage = (Image)this.original.Clone();
int segwidth = (int)Math.Floor((double)(this.original.Width / segsX));
int segheight = (int)Math.Floor((double)(this.original.Height / segsY));
int segsCount = segsX * segsY;
Image[] segments = new Image[segsCount];
for (i = 0; i < segsCount; i++)
{
x = (i % segsX);
y = (int)Math.Floor((double)(i / segsX));
segments[i] = Crop(wholeImage, new Rectangle(x * segwidth, y * segheight, segwidth, segheight), (i%2>0));
}
// Call to an array shuffling helper class
using (Graphics g = Graphics.FromImage(wholeImage))
{
for (j = 0; j < segsCount; j++)
{
x = (j % segsX);
y = (int)Math.Floor((double)(j / segsX));
insertPoint = new Point(x * segwidth, y * segheight);
g.DrawImage(segments[j], insertPoint);
}
}
wholeImage.Save(this.targetfolder + Path.DirectorySeparatorChar + aggr_filename, ImageFormat.Png);
// The cropping function (including the hatch generation, which would be commented out when no longer needed)
static private Image Crop(Image wholeImage, Rectangle cropArea, Boolean odd = true)
{
Bitmap cropped = new Bitmap(cropArea.Width, cropArea.Height);
Rectangle rect = new Rectangle(0, 0, cropArea.Width, cropArea.Height);
System.Drawing.Drawing2D.HatchBrush brush;
if (odd)
{
brush = new System.Drawing.Drawing2D.HatchBrush(System.Drawing.Drawing2D.HatchStyle.Plaid, Color.Red, Color.Blue);
}
else
{
brush = new System.Drawing.Drawing2D.HatchBrush(System.Drawing.Drawing2D.HatchStyle.Plaid, Color.Beige, Color.CadetBlue);
}
using(Graphics g = Graphics.FromImage(cropped))
{
g.DrawImage(wholeImage, rect, cropArea, GraphicsUnit.Pixel);
g.FillRectangle(brush, rect);
}
return cropped as Image;
}
【问题讨论】:
-
对 Image 实例使用 using(this.original = Image.FromFile(this.filename)){...}。这不会解决问题,否则会导致内存泄漏。
-
啊,谢谢CaptainPlanet!仍然不是 C# 原生... :)
标签: c# graphics image-processing