2012-11-01 36 views
-1

我在做c#中的控制檯應用程序。在這個應用程序中,我必須創建一個png類型的位圖,並且它必須存儲在某個定義的路徑中(比如C:或D:驅動器)。如何在c的控制檯應用程序中將位圖保存爲png#

在Windows應用程序中,我有下面的代碼來創建一個位圖,它將顯示在一個圖片框中。

void CreateBitmap() 
{ 
    System.Drawing.Bitmap flag = new System.Drawing.Bitmap(10, 10); 
    for(int x = 0; x < flag.Height; ++x) 
     for(int y = 0; y < flag.Width; ++y) 
     flag.SetPixel(x, y, Color.White); 
     for(int x = 0; x < flag.Height; ++x) 
     flag.SetPixel(x, x, Color.Red); 
    pictureBox1.Image = flag; 
} 

如何使用控制檯應用程序創建並將其存儲在指定路徑中?

我已經改變了我的代碼如下,但仍存在錯誤:

static void CreatePng(string[] binvalues) 
{ 
    String aName = System.Reflection.Assembly.GetExecutingAssembly().Location; 
    String aPath = System.IO.Path.GetDirectoryName(aName); 
    string[] ExecDirectories = System.IO.Directory.GetDirectories(aPath); 

    System.Drawing.Bitmap flag = new System.Drawing.Bitmap(10, 10); 

    for (int x = 0; x < flag.Height; ++x) 
     for (int y = 0; y < flag.Width; ++y) 
      flag.SetPixel(x, y, Color.White); 
    for (int x = 0; x < flag.Height; ++x) 
     flag.SetPixel(x, x, Color.Red); 
    flag.Save(aPath, System.Drawing.Imaging.ImageFormat.Png); 
} 

它顯示在最後一行運行時錯誤的flag.save似乎出問題了嗎?

+1

HTTP://www.whathaveyoutried。com/ – Maarten

+1

@Marteen:你至少可以將這個鏈接打包成一個很好的評論......雖然我同意這個鏈接,它的目的,你的評論很糟糕,[並不真正有用](http:// meta .stackexchange.com /問題/ 147161 /因爲,當-是-HTTP-whathaveyoutried-COM-禁止)。 – Bobby

回答

1

使用相同的代碼和,而不是分配給一個PictureBox,呼籲位圖Save()方法:

flag.Save("yourpath", System.Drawing.Imaging.ImageFormat.Png); 

請注意,您可能需要參考您的控制檯應用程序添加到System.Drawing,因爲它在默認情況下不存在。

0

現在,我從來沒有用C#做過這件事,所以更傾向於有人可能會幫助,但這是我能夠找到的。

1)您需要將圖像數據存儲在Bitmap中。從事物的外表,你這樣做是已經與flag

2)你需要呼籲Bitmapsave()功能:

flag.Save(filename, ImageFormat.Png); 

3)filename將您定義的String。這很容易,因爲您可以簡單地讓應用程序提示用戶輸入路徑並將其保存。

有問題?

聲明:我從this page收到我的信息。關於拯救你可以挖掘的png的「正確」途徑有很多討論。

+0

嗨在這裏我已經改變了我的代碼,但仍然錯誤顯示 –

+0

你可以發佈我們的運行時錯誤?應該有一個堆棧跟蹤,詳細說明到底發生了什麼問題......可能缺少目錄,格式錯誤或找不到文件?還有別的嗎? – Grambot

+0

拋出的錯誤是:「在System.Drawing.dll中發生類型'System.Runtime.Interopservices.ExternalException'的未處理的異常」附加信息:GDI中發生的一般錯誤+ –

0

使用此:

flag.Save(filename, System.Drawing.Imaging.ImageFormat.Png); 
  1. 你並不需要將圖像添加到PictureBox。你有一個控制檯應用程序,並且PictureBox是一個視覺控制。
  2. 對於將來的問題,如果您花費最少的時間搜索SO或其他來源的答案,首先會回答問題
  3. 問題未標記爲正確。如果你想保存一個System.Drawing.Bitmap它不能被標記爲BitmapImage,因爲這隻適用於WPF。我改變了這一點。
0

你可以試試下面代碼 - :

public bool ResizeImage(string OriginalFilepath, string NewFilepath) 
{ 
    Bitmap original = (Bitmap)Image.FromFile(OriginalFilepath); 
    Bitmap resized = new Bitmap(original, new Size(Width,Height)); 
    resized.Save(NewFilepath.png);  
} 
相關問題