我已经实现了以下解决方案来压缩base 64映像并返回新的base 64字符串。它在Windows Phone 8.0中运行良好,但针对Windows Phone 8.1,似乎环境发生了变化。
WriteableBitmap
没有BitmapImage
的构造函数,WriteableBitmap
没有函数SaveJpeg
。我知道SaveJpeg
是一个扩展,有没有办法将此扩展添加到Windows Phone 8.1?或者我可以使用任何API吗?我需要更改什么才能使8.1兼容?我在这里坚持下去了: - /
public static string Compress(String base64String, int compression)
{
String compressedImage;
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream memoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(memoryStream.AsRandomAccessStream());
WriteableBitmap bmp = new WriteableBitmap(bitmapImage);
int height = bmp.PixelHeight;
int width = bmp.PixelWidth;
int orientation = 0;
int quality = 100 - compression;
MemoryStream targetStream = new MemoryStream();
bmp.SaveJpeg(targetStream, width, height, orientation, quality);
byte[] targetImage = targetStream.ToArray();
compressedImage = System.Convert.ToBase64String(targetImage);
return compressedImage;
}
答案 0 :(得分:5)
在WP8.1运行时我使用BitmapPropertySet来定义压缩级别。以下是在 Streams 上运行的示例代码:
/// <summary>
/// Method compressing image stored in stream
/// </summary>
/// <param name="sourceStream">stream with the image</param>
/// <param name="quality">new quality of the image 0.0 - 1.0</param>
/// <returns></returns>
private async Task<IRandomAccessStream> CompressImageAsync(IRandomAccessStream sourceStream, double newQuality)
{
// create bitmap decoder from source stream
BitmapDecoder bmpDecoder = await BitmapDecoder.CreateAsync(sourceStream);
// bitmap transform if you need any
BitmapTransform bmpTransform = new BitmapTransform() { ScaledHeight = newHeight, ScaledWidth = newWidth, InterpolationMode = BitmapInterpolationMode.Cubic };
PixelDataProvider pixelData = await bmpDecoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, bmpTransform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);
InMemoryRandomAccessStream destStream = new InMemoryRandomAccessStream(); // destination stream
// define new quality for the image
var propertySet = new BitmapPropertySet();
var quality = new BitmapTypedValue(newQuality, PropertyType.Single);
propertySet.Add("ImageQuality", quality);
// create encoder with desired quality
BitmapEncoder bmpEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destFileStream, propertySet);
bmpEncoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, newHeight, newWidth, 300, 300, pixelData.DetachPixelData());
await bmpEncoder.FlushAsync();
return destStream;
}