2009-10-26 55 views
7

在Visual Studio 2008中工作我試圖在PNG圖像上繪製並再次保存該圖像。C#中的PNG圖像問題

我做到以下幾點:

private Image img = Image.FromFile("file.png"); 
private Graphics newGraphics; 

並在構造函數:

newGraphics = Graphics.FromImage(img); 

構建解決方案沒有給出錯誤。當我嘗試運行它,我得到這個:

圖形對象不能創建從具有索引 像素格式的圖像 。

我沒有太多的在C#中使用圖像的經驗。這是什麼意思,我該如何補救?

編輯:通過調試,Visual Studio告訴我,圖像有一個format8bppindexed像素格式。

所以,如果我不能使用Graphics類,我該用什麼?

編輯2:在閱讀this後,我認爲可以安全地假設在使用GDI +時,我更好地堅持JPG文件,不是嗎?

EDIT3:我使用語句:

using System; 
using System.Collections.Generic; 
using System.Drawing; 
using System.Drawing.Imaging; 
using System.Windows.Forms; 
+0

使用這種方法的任何運氣? http://www.c-sharpcorner.com/UploadFile/rrraman/graphicsObject08232007102733AM/graphicsObject.aspx – Greg 2009-10-26 14:55:58

+0

我一直在用Graphics對象來使用PNG文件。發佈一個鏈接到您正在使用的PNG文件,我們會看到它有什麼問題。 – MusiGenesis 2009-10-26 14:57:25

+0

內部GDI與Bitmaps一起使用,JPG被壓縮,並不是真的有很大的壓縮圖像來處理原始數據。您的圖像是8bppIndexed,這是一種位圖格式,其中顏色存儲在調色板中,而不是像素數據。 Graphics對象不能直接修改像素值,因爲這不會改變它。你需要將它轉換爲24bppRGB – badbod99 2009-10-26 15:12:16

回答

9

如果沒有支持索引你的運氣設法吸引到圖像,因爲明顯的GDI +圖形對象不支持索引圖像的PNG更好的PNG庫。

如果您不需要使用索引PNG,則可以捕獲該錯誤並使用第三方實用程序將您的輸入轉換爲常規RGB PNG。

編輯:

我發現這個鏈接http://fci-h.blogspot.com/2008/02/c-indexed-pixel-problem.html,給出了一個方法來繪製圖像上,但它不會影響原來,只是一個副本,你可以保存()如果您需要。

萬一鏈路出現故障:

Bitmap bm = (Bitmap) System.Drawing.Image.FromFile("Fci-h.jpg",true); 
Bitmap tmp=new Bitmap (bm.Width ,bm.Height); 
Graphics grPhoto = Graphics.FromImage(tmp); 
grPhoto.DrawImage(bm, new Rectangle(0, 0, tmp.Width , tmp.Height), 0, 0, tmp.Width , tmp.Height , GraphicsUnit.Pixel); 
+0

GDI +不支持從它們創建圖形上下文,這對OP具有相同的效果。無論如何,這是解決方案解決方案的一個體面的鏈接: http://fci-h.blogspot.com/2008/02/c-indexed-pixel-problem.html – 2009-10-26 14:49:38

+0

該blogpost做到了。謝謝。 – KdgDev 2009-10-26 15:11:25

12

您無法從索引圖像格式創建一個圖形(PNG,GIF,...)。 您應該使用位圖(文件或將圖像轉換爲位圖)。

Image img = Image.FromFile("file.png"); 
img = new Bitmap(img); 
newGraphics = Graphics.FromImage(img); 
+0

確實,死鏈接在那裏。 – KdgDev 2009-10-26 14:48:43

+0

也許我沒有所需的「使用」語句,但Visual Studio無法識別該功能。 – KdgDev 2009-10-26 14:59:34

+0

哪個功能? – Guillaume 2009-10-26 15:09:00