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

提供: MonoBook
< Xamarin.Mac
2015年10月1日 (木) 02:03時点における114.49.19.146 (トーク)による版 (ページの作成:「==実装1== Xamarin.Mac 2.0系の場合はCGImageDestination.Createのまま。 Xamarin.Mac 1.0系の場合はCGImageDestination.FromUrlに変更する。 <source lang="c...」)
(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
ナビゲーションに移動 検索に移動

実装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);

関連項目

参考文献