Compress and save base64 image on Windows Phone 8.1

后端 未结 1 1237
抹茶落季
抹茶落季 2020-12-04 00:49

I have implemented the following solution to compress a base 64 image and get back the new base 64 string. It works fine in Windows Phone 8.0 but targeting Windows Phone 8.1

相关标签:
1条回答
  • 2020-12-04 01:22

    In WP8.1 Runtime I've used BitmapPropertySet to define a level of compression. Here below is sample code operating on 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;
    }
    
    0 讨论(0)
提交回复
热议问题