问题描述
photoOutput = new AVCapturePhotoOutput();
if (CaptureSession.CanAddOutput(photoOutput))
{
CaptureSession.AddOutput(photoOutput);
photoOutput.IsHighResolutionCaptureEnabled = true;
}
拍照按钮:
void TakePhoto()
{
AVCapturePhotoSettings settings = GetCurrentPhotoSettings();
photoOutput.CapturePhoto(settings,this);
}
AVCapturePhotoSettings GetCurrentPhotoSettings()
{
AVCapturePhotoSettings photoSettings = AVCapturePhotoSettings.Create();
var previewPixelType = photoSettings.AvailablePreviewPhotoPixelFormatTypes.First();
var keys = new[]
{
new Nsstring(CVPixelBuffer.PixelFormatTypeKey),new Nsstring(CVPixelBuffer.WidthKey),new Nsstring(CVPixelBuffer.HeightKey),};
var objects = new NSObject[]
{
previewPixelType,new NSNumber(160),new NSNumber(160)
};
var dictionary = new NSDictionary<Nsstring,NSObject>(keys,objects);
photoSettings.PreviewPhotoFormat = dictionary;
photoSettings.IsHighResolutionPhotoEnabled = true;
return photoSettings;
}
[Export("captureOutput:didFinishProcessingPhotoSampleBuffer:previewPhotoSampleBuffer:resolvedSettings:bracketSettings:error:")]
void DidFinishProcessingPhoto(AVCapturePhotoOutput captureOutput,CMSampleBuffer photoSampleBuffer,CMSampleBuffer previewPhotoSampleBuffer,AVCaptureResolvedPhotoSettings resolvedSettings,AVCaptureBracketedStillimagesettings bracketSettings,NSError error)
{
if (photoSampleBuffer == null)
{
Console.WriteLine($"Error occurred while capturing photo: {error}");
return;
}
NSData imageData = AVCapturePhotoOutput.GetJpegPhotoDataRepresentation(photoSampleBuffer,previewPhotoSampleBuffer);
UIImage imageInfo = new UIImage(imageData);
(Element as Cameraview).SetPhotoResult(imageInfo.AsJPEG().ToArray());
}
作为执行此代码的结果,我获得了使用该函数保存的图像字节数组:
void SaveImageTest(string filename,byte[] arr)
{
UIImage img = new UIImage(NSData.FromArray(arr));
var jpeg = img.AsJPEG();
NSError error;
jpeg.Save(filename,false,out error);
}
将图像上传到服务器,我在图像详细信息中获得 96 DPI。 image details
我想创建 72 个 DPI 图像。,
我没有找到可理解的解决方案,也许 swift 无法创建此类图像,您可能知道用于图像转换的 Xamarin 库
解决方法
我们可以使用以下代码调整图像大小
/*
sourceImage:the iamge that you download
newSize the size you want ( for example 72*72)
*/
public UIImage ScalingImageToSize(UIImage sourceImage,CGSize newSize)
{
UIGraphics.BeginImageContextWithOptions(newSize,false,UIScreen.MainScreen.Scale);
sourceImage.Draw(new CGRect(0,newSize.Width,newSize.Height));
UIImage newImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return newImage;
}