如何将位图转换为字节数组?

15
基本上,我正在使用listviews插入事件插入图像,尝试调整来自fileupload控件的图像大小,然后使用LINQ将其保存在SQL数据库中。
我找到了一些代码来创建一个新位图,其中包含fileupload控件中的内容,但是这是将其存储在服务器上的文件中,来自此源代码, 但是我需要将位图保存回SQL数据库中,我认为我需要将其转换回byte[]格式。
那么,如何将位图转换为byte[]格式?
如果我做错了,请纠正我。
以下是我的代码:
            // Find the fileUpload control
            string filename = uplImage.FileName;

            // Create a bitmap in memory of the content of the fileUpload control
            Bitmap originalBMP = new Bitmap(uplImage.FileContent);

            // Calculate the new image dimensions
            int origWidth = originalBMP.Width;
            int origHeight = originalBMP.Height;
            int sngRatio = origWidth / origHeight;
            int newWidth = 100;
            int newHeight = sngRatio * newWidth;

            // Create a new bitmap which will hold the previous resized bitmap
            Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);

            // Create a graphic based on the new bitmap
            Graphics oGraphics = Graphics.FromImage(newBMP);

            // Set the properties for the new graphic file
            oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
            oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

            // Draw the new graphic based on the resized bitmap
            oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);



            PHJamesDataContext db = new PHJamesDataContext();

            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            newBMP.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
            stream.Position = 0;
            byte[] data = new byte[stream.Length];

            PHJProjectPhoto myPhoto =
                new PHJProjectPhoto
                {
                    ProjectPhoto = data,
                    OrderDate = DateTime.Now,
                    ProjectPhotoCaption = ProjectPhotoCaptionTextBox.Text,
                    ProjectId = selectedProjectId
                };

            db.PHJProjectPhotos.InsertOnSubmit(myPhoto);
            db.SubmitChanges();
3个回答

23

您应该能够更改此块

        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
            };

13

你给了我正确的答案,但我需要更详细的解释来实现它,还是谢谢你。 - the-undefined

6
假设您的位图是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();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接