I have a Silverlight Out-of-browser application and I want to save pictures on a specified directory. In the application, I have the picture loaded in a BitmapImage and I wish to save it on the HardDrive (in jpg if possible). My code :
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);
    }
} 
I have also tried with this method to pass from BitmapImage to 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;
} 
The problem is that the file I get is unreadable (corrupted) and when I try to read it from the application, I got a Catastrophic Failure. I also noticed that the file generated by the application is four time heavier than the original...
Thank you for your help !
Philippe
Sources :
 
     
    