質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

XAML

XAML(Extensible Application Markup Language)はWPF、Silverlight、Windows PhoneそしてWindows Store appsでユーザーインターフェースを定義するために使われるXML言語です。

iPhone

iPhoneとは、アップル社が開発・販売しているスマートフォンです。 同社のデジタルオーディオプレーヤーiPodの機能、電話機能、インターネットやメールなどのWeb通信機能の3つをドッキングした機器です。

Xamarin

Xamarin(ザマリン)は、iPhoneなどのiOSやAndroidで動作し、C# 言語を用いてアプリを開発できるクロスプラットフォーム開発環境です。Xamarin Studioと C# 言語を用いて、 iOS と Android の両方の開発を行うことができます。

Q&A

解決済

1回答

2780閲覧

Xamarin.Forms + iOSでカメラキャプチャした画像が表示されない。

ikarimame

総合スコア37

iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

XAML

XAML(Extensible Application Markup Language)はWPF、Silverlight、Windows PhoneそしてWindows Store appsでユーザーインターフェースを定義するために使われるXML言語です。

iPhone

iPhoneとは、アップル社が開発・販売しているスマートフォンです。 同社のデジタルオーディオプレーヤーiPodの機能、電話機能、インターネットやメールなどのWeb通信機能の3つをドッキングした機器です。

Xamarin

Xamarin(ザマリン)は、iPhoneなどのiOSやAndroidで動作し、C# 言語を用いてアプリを開発できるクロスプラットフォーム開発環境です。Xamarin Studioと C# 言語を用いて、 iOS と Android の両方の開発を行うことができます。

0グッド

0クリップ

投稿2020/10/19 11:57

困っていること

Xamarin.Forms+iOSでAVFoundationを使い画像をキャプチャしておりますが、画像が表示されずに困っております。

ソースコード

MainPage.xaml

xaml

1<?xml version="1.0" encoding="utf-8"?> 2<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="CameraTest.MainPage"> 3 <Grid> 4 <Grid.RowDefinitions> 5 <RowDefinition Height="64"/> 6 <RowDefinition Height="*"/> 7 <RowDefinition Height="64"/> 8 </Grid.RowDefinitions> 9 <Grid.ColumnDefinitions> 10 <ColumnDefinition Width="64"/> 11 <ColumnDefinition Width="*"/> 12 <ColumnDefinition Width="64"/> 13 </Grid.ColumnDefinitions> 14 <Image Grid.Row="1" Grid.Column="1" Source="{Binding CapImg}"/> 15 </Grid> 16</ContentPage>

MainPage.cs

C#

1using System; 2using System.Collections.Generic; 3using System.ComponentModel; 4using System.Linq; 5using System.Text; 6using System.Threading.Tasks; 7using Xamarin.Forms; 8 9namespace CameraTest 10{ 11 public partial class MainPage : ContentPage 12 { 13 public MainPage() 14 { 15 BindingContext = new MainPageVM(); 16 17 InitializeComponent(); 18 } 19 } 20} 21

MainPageVM.cs

c#

1using System; 2using System.ComponentModel; 3using Xamarin.Forms; 4 5namespace CameraTest 6{ 7 public class MainPageVM : INotifyPropertyChanged 8 { 9 public event PropertyChangedEventHandler PropertyChanged; 10 public void FirePropertyChangedEvent(string propname) 11 { 12 if (PropertyChanged != null) 13 { 14 PropertyChanged(this, new PropertyChangedEventArgs(propname)); 15 } 16 } 17 18 public MainPageVM() 19 { 20 if (CameraControl == null) 21 CameraControl = DependencyService.Get<ICameraControl>(); 22 CameraControl.Initialize(); 23 CameraControl.CaptureCameraImage += CaptureCameraImage; 24 CameraControl.CaptureStart(); 25 } 26 27 public static ICameraControl CameraControl { get; set; } 28 29 private ImageSource _capimg = null; 30 public ImageSource CapImg 31 { 32 get { return _capimg; } 33 set 34 { 35 _capimg = value; 36 FirePropertyChangedEvent("CapImg"); 37 } 38 } 39 40 private bool CaptureCameraImage(ImageSource image) 41 { 42 CapImg = image; 43 return true; 44 } 45 46 } 47}

ICameraControl.cs

c#

1using System; 2using Xamarin.Forms; 3 4namespace CameraTest 5{ 6 public delegate bool CaptureCameraImageDelegate(ImageSource image); 7 public interface ICameraControl 8 { 9 CaptureCameraImageDelegate CaptureCameraImage { get; set; } 10 void Initialize(); 11 bool CaptureStart(); 12 bool CaptureStop(); 13 } 14}

CameraTest.iOSプロジェクト

CameraControl_iOS.cs

c#

1using System; 2using AVFoundation; 3using CoreFoundation; 4using CoreGraphics; 5using CoreMedia; 6using CoreVideo; 7using Foundation; 8using UIKit; 9using Xamarin.Forms; 10 11[assembly: Dependency(typeof(CameraTest.iOS.CameraControl_iOS))] 12namespace CameraTest.iOS 13{ 14 public class CameraControl_iOS : AVCaptureVideoDataOutputSampleBufferDelegate, ICameraControl 15 { 16 public CameraControl_iOS() 17 { 18 } 19 20 private AVCaptureSession captureSession = null; 21 22 public CaptureCameraImageDelegate CaptureCameraImage { get; set; } 23 24 public bool CaptureStart() 25 { 26 if (captureSession == null) return false; 27 captureSession.StartRunning(); 28 return true; 29 } 30 31 public bool CaptureStop() 32 { 33 if (captureSession == null) return false; 34 captureSession.StopRunning(); 35 return true; 36 } 37 38 public void Initialize() 39 { 40 NSError error; 41 42 captureSession = new AVCaptureSession(); 43 captureSession.SessionPreset = AVCaptureSession.PresetHigh; 44 45 var videoDevice = AVCaptureDevice.GetDefaultDevice(AVMediaType.Video); 46 if (videoDevice == null) 47 throw new Exception("Video recording not supported on this device"); 48 49 if (!videoDevice.LockForConfiguration(out error)) 50 { 51 Console.WriteLine(error.LocalizedDescription); 52 videoDevice.UnlockForConfiguration(); 53 return; 54 } 55 videoDevice.ActiveVideoMinFrameDuration = new CMTime(1, 30); 56 videoDevice.UnlockForConfiguration(); 57 58 // get input 59 var input = AVCaptureDeviceInput.FromDevice(videoDevice); 60 if (input == null) 61 { 62 // Error, report and abort 63 Console.WriteLine("Unable to gain input from capture device."); 64 return; 65 } 66 captureSession.AddInput(input); 67 //foreach (var i in captureSession.Inputs) Console.WriteLine(i.ToString()); 68 69 // crate output 70 var output = new AVCaptureVideoDataOutput(); 71 var settings = new AVVideoSettingsUncompressed(); 72 settings.PixelFormatType = CVPixelFormatType.CV32BGRA; 73 output.WeakVideoSettings = settings.Dictionary; 74 75 var queue = new DispatchQueue("myQueue"); 76 output.SetSampleBufferDelegateQueue(this, queue); 77 captureSession.AddOutput(output); 78 //foreach (var o in captureSession.Outputs) Console.WriteLine(o.ToString()); 79 } 80 81 public override void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) 82 { 83 try 84 { 85 if (CaptureCameraImage != null) 86 { 87 using (var image = GetImageFromSampleBuffer(sampleBuffer)) 88 using (var stream = image.AsPNG().AsStream()) 89 { 90 var dst = ImageSource.FromStream(() => { return stream; }); 91 CaptureCameraImage(dst); 92 } 93 } 94 //base.DidOutputSampleBuffer(captureOutput, sampleBuffer, connection); 95 } 96 catch (Exception e) 97 { 98 Console.WriteLine(e.ToString()); 99 } 100 finally 101 { 102 sampleBuffer.Dispose(); 103 } 104 } 105 106 private UIImage GetImageFromSampleBuffer(CMSampleBuffer sampleBuffer) 107 { 108 using (var pixelBuffer = sampleBuffer.GetImageBuffer() as CVPixelBuffer) 109 { 110 pixelBuffer.Lock(CVPixelBufferLock.None); 111 CGBitmapFlags flags = CGBitmapFlags.PremultipliedFirst | CGBitmapFlags.ByteOrder32Little; 112 using (var cs = CGColorSpace.CreateDeviceRGB()) 113 { 114 using (var context = new CGBitmapContext(pixelBuffer.BaseAddress, 115 pixelBuffer.Width, 116 pixelBuffer.Height, 117 8, 118 pixelBuffer.BytesPerRow, 119 cs, 120 flags)) 121 { 122 using (var cgImage = context.ToImage()) 123 { 124 pixelBuffer.Unlock(CVPixelBufferLock.None); 125 return UIImage.FromImage(cgImage); 126 } 127 } 128 } 129 } 130 } 131 } 132}

試したこと

CameraControl_iOS.csのDidOutputSampleBuffer()のコードを以下のように変更すると表示されるのですが、その場合StreamをDisposeすることが出来ません。

c#

1 public override void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) 2 { 3 try 4 { 5 if (CaptureCameraImage != null) 6 { 7 using (var image = GetImageFromSampleBuffer(sampleBuffer)) 8 { 9 var stream = image.AsPNG().AsStream(); 10 var dst = ImageSource.FromStream(() => { return stream; }); 11 CaptureCameraImage(dst); 12 } 13 } 14 //base.DidOutputSampleBuffer(captureOutput, sampleBuffer, connection); 15 } 16 catch (Exception e) 17 { 18 Console.WriteLine(e.ToString()); 19 } 20 finally 21 { 22 sampleBuffer.Dispose(); 23 } 24 }

どのように実装すべきなのでしょうか?

環境

macOS Catalina v10.15.7
Visual Studio for mac v8.7.8(build 4)
Xcode v12.0.1(12A7300)

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

ImageSource.FromStreamで渡したコールバックで返すStreamは、Imageビューで表示した際にDisposeされるので、気にする必要はありません。

投稿2020/10/19 17:49

f-miyu

総合スコア1625

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

ikarimame

2020/10/20 02:44

なるほど、Imageで表示した際にDisposeされるということでusingを利用するのをやめました。 所で、表示した際にDisposeされるというのと関係があるのかわからないのですが、ImageSource.FromStreamで取得したImageSourceを複数のImageに設定した場合、先に設定したImageにのみ画像が表示され、あとで設定したImageには画像が表示されなかったり、先に設定した方のImageがちらついて表示されたりして困っております。 Imageで表示された際にDispoeされることが問題なのかと思い、新たなMemoryStreamにCopyToしてみたりもしましたが、やはり画像は表示されませんでした。 最終的にはキャプチャした画像、それに画像処理をかけた結果の画像というように並べて表示したいと思っておりますが、なぜCopyしたStreamの画像は表示されないのでしょうか?
ikarimame

2020/10/20 03:13

申し訳ありません 上記の件よく確認しましたところ、私のコードにミスがありました。 新たなMemoryStreamにCopyToしたうえでそれぞれImageに割り当てる分には問題なく画像が表示できました。 ありがとうございます
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問