我在屏幕上繪製了一個Graphics對象,並且需要將其保存到png或bmp文件中。圖形似乎不直接支持,但它必須以某種方式可能。將System.Drawing.Graphics保存爲png或bmp
步驟是什麼?
我在屏幕上繪製了一個Graphics對象,並且需要將其保存到png或bmp文件中。圖形似乎不直接支持,但它必須以某種方式可能。將System.Drawing.Graphics保存爲png或bmp
步驟是什麼?
將其複製到Bitmap
,然後調用位圖的Save
方法。
請注意,如果你是字面上在屏幕上繪圖(通過抓取屏幕的設備上下文),那麼唯一的辦法救你剛纔畫的屏幕是由繪圖的逆過程屏幕至 a Bitmap
。這是可能的,但直接繪製到位圖(使用您用於繪製屏幕的相同代碼)顯然會更容易。
您可能正在繪製圖像或控件。如果使圖像使用
Image.Save("myfile.png",ImageFormat.Png)
如果在控制使用Control.DrawToBitmap()繪圖,然後返回的圖像保存爲上方。
感謝您的更正 - 我不知道你可以直接畫到屏幕上。
你*可以*使用圖形直接繪製到屏幕上,圖形具有一個構造函數來獲取設備上下文 - 您所需要的只是屏幕的設備上下文。 – MusiGenesis 2010-05-28 12:27:18
謝謝你,我從來沒有想過嘗試直接畫畫! – 2010-05-28 12:31:10
我實際上會推薦*不*直接畫到屏幕上,因爲這樣做確實沒有意義。 – MusiGenesis 2010-05-28 12:57:07
Graphics graph = CreateGraphics();
Bitmap bmpPicture = new Bitmap("filename.bmp");
graph.DrawImage(bmpPicture, width, height);
下面是代碼:
Bitmap bitmap = new Bitmap(Convert.ToInt32(1024), Convert.ToInt32(1024), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
// Add drawing commands here
g.Clear(Color.Green);
bitmap.Save(@"C:\Users\johndoe\test.png", ImageFormat.Png);
如果你的顯卡是一個形式,你可以使用這個:
private void DrawImagePointF(PaintEventArgs e)
{
... Above code goes here ...
e.Graphics.DrawImage(bitmap, 0, 0);
}
此外,保存在網頁上,你可以使用這個:
MemoryStream memoryStream = new MemoryStream();
bitmap.Save(memoryStream, ImageFormat.Png);
var pngData = memoryStream.ToArray();
<img src="data:image/png;base64,@(Convert.ToBase64String(pngData))"/>
圖形對象是一個GDI +繪圖表面。他們必須有一個附加的設備上下文來繪製,即表單或圖像。
我不明白這是如何回答這個問題的,即採用GRAPHICS對象,並將其複製到位圖中。這段代碼似乎做了OPPOSITE。 (我有一種情況,一個「圖形」被傳遞給一個方法,並且「圖形」的來源在代碼中不能被訪問,只有「圖形」本身。) – ToolmakerSteve 2015-04-13 18:42:18
試試這個,工作正常,我...
private void SaveControlImage(Control ctr)
{
try
{
var imagePath = @"C:\Image.png";
Image bmp = new Bitmap(ctr.Width, ctr.Height);
var gg = Graphics.FromImage(bmp);
var rect = ctr.RectangleToScreen(ctr.ClientRectangle);
gg.CopyFromScreen(rect.Location, Point.Empty, ctr.Size);
bmp.Save(imagePath);
Process.Start(imagePath);
}
catch (Exception)
{
//
}
}
對於未來的讀者:儘管這個問題的標題,這個答案並不表明如何保存任意Graphics對象的圖像。也就是說,圖形或位圖中沒有「將它(圖形實例)複製到位圖」的功能。從最後一句開始,它可能是指'Graphics g = Graphics.FromImage(bitmap)',然後渲染爲** graphics(g),而不是原始圖形對象。然後你可以做位圖。保存你已經渲染的東西。 – ToolmakerSteve 2015-04-13 19:02:51