Como faço para converter um bitmap em byte []?
-
06-07-2019 - |
Pergunta
Basicamente, estou inserindo uma imagem usando o evento de inserção de ListViews, tentando redimensionar uma imagem do controle FileUpload e salve -a em um banco de dados SQL usando o LINQ.
Encontrei algum código para criar um novo bitmap do conteúdo no controle FileUpload, mas isso era para armazená -lo em um arquivo no servidor, de esta fonte, mas preciso salvar o bitmap de volta no banco de dados SQL, que acho que preciso converter novamente em um formato byte [].
Então, como faço para converter o bitmap em um formato byte []?
Se eu estiver fazendo isso da maneira errada, ficaria agradecido por você me corrigir.
Aqui está o meu 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();
Solução
Você deve ser capaz de alterar este bloco para
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
};
Outras dicas
Se você tem um MemoryStream
Já ligue para MemoryStream.ToArray
Para divulgar os dados.
Assumindo que seu bitmap é 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();
}