2015-02-10 69 views
1

我正在尋找快速方式圖片中的圖片轉換爲字節數組。c#如何將pictureBox.Image轉換爲字節數組?

我看到了這段代碼,但我不需要它。因爲圖像的圖片框是從數據庫讀取的數據。 所以我不知道的imageformat

public byte[] imageToByteArray(System.Drawing.Image imageIn) 
{ 
    MemoryStream ms = new MemoryStream(); 
    imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); 
    return ms.ToArray(); 
} 

所以請讓我知道,如果有人知道快速的方式

謝謝!玩的很開心!

+0

您必須「知道」ImageFormat。它將被保存的格式,由您來決定。它不依賴於源格式。 – Marek 2015-02-10 08:36:52

+0

@Marek,他可能實際上應該有'imageIn.PixelFormat'屬性的源格式。 ()) – DarkUrse 2015-02-10 08:50:23

回答

1

這可能不是你正在尋找什麼,但它可能對你有用,如果你正在尋找性能做一些像素操作..我認爲這將是值得一提的在這裏。

既然你已經加載的圖像與Image imageIn實際上你可以直接訪問圖像緩衝區而不做任何副本,因此節省了時間和資源:

public void DoStuffWithImage(System.Drawing.Image imageIn) 
{ 
    // Lock the bitmap's bits. 
    Rectangle rect = new Rectangle(0, 0, imageIn.Width, imageIn.Height); 
    System.Drawing.Imaging.BitmapData bmpData = 
        imageIn.LockBits(rect, System.Drawing.Imaging.ImageLockMode.Read, 
        imageIn.PixelFormat); 

    // Access your data from here this scan0, 
    // and do any pixel operation with this imagePtr. 
    IntPtr imagePtr = bmpData.Scan0; 

    // When you're done with it, unlock the bits. 
    imageIn.UnlockBits(bmpData); 
} 

對於一些詳細信息,看看這個MSDN

ps:這個bmpData.Scan0當然會讓你只能訪問像素有效載荷。又名,沒有標題!

+0

參數缺失此處Dim圖像作爲字節()= GetBytes(ListView2.Items(索引).SubItems(8).Text) Dim converter As New ImageConverter() PictureBox1.Image = DirectCast(converter.ConvertFrom(picture) ,Image)' – 2015-12-27 21:50:52

2

試着閱讀:http://www.vcskicks.com/image-to-byte.php 希望它能幫助你。

編輯:我想你有你的代碼從Fung鏈接鏈接剪斷。如果是的話,就有答案了對你的問題就在那裏,你只需要向下滾動網頁...

第二編輯(從頁代碼片段 - 感謝信息費多爾):

public static byte[] ImageToByte(Image img) 
{ 
    ImageConverter converter = new ImageConverter(); 
    return (byte[])converter.ConvertTo(img, typeof(byte[])); 
} 
相關問題