私はBitmapImage
WPF アプリケーションで使用している を持っています。後でそれをバイト配列としてデータベースに保存したいのですが (これが最善の方法だと思います)、どうすればこの変換を実行できますか?
あるいは、BitmapImage
(またはその基本クラスのいずれか、BitmapSource
またはImageSource
) をデータ リポジトリに保存するためのより良い方法はありますか?
私はBitmapImage
WPF アプリケーションで使用している を持っています。後でそれをバイト配列としてデータベースに保存したいのですが (これが最善の方法だと思います)、どうすればこの変換を実行できますか?
あるいは、BitmapImage
(またはその基本クラスのいずれか、BitmapSource
またはImageSource
) をデータ リポジトリに保存するためのより良い方法はありますか?
byte[] に変換するには、MemoryStream を使用できます。
byte[] data;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
using(MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
JpegBitmapEncoder の代わりに、casperOne が言ったように、好きな BitmapEncoder を使用できます。
MS SQL を使用している場合は、MS SQL がそのデータ型をサポートしているため -Column を使用することもできますがimage
、何らかの方法で BitmapImage を変換する必要があります。
から派生したクラスのインスタンスBitmapEncoder
( などBmpBitmapEncoder
) を使用し、メソッドを呼び出してSave
を に保存するBitmapSource
必要がありStream
ます。
画像を保存する形式に応じて、特定のエンコーダーを選択します。
に書き込むと、MemoryStream
そこからバイトにアクセスできます。このようなもの:
public Byte[] ImageToByte(BitmapImage imageSource)
{
Stream stream = imageSource.StreamSource;
Byte[] buffer = null;
if (stream != null && stream.Length > 0)
{
using (BinaryReader br = new BinaryReader(stream))
{
buffer = br.ReadBytes((Int32)stream.Length);
}
}
return buffer;
}
MemoryStream を使用するだけです。
byte[] data = null;
using(MemoryStream ms = new MemoryStream())
{
bitmapImage.Save(ms);
data = ms.ToArray();
}