I am trying to write a function that will resize an image and compress it using a compression quality value. I found some useful information here and here and here, but I am still quite confused.
I am using Dependency Services and have got it done for ios and Android successfully. Below is the code which I have used for ios.
iOS
public byte[] DecodeImage(byte[] imgBytes, int regWidth, int regHeight, int compressionQuality)
{
try
{
NSData data = NSData.FromArray(imgBytes);
var image = UIImage.LoadFromData(data);
data = image.AsJPEG((nfloat) compressionQuality / 100);
byte[] bytes = new byte[data.Length];
System.Runtime.InteropServices.Marshal.Copy(data.Bytes, bytes, 0, Convert.ToInt32(data.Length));
return bytes;
}
catch (Exception ex)
{
return null;
}
}
I would like to replicate the same function for the dependency service in my UWP project, any help would be greatly appreciated.
This is what I currently have, but it does not work.
public async Task<byte[]> DecodeImageAsync(string fileUri, int regWidth, int regHeight, int compressionQuality)
{
byte[] returnVal;
StorageFile file = await StorageFile.GetFileFromPathAsync(fileUri);
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); //ConfigureAwait(false).;
var qualityNum = (float)compressionQuality / 100;
var propertySet = new BitmapPropertySet();
var qualityValue = new BitmapTypedValue(
qualityNum, // Maximum quality
Windows.Foundation.PropertyType.Single
);
propertySet.Add("ImageQuality", qualityValue);
var resizedStream = new InMemoryRandomAccessStream();
BitmapEncoder en = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream,
propertySet);
double widthRatio = (double) regWidth / decoder.PixelWidth;
double heightRatio = (double) regHeight / decoder.PixelHeight;
double scaleRatio = Math.Min(widthRatio, heightRatio);
if (regWidth == 0)
scaleRatio = heightRatio;
if (regHeight == 0)
scaleRatio = widthRatio;
uint aspectHeight = (uint) Math.Floor(decoder.PixelHeight * scaleRatio);
uint aspectWidth = (uint) Math.Floor(decoder.PixelWidth * scaleRatio);
encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear;
encoder.BitmapTransform.ScaledHeight = aspectHeight;
encoder.BitmapTransform.ScaledWidth = aspectWidth;
returnVal = new byte[stream.Size];
await encoder.FlushAsync();
stream.Seek(0);
returnVal = new byte[stream.Size];
var dr = new DataReader(stream.GetInputStreamAt(0));
await dr.LoadAsync((uint)stream.Size);
dr.ReadBytes(returnVal);
}
return returnVal;
}
Any thoughts on how I could change the code to resize as well as compress the image would be appreciated.