林碧山
林碧山

Reputation: 1

How can I convert Cameraview.GetSnapShot() to Bitmap in a Maui mobile App?

This is my first pilot mobile application. I have set up a Maui mobile application and it can capture and save the camera image as a file successfully. My further intention is to manage the image file pixel by pixel(eg. to gray pixels). It might need to convert the file to Bitmap class. I am suffer in generating a Bitmap as I usually do. Below is my description. The error messgae shows "System.PlatformNotSupportedException Message=System.Drawing.Common is not supported on non-Windows platforms."

//  Namespace using (with System.Drawing.Common ):
    using System.Drawing;


    //Main code:
      string camPath = FileSystem.AppDataDirectory+"\\cam.jpg";
      string grayPath = FileSystem.AppDataDirectory + "\\gray.jpg";
      await Cameraview.SaveSnapShot(Camera.MAUI.ImageFormat.JPEG, camPath);
//Error happen at the line below
      System.Drawing.Bitmap bmp =         (System.Drawing.Bitmap)System.Drawing.Image.FromFile(camPath);//Error happen here! How to rewrite this part? 
  System.Drawing.Bitmap newbmp = MakeGrayscale(bmp);
  newbmp.Save(grayPath);
  sampleImage.Source = null;
  sampleImage.Source = ImageSource.FromFile(grayPath);  

    //call functions:
    public static System.Drawing.Bitmap MakeGrayscale(System.Drawing.Bitmap original)
    {
    // Build a new Bitmap 
    System.Drawing.Bitmap newBitmap = new System.Drawing.Bitmap(original.Width, original.Height);

    // set  pixels to gray 
    for (int i = 0; i < original.Width; i++)
    {
        for (int j = 0; j < original.Height; j++)
        {
            System.Drawing.Color originalColor = original.GetPixel(i, j);
            int grayScale = (int)((originalColor.R * 0.3) + (originalColor.G * 0.59) + (originalColor.B * 0.11));
            System.Drawing.Color newColor = System.Drawing.Color.FromArgb(grayScale, grayScale, grayScale);
            newBitmap.SetPixel(i, j, newColor);
        }
    }

    return newBitmap;
    }

    public static byte[] BitmapToBytes(System.Drawing.Bitmap Bitmap)
    {
    System.IO.MemoryStream ms = null;
    try
    {
        ms = new MemoryStream();
        Bitmap.Save(ms, Bitmap.RawFormat);
        byte[] byteImage = new Byte[ms.Length];
        byteImage = ms.ToArray();
        return byteImage;
    }
    catch (ArgumentNullException ex)
    {
        return null;
    }
    finally
    {
        ms.Close();
    }
    }

    public static System.IO.Stream BytesToStream(byte[] bytes)
    {
    System.IO.Stream stream;
    try
    {
        stream = new MemoryStream(bytes);
    }
    catch
    {
        return null;
    }
    return stream;
    }

Upvotes: 0

Views: 254

Answers (0)

Related Questions