2011-09-23 81 views
6

我通過該代碼捕獲截圖進行保存。通過C#發送屏幕截圖

Graphics Grf; 
Bitmap Ekran = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppPArgb); 
Grf = Graphics.FromImage(Ekran); 
Grf.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); 
Ekran.Save("screen.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); 

然後發送該保存的屏幕截圖作爲電子郵件:

SmtpClient client = new SmtpClient(); 
MailMessage msg = new MailMessage(); 
msg.To.Add(kime); 
if (dosya != null) 
{ 
    Attachment eklenecekdosya = new Attachment(dosya); 
    msg.Attachments.Add(eklenecekdosya); 
} 
msg.From = new MailAddress("[email protected]", "Konu"); 
msg.Subject = konu; 
msg.IsBodyHtml = true; 
msg.Body = mesaj; 
msg.BodyEncoding = System.Text.Encoding.GetEncoding(1254); 
NetworkCredential guvenlikKarti = new NetworkCredential("[email protected]", "*****"); 
client.Credentials = guvenlikKarti; 
client.Port = 587; 
client.Host = "smtp.live.com"; 
client.EnableSsl = true; 
client.Send(msg); 

我想這樣做:如何通過SMTP協議直接發送截圖作爲電子郵件沒有保存?

回答

7

將位圖保存爲流。然後將流附加到您的郵件。例如:

System.IO.Stream stream = new System.IO.MemoryStream(); 
Ekran.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); 
stream.Position = 0; 
// later: 
Attachment attach = new Attachment(stream, "MyImage.jpg"); 
+3

記住圍繞這些調用與使用塊,這樣你就不會出現內存泄漏,或致電.Dispose()方法來釋放記憶。 – Digicoder

+0

對不起,我在編輯我的答案,當我最終發佈時,我看到你的是一樣的。你喜歡我刪除我的嗎? :)無論如何,+1爲你 – Marco

+0

是的 - Digicoder提出了一個重要的觀點。通過在所有IDisposable對象上使用「使用」塊,可以改進原始代碼。爲了簡單起見,我把它放在外面,而且正確設置「使用」塊將需要修改所有原始代碼。 –

2

使用此:

using (MemoryStream ms = new MemoryStream()) 
{ 
    Ekran.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); 
    using (Attachment att = new Attachment(ms, "attach_name")) 
    { 
     .... 
     client.Send(msg); 
    } 
} 
+0

別忘了附件也是一次性的...... –

+0

@詹姆斯:是的,你是對的:) – Marco