gpt4 book ai didi

xamarin - 如何在 Xamarin iOS 中将 Stream 转换为 UIImage?

转载 作者:行者123 更新时间:2023-12-02 02:05:44 25 4
gpt4 key购买 nike

我有 Xamarin Forms 解决方案,在 iOS 项目中,我想将 Stream 中的图像转换为 UIImage。我用以下代码获得了 Stream:

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();

我需要 UIImage 才能使用以下代码旋转它:

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;
}

如何将Stream转换为UIImage?

最佳答案

您需要先将流转换为 NSData,然后才能将其转换为 UIImage。

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

这些都是IDisposable,因此您可以根据您的情况使用using 语句。如果您不使用 using 语句,请确保手动处理内存中的图像对象。

关于xamarin - 如何在 Xamarin iOS 中将 Stream 转换为 UIImage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43995539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com