2014-09-23 67 views
2

我已经实现了以下解决方案来压缩基本64位图像并取回新的base 64字符串。它在Windows Phone 8.0中运行良好,但是针对Windows Phone 8.1似乎环境中存在变化。在Windows Phone 8.1上压缩并保存base64图像

WriteableBitmap没有构造函数为BitmapImageWriteableBitmap没有功能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; 
} 

回答

5

在WP8.1运行时我用BitmapPropertySet定义压缩的程度。这里下面的示例代码运行在

/// <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; 
} 
+0

,如果你不知道什么尺寸的时间提前? – 2014-11-24 14:56:43

+0

@ JerryNixon-MSFT你的意思是你不知道你想要缩放图像的大小? – Romasz 2014-11-24 15:10:05

+0

我的意思是,如果你使用base64编码,而你不知道在SetPixelData中设置的高度和宽度 – 2014-11-24 15:20:00

相关问题