How to convert ImageSourse to NSUrl or CGImage in xamarin ios

149 Views Asked by At

I want to convert the ImageSource or image byte array to Xamarin.ios NSUrl or CGImage. How to implement this. I am generating the byte Array from LayoutView like below. So after getting the the byte array I need to convert it to NSUrl or CGImage for printing that layout. From the below code I will get the bytearray.

public byte[] LayoutToImage()
{
    var view = UIApplication.SharedApplication.KeyWindow;
    UIGraphics.BeginImageContext(view.Frame.Size);
    view.DrawViewHierarchy(view.Frame, true);
    var image = UIGraphics.GetImageFromCurrentImageContext();
    UIGraphics.EndImageContext();
    using (var imageData = image.AsPNG())
    {
        var bytes = new byte[imageData.Length];
        System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, bytes, 0, Convert.ToInt32(imageData.Length));
        return bytes;
    }
}

I am able to print the image on the iOS project resource file, like that I need to print the layout view also.

 string fileName = "SampleImg.png";
 string localDocUrl = Path.Combine(NSBundle.MainBundle.BundlePath, fileName);var Error = Driver.PrintImageWithURL(new NSUrl(localDocUrl), pSettings);
1

There are 1 best solutions below

0
Zack On BEST ANSWER

As Jason said GetImageFromCurrentImageContext returns a UIImage. If you want to convert to CGImage, you can directly use UIImage.CGImage to get CGImage. Converting a byte array to a CGImage also needs to be converted to a UIImage first.