我有一个 Silverlight 浏览器外应用程序,我想将图片保存在指定目录中。在应用程序中,我将图片加载到 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。我还注意到应用程序生成的文件比原始文件重四倍......
感谢您的帮助 !
菲利普
资料来源: