How do I convert a Bitmap to byte[]?

后端 未结 3 1711
囚心锁ツ
囚心锁ツ 2020-12-20 11:34

Basically I am inserting an image using the listviews inserting event, trying to resize an image from the fileupload control, and then save it in a SQL database using LINQ.<

相关标签:
3条回答
  • 2020-12-20 12:19

    If you've got a MemoryStream already, just call MemoryStream.ToArray to get the data out.

    0 讨论(0)
  • 2020-12-20 12:19

    Assuming, that your bitmap is bmp

    byte[] data;
    using(System.IO.MemoryStream stream = new System.IO.MemoryStream()) {
       bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
       stream.Position = 0;
       data = new byte[stream.Length];
       stream.Read(data, 0, stream.Length);
       stream.Close();
    }
    
    0 讨论(0)
  • 2020-12-20 12:26

    You should be able to change this block to

            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            newBMP.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
    
            PHJProjectPhoto myPhoto =
                new PHJProjectPhoto
                {
                    ProjectPhoto = stream.ToArray(), // <<--- This will convert your stream to a byte[]
                    OrderDate = DateTime.Now,
                    ProjectPhotoCaption = ProjectPhotoCaptionTextBox.Text,
                    ProjectId = selectedProjectId
                };
    
    0 讨论(0)
提交回复
热议问题