Hi I want to change a collared image to greyscale before I show it on the screen. Can some one please tell me why my code below is not working?
private byte[] ConvertMediaFileToByteArray(MediaFile file)
{
using (var memoryStream = new MemoryStream())
{
file.GetStream().CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
public void LoadAndConvertImage(MediaFile imgPath){
byte[] imgSrc = ConvertMediaFileToByteArray(imagePath);
ConvertToGrayRemoveNoise(ref cropedBytes);
ImageSource imageSource = ImageSource.FromStream(() =>
{
var cropedImage = new MemoryStream(cropedBytes);
file.Dispose();
return cropedImage;
});
Image Image.Source = imageSource;
}
public void ConvertToGray(ref byte[] srcPixels)
{
try
{
for (int i = 0; i < srcPixels.Length; i += 4)
{
double b = (double)srcPixels[i] / 255.0;
double g = (double)srcPixels[i + 1] / 255.0;
double r = (double)srcPixels[i + 2] / 255.0;
byte a = srcPixels[i + 3];
//convert to gray
double e = (0.299 * r + 0.587 * g + 0.114 * b) * 255;
byte f = Convert.ToByte(e);
srcPixels[i] = f;
srcPixels[i + 1] = f;
srcPixels[i + 2] = f;
srcPixels[i + 3] = a;
}
}
catch (Exception error)
{
Debug.WriteLine(error.ToString());
}
}
I see two issues. Sometime the ConvertToGray function runs into the Catch with a pointer out of range. If this does not happen the initialisation of the image fails with "initWithData returned nil". I would like to work with the byte[] as several plugins with crop also use that as input and output.