2012-12-25 70 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'結合在一起,現在工作:)再次感謝! –