Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Stream to UIImage in Xamarin iOS?

I have Xamarin Forms solution and in iOS project, I would like to convert image that is in Stream to UIImage. I obtained Stream with this code:

var _captureSession = new AVCaptureSession();
var _captureDevice = AVCaptureDevice.GetDefaultDevice(AVMediaType.Video);

var output = new AVCaptureStillImageOutput { OutputSettings = new NSDictionary(AVVideo.CodecKey, AVVideo.CodecJPEG) };

NSError error;
_captureSession.AddInput(new AVCaptureDeviceInput(_captureDevice, out error));
_captureSession.AddOutput(output);
_captureSession.StartRunning();

var buffer = await output.CaptureStillImageTaskAsync(output.Connections[0]);
NSData data = AVCaptureStillImageOutput.JpegStillToNSData(buffer);
Stream stream = data.AsStream();

I need UIImage in order to rotate it with this code:

public UIImage RotateImage(UIImage image)
{
    CGImage imgRef = image.CGImage;
    float width = imgRef.Width;
    float height = imgRef.Height;
    CGAffineTransform transform = CGAffineTransform.MakeIdentity();
    RectangleF bounds = new RectangleF(0, 0, width, height);

    float scaleRatio = bounds.Size.Width / width;
    SizeF imageSize = new SizeF(imgRef.Width, imgRef.Height);
    UIImageOrientation orient = image.Orientation;
    float boundHeight;

    if (width > height)
    {
        boundHeight = bounds.Size.Height;
        bounds.Size = new SizeF(boundHeight, bounds.Size.Width);
        transform = CGAffineTransform.MakeTranslation(imageSize.Height, 0);
        transform = CGAffineTransform.Rotate(transform, (float)Math.PI / 2.0f);
    }

    UIGraphics.BeginImageContext(bounds.Size);
    CGContext context = UIGraphics.GetCurrentContext();

    context.ScaleCTM(-scaleRatio, scaleRatio);
    context.TranslateCTM(-height, 0);

    context.ConcatCTM(transform);

    context.DrawImage(new RectangleF(0, 0, width, height), imgRef);
    UIImage imageCopy = UIGraphics.GetImageFromCurrentImageContext();
    UIGraphics.EndImageContext();

    return imageCopy;
}

How to convert Stream to UIImage?

like image 702
Uros Avatar asked Jan 04 '23 00:01

Uros


1 Answers

You need to covert your stream into NSData first, then you can convert it into a UIImage.

var imageData = NSData.FromStream(stream);
var image = UIImage.LoadFromData(imageData);

These are both IDisposable so you can use using statements based on your situation. If you don't use a using statement make sure you dispose of the image objects from memory manually.

like image 134
Dan Beaulieu Avatar answered Feb 01 '23 20:02

Dan Beaulieu