圖片存取 in sqlite by C#
這一篇,但那一篇的作法試從檔案中讀取圖片資料在存入sqlite的資料庫中的;
不同於那篇文章, 現在修改了一部分,能夠讀取畫面中的圖像的byte array
(在此是用C# WPF的語法)
GetImageSourceByte function 說明︰
傳入一個 ImageSource ,利用 PngBitmapEncoder 的方式將ImageSource 轉成一個 Stream 並存入 MemoryStream 中; 最後在從 MemoryStream 取得資料存到 byte array中,
參考 定義
/**
* @Name GetImageSourceByte
*
* Get the ImageSource Byte array, which can save in database as BLOB type
*
* @param EventImage [in] - image to save
* @return the image byte array
*
*/
public byte[] GetImageSourceByte(ImageSource EventImage)
{
byte[] MyData = null;
/// new a JpegBitmapEncoder and add r into it
PngBitmapEncoder e = new PngBitmapEncoder();
e.Frames.Add(EventImage as BitmapFrame);
/// new memoryStream
MemoryStream ms = new MemoryStream();
/// Save to memory
e.Save(ms);
/// Re set the position, or read the memory from the last position
///ms.Seek(0, SeekOrigin.Begin);
/// Or set position
ms.Position = 0;
MyData = new byte[ms.Length];
ms.Read(MyData, 0, System.Convert.ToInt32(ms.Length));
ms.Close();
return MyData;
}
這裡說明一下 如何取得 傳入要傳的 ImageSource
參考 定義
/// Get bound of the visual
/// g is the WPF visual object, such as "grid","canvas", "Image", ...
Rect b = VisualTreeHelper.GetDescendantBounds(g);
/// new a RenderTargetBitmap with actual size of c
RenderTargetBitmap r = new RenderTargetBitmap((int)b.Width, (int)b.Height, 96, 96, PixelFormats.Pbgra32);
/// Render visual
r.Render(g);
/// Create BitmapFrame as ImageSource
BitmapFrame BitF= BitmapFrame.Create(r);
/// Get Byte[]
byte[] Img = GetImageSourceByte(BitF);
在此感謝 James 的指點
1 則留言:
居然偷偷在這邊感謝我~~
幸好我細心~~
張貼留言