2012-12-25 87 views
-3

我想创建多个200x200图像,并以它们为中心的数字并将它们与相应的文件名自动保存到一个文件夹中。只是,没有别的了。C#创建多个图像并保存它们

我觉得最好用一个图像盒试试这个,然后用一个循环写在它上面,但我无处可去。有任何想法吗?

回答

2

你是在正确的轨道上,花蕾。然而;要完成你想要的任务,你需要调用'Graphics'类,这个类可以在System.Drawing命名空间中找到。

你想完成的任务很容易。通过你想要的图像

第一循环创建

比方说,你要5张图片

...叫for循环!

for (int I = 0; I < 5; I++) { } 

在循环内部我们要创建一个200x200的图像,可以编辑。 我更喜欢'位图'类来完成这一点。

创建位图后,我将为它创建图形。 然后,我将绘制大约的字符串。中心。如果你想100%的中心,你可以使用MeasureString函数

最终代码:

for (int I = 0; I < 5; I++) { 
    Bitmap B = new Bitmap(200, 200); 
    Graphics G = Graphics.FromImage(B); 
    G.DrawString(I.ToString(), this.Font, Brushes.Black, new PointF(100.0f, 100.0f); 
    B.Save(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolders.Desktop), I + ".png"))) // Save on the desktop 
} 

我还没有试过这种代码,但我认为它的工作原理。可能需要一些修改:)

+1

这不会将文本放在死点中,而是从中心开始绘制它。所以需要一个'StringFormat'或者将它定位在死点的东西。只是指出它:) – Cheesebaron

+0

非常感谢,但..'最好的重载方法匹配'System.Drawing.Graphics.DrawString(字符串,System.Drawing.Font,System.Drawing.Brush,System.Drawing.RectangleF) '有一些无效的参数','不能从'int'转换为'string'','不能从'System.Drawing.Point'转换为'System.Drawing.RectangleF'' ..全部在线G.DrawString –

+0

两个秒。我会修复它:) – dotTutorials

0

对不起只拿到了我的电话......

在伪代码

创建一个循环。

Inside the loop create a bitmap 
    // for i=0... 
    // using (var BMP = new bitmap(dimensions)) 
    { 
    // get graphics 
     Using (graphics g = graphics.fromimage(BMP)) 
    { 
    // draw text 
    Text render.draw text() 
    // save image 
    } 
    } 
0

这可能是因为有一种方法做艰苦的工作是简单的:

public void CreateImageWithText(string text) 
{ 
    using (var b = new Bitmap(200, 200)) 
    { 
     using (var g = new Graphics.FromImage(b)) 
     { 
      using (var f = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point)) 
      { 
       var strFormat = new StringFormat(); 
       strFormat.Alignment = StringAlignment.Center; 
       strFormat.LineAlignment = StringAlignment.Center; 

       g.DrawString(text, f, Brushes.Blue, new Rectangle(0,0,200,200), strFormat); 
      } 
     } 
     b.Save("C:\\image.jpg", ImageFormat.Jpeg); 
    } 
} 

,然后在for循环做:

for (var i = 0; i < 5; i++) 
    CreateImageWithText(string.Format("{0}", i)); 

记住要正确处理您的Bitmap的s,GraphicsFont实例,如果你打算多次调用它。这是我的方法中的使用语句。

+0

谢谢,但我在这里得到两个错误..“名称'ImageFormat'不存在于当前上下文中”和“System.Drawing.Graphics.FromImage(System.Drawing.Image) '是一种'方法',但像“类型”一样使用。 –

+0

看起来像我不得不指定System.Drawing.Imaging具体..但是,我仍然无法摆脱第二个错误。''System.Drawing.Graphics.FromImage(System.Drawing.Image)'是一个'方法“,但像”类型“一样使用。 –

+0

我把这些与@dotTutorials'结合在一起,现在工作:)再次感谢! –