Xamarin.Mac/CGImageをファイルに保存する

提供: MonoBook
ナビゲーションに移動 検索に移動

実装1

Xamarin.Mac 2.0系の場合はCGImageDestination.Createのまま。 Xamarin.Mac 1.0系の場合はCGImageDestination.FromUrlに変更する。

using System;
using Foundation;
using CoreGraphics;
using ImageIO;

namespace Library
{
    public static class CGImageExtensions
    {
        public static bool Save(this CGImage cgImage, string path, string typeIdentifier)
        {
            using (var url = NSUrl.FromFilename(path))
            using (var dst = CGImageDestination.Create(url, typeIdentifier, imageCount:1))
            {
                if (dst == null)
                {
                    return false;
                }

                dst.AddImage(cgImage);

                return dst.Close();
            }
        }
    }
}

引数typeIdentifierはMobileCoreServices.UTTypeに定義されている定数文字列群を指定する。 拡張子で自動判別するようにしてMobileCoreServices.UTTypeを無視するようにした方が直感的かもしれない。

        cgImage.Save(save, MobileCoreServices.UTType.PNG);

関連項目

参考文献