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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With