Xamarin.Mac/System.Drawing.ImageをNSImageに変換する

提供: MonoBook
< Xamarin.Mac
2015年1月24日 (土) 06:56時点における126.213.5.102 (トーク)による版 (ページの作成:「MonoMacにおいてSystem.Drawing.ImageをMonoMac.AppKit.NSImageに変換する方法を試行錯誤している。 ==方法1== NSImageはファイルからのイン...」)
(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
ナビゲーションに移動 検索に移動

MonoMacにおいてSystem.Drawing.ImageをMonoMac.AppKit.NSImageに変換する方法を試行錯誤している。

方法1

NSImageはファイルからのインスタンス生成はできるようだが、byte[]などのメモリ上のデータからのインスタンス生成はできない。 そこでMonoMac.CoreGraphicsのCGImageを経由して変換を行う。

    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using MonoMac.Foundation;
    using MonoMac.AppKit;
    using MonoMac.CoreGraphics;

    public static class NSImageExtentions
    {
        public static NSImage ToNSImage(this Image image) 
        {
            NSImage nsImage = null;
            byte[] buf = null;

            // ImageをPNG形式でbyte[]に展開する。
            using (var ms = new MemoryStream())
            {
                image.Save(ms, ImageFormat.Png);
                buf = ms.ToArray();
            }
            // メモリ使用量を抑えるため、ここでMemoryStreamは破棄する。

            // byte[]からNSImageを生成する。
            if (null != buf)
            {
                using (var dp = new CGDataProvider(buf, 0, buf.Length))
                using (var cg = CGImage.FromPNG(dp, null, false, CGColorRenderingIntent.Default))
                {
                    nsImage = NSImage(cg, new SizeF(cg.Width, cg.Height));
                }
            }

            return nsImage;
        }
    }

System.Drawing.ImageからのNSImageへの変換はともかく、byte[]からNSImageインスタンスの生成は、ウェブなどからファイルを落としてくるようなアプリの場合には、ほぼ登場する手法となると思われる。

関連項目

参考文献