Silverlight Out-of-browser アプリケーションがあり、指定したディレクトリに画像を保存したいと考えています。アプリケーションでは、画像を BitmapImage にロードし、それをハードドライブ (可能であれば jpg) に保存したいと考えています。私のコード:
private void SaveImageToImagePath(BitmapImage image)
{
string path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Images");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
Save(image, new FileStream(Path.Combine(path, String.Format("{0}.jpg", _imageName)), FileMode.OpenOrCreate));
}
private void Save(BitmapSource bitmapSource, FileStream stream)
{
var writeableBitmap = new WriteableBitmap(bitmapSource);
for (int i = 0; i < writeableBitmap.Pixels.Length; i++)
{
int pixel = writeableBitmap.Pixels[i];
byte[] bytes = BitConverter.GetBytes(pixel);
Array.Reverse(bytes);
stream.Write(bytes, 0, bytes.Length);
}
}
このメソッドを使用して、BitmapImage から ByteArray に渡すことも試みました。
private byte[] ToByteArray(WriteableBitmap bmp)
{
// Init buffer
int w = bmp.PixelWidth;
int h = bmp.PixelHeight;
int[] p = bmp.Pixels;
int len = p.Length;
byte[] result = new byte[4 * w * h];
// Copy pixels to buffer
for (int i = 0, j = 0; i < len; i++, j += 4)
{
int color = p[i];
result[j + 0] = (byte)(color >> 24); // A
result[j + 1] = (byte)(color >> 16); // R
result[j + 2] = (byte)(color >> 8); // G
result[j + 3] = (byte)(color); // B
}
return result;
}
問題は、取得したファイルが読み取り不能 (破損) であり、アプリケーションから読み取ろうとすると、Catastrophic Failureが発生したことです。また、アプリケーションによって生成されたファイルは、元のファイルよりも 4 倍重いことに気付きました...
ご協力ありがとうございました !
フィリップ
ソース: