将BitmapSource转换为流在Windows Phone中

3
我有一个类需要使用流来旋转从手机相机拍摄的图像。我遇到的问题是,当从隔离存储中加载图片(即用户先前保存了图片后)时,它会被加载到BitmapSource中。
如果可能的话,我想要将位图源“提取”回到流中?是否有人知道在使用 Silverlight for WP7 吗?
谢谢
3个回答

5

试一试这个:

WriteableBitmap bmp = new WriteableBitmap((BitmapSource)img);

using (MemoryStream stream = new MemoryStream()) {

    bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
    return stream;
}

2
对我来说不起作用!WriteableBitmap没有SaveJpeg方法。 - Butzke

2

您不必直接将其拉回到位图源中,但可以通过IsolatedStorageFileStream类到达那里。

这是我的版本,其中的方法接受一个流(您的代码显然比我的更多,但对于我们的目的来说,这应该足够了)。

public class MyPhotoClass
{
    public BitmapSource ConvertToBitmapSource(Stream stream)
    {
        BitmapImage img = new BitmapImage();
        img.SetSource(stream);
        return img;
    }
}

然后使用从隔离存储中获取的文件数据调用该类:

private void LoadFromIsostore_Click(object sender, RoutedEventArgs e)
{
    using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (IsolatedStorageFileStream fs = file.OpenFile("saved.image", FileMode.Open))
        {
            MyPhotoClass c = new MyPhotoClass();
            BitmapSource picture = c.ConvertToBitmapSource(fs);
            MyPicture.Source = picture;
        }
    }
}

请注意,我们正在直接使用从OpenFile方法返回的IsolatedStorageFileStream对象。它是一个流,这正是ConvertToBitmapSource所需要的。
如果这不是您要寻找的内容,或者我误解了您的问题,请告诉我...

1
        var background = Brushes.Transparent;

        var bmp = Viewport3DHelper.RenderBitmap(viewport, 500, 500, background);

        BitmapEncoder encoder;
        string ext = Path.GetExtension(FileName);
        switch (ext.ToLower())
        {

            case ".png":
                var png = new PngBitmapEncoder();
                png.Frames.Add(BitmapFrame.Create(bmp));
                encoder = png;
                break;
            default:
                throw new InvalidOperationException("Not supported file format.");
        }

        //using (Stream stm = File.Create(FileName))
        //{
        //    encoder.Save(stm);
        //}

        using (MemoryStream stream = new MemoryStream())
        {
            encoder.Save(stream);

            this.pictureBox1.Image = System.Drawing.Image.FromStream(stream);
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接