如何在Windows Phone上压缩图像

时间:2012-02-16 20:22:13

标签: c# silverlight windows-phone-7 image-processing

我的应用使用相机拍摄图像并将其上传到flickr。我想压缩图像,以便上传不会像目前那样长。我尝试了BitmapSource和WriteableBitmap的'SaveJpeg'方法来完成此任务但失败了。位图源在Silverlight / WP中没有与完整.NET框架版本中相同的成员,而且WriteableBitmap一直在给我一个“此流不支持写入它”错误的SaveJpeg方法。

这是我目前正在我的CameraCaptureTask完成的事件处理程序中执行的操作:

private void CameraCaptureCompleted(object sender, PhotoResult e)
    {
        if (e == null || e.TaskResult != TaskResult.OK)
        {
            return;
        }                                                             
        BitmapImage bitmap = new BitmapImage {CreateOptions = BitmapCreateOptions.None};                        
        bitmap.SetSource(AppHelper.LoadImage(e.ChosenPhoto));
        WriteableBitmap writeableBitmap = new WriteableBitmap(bitmap);

        // Encode the WriteableBitmap object to a JPEG stream.
        writeableBitmap.SaveJpeg(e.ChosenPhoto, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 85);
    }

这段代码给了我一个:“Stream不支持写入”错误。

还有其他方法可以压缩图像,还是我必须编写压缩算法?

更新固定!!

private void CameraCaptureCompleted(object sender, PhotoResult e)
    {
        if (e == null || e.TaskResult != TaskResult.OK)
        {
            return;
        }                                                             
        BitmapImage bitmap = new BitmapImage {CreateOptions = BitmapCreateOptions.None};                        
        bitmap.SetSource(AppHelper.LoadImage(e.ChosenPhoto));
        WriteableBitmap writeableBitmap = new WriteableBitmap(bitmap);

        // Encode the WriteableBitmap object to a JPEG stream.
        writeableBitmap.SaveJpeg(new MemoryStream(), writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 85);
    }

我试图写入源流。卫生署!

感谢。

1 个答案:

答案 0 :(得分:3)

SaveJpeg是我想的方式。你可能会采取其他一些方式,但我认为这将是最简单和最自然的。错误'此流不支持写入'可能是因为您传递给SaveJpeg的任何流都不可写。我不确定你要写什么,尝试只使用一个普通的旧内存流,看看它是否像这样工作

using System.IO;

// ...

MemoryStream ms = new MemoryStream();
pic.SaveJpeg(ms, pic.PixelWidth, pic.PixelHeight, 0, 0, 50);

您可以在最终参数中调整质量。 PixelWidth / Height来自WriteableBitmap,因此如果您有其他来源,则可能必须使用其他方法/属性来获取宽度/高度。您可能想要缩放这些,因为来自相机的图片可能非常大。这取决于您上传这些图片的内容,但是缩放它们可以使文件大小更小。