Pregunta

Básicamente estoy insertando una imagen usando el evento de inserción de vistas de lista, tratando de cambiar el tamaño de una imagen desde el control de carga de archivos, y luego guardarla en una base de datos SQL usando LINQ.

Encontré un código para crear un nuevo mapa de bits del contenido en el control de carga de archivos, pero esto fue para almacenarlo en un archivo en el servidor, desde esta fuente , pero necesito volver a guardar el mapa de bits en la base de datos SQL, que creo que necesito volver a convertir a un formato de byte [].

Entonces, ¿cómo convierto el mapa de bits a un formato de byte []?

Si voy por este camino equivocado, agradecería que me corrigieran.

Aquí está mi código:

            // 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();
¿Fue útil?

Solución

Debería poder cambiar este bloque a

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

Otros consejos

Si ya tiene un MemoryStream , simplemente llame a MemoryStream.ToArray para obtener los datos.

Suponiendo que su mapa de bits es 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();
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top