پر کردن کنترل Image از داده های Binary موجود در بانک
سلام
من با استفاده از این کلاس عکس ها رو تبدیل به بایت میکنم و در دیتابیس ذخیره میکنم (تا اینجا مشکلی نیست)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;
namespace SavePhotoInDB
{
class Convertor
{
public static Image ConvertByteArrayToImage(byte[] myByteArray)
{
MemoryStream ms = new MemoryStream(myByteArray, 0, myByteArray.Length);
ms.Write(myByteArray, 0, myByteArray.Length);
return Image.FromStream(ms, true);
}
public static byte[] ReadFile(string sPath)
{
byte[] data = null;
FileInfo FInfo = new FileInfo(sPath);
long numOfBytes = FInfo.Length;
FileStream FStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(FStream);
data = br.ReadBytes((int)numOfBytes);
return data;
}
}
}
حالا میخوام از دیتابیس اون مقدار رو بخونم و تبدیل به عکس کنم و اون عکس رو بریزم توی Source مربوط به کنترل Image خودم.
این رو هم با استفاده از این تکه کد انجام میدادم (توی WinForms)
SqlDataReader DR = SCM.ExecuteReader();
DR.Read();
byte[] img = (byte[])DR["pic"];
Image i = Convertor.ConvertByteArrayToImage(img);
pictureBox1.Image = i;
ولی خط آخر توی WPF جواب نمیده. یعنی نمیشه سورس کنترل Image رو اینطوری پر کرد! اگه ممکنه دوستان راهنمایی کنید. پیشاپیش ممنون
نقل قول: پر کردن کنترل Image از داده های Binary موجود در بانک
سلام
ببین این کارت رو راه میندازه
تست نکردم چون الان Vs ندارم
public BitmapImage ConvetToImage(byte[] buffer)
{
if (buffer.Length == 0)
{
return null;
}
BitmapImage res = new BitmapImage();
res.BeginInit();
res.StreamSource = new System.IO.MemoryStream(buffer);
res.EndInit();
return res;
}
حالا میتنوی اینو بنویسی
SqlDataReader DR = SCM.ExecuteReader();
DR.Read();
byte[] img = (byte[])DR["pic"];
image1.Source = ConvetToImage(img);
نقل قول: پر کردن کنترل Image از داده های Binary موجود در بانک
با تشکر از پاسختون، مشکل حل شد.
فقط یه نکته کوچیک هم هست، میگم شاید بدرد بقیه بخوره. چون عکس بصورت Binary در دیتابیس ذخیره شده، وقتی میخوایم بریزیمش توی متغیر byte[] باید از ToArray() استفاده کنیم.