我的应用程序使用相机拍摄图像并将其上传到 flickr。我想压缩图片,这样上传时间就不会像现在这样长。我尝试了 BitmapSource 和 WriteableBitmap 的“SaveJpeg”方法来完成此操作但失败了。位图源在 Silverlight/WP 中没有可用的成员,因为它在完整的 .NET 框架版本和 SaveJpeg 方法中,WriteableBitmap 一直给我一个“这个流不支持写入它”的错误。
这是我目前在我的 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 does not support writing”错误。
有没有其他方法可以压缩图像,或者我是否必须编写压缩算法?
更新已修复!
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);
}
我正在尝试写入源流。呸!
谢谢。
最佳答案
我认为 SaveJpeg 是我这样做的方式。你或许可以用其他方式来做,但我认为那是最简单和最自然的。错误“此流不支持写入”可能是因为您传递给 SaveJpeg 的任何流都是不可写的。我不太确定你要写什么,尝试只使用一个普通的旧内存流,看看它是否像这样工作
using System.IO;
// ...
MemoryStream ms = new MemoryStream();
pic.SaveJpeg(ms, pic.PixelWidth, pic.PixelHeight, 0, 0, 50);
您可以在最终参数中调整质量。 PixelWidth/Height 来自 WriteableBitmap
,因此如果您有其他来源,您可能必须使用其他方法/属性来获取宽度/高度。您可能想要缩放这些,因为来自相机的图片可能非常大。这取决于您上传这些图片的目的,但是缩放它们也可以使文件大小变小。
关于c# - 如何在 Windows Phone 上压缩图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9318481/