Compress and save base64 image on Windows Phone 8.1

后端 未结 1 1245
抹茶落季
抹茶落季 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:

    /// 
    /// Method compressing image stored in stream
    /// 
    /// stream with the image
    /// new quality of the image 0.0 - 1.0
    /// 
    private async Task 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)
提交回复
热议问题