「Xamarin.Mac/System.Drawing.ImageをNSImageに変換する」の版間の差分
ナビゲーションに移動
検索に移動
imported>Monobook |
(→方法1) |
||
3行目: | 3行目: | ||
== 方法1 == | == 方法1 == | ||
NSImageは[[ファイル]]からのインスタンス生成はできるようだが、byte[]などのメモリ上の[[データ]]からのインスタンス生成はできない。 | NSImageは[[ファイル]]からのインスタンス生成はできるようだが、byte[]などのメモリ上の[[データ]]からのインスタンス生成はできない。 | ||
− | + | そこでCoreGraphicsのCGImageを経由して変換を行う。大雑把には以下のような手順をとった。 | |
+ | # ImageをMemoryStreamに保存 | ||
+ | # MemoryStreamからCGImageを生成 | ||
+ | # CGImageをNSImageに変換 | ||
+ | |||
<source lang="csharp"> | <source lang="csharp"> | ||
using System; | using System; |
2017年7月6日 (木) 06:40時点における最新版
Xamarin.MacにおいてSystem.Drawing.ImageをAppKit.NSImageに変換する方法を試行錯誤している。
方法1[編集 | ソースを編集]
NSImageはファイルからのインスタンス生成はできるようだが、byte[]などのメモリ上のデータからのインスタンス生成はできない。 そこでCoreGraphicsのCGImageを経由して変換を行う。大雑把には以下のような手順をとった。
- ImageをMemoryStreamに保存
- MemoryStreamからCGImageを生成
- CGImageをNSImageに変換
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Foundation;
using AppKit;
using CoreGraphics;
public static class NSImageExtensions
{
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 = new NSImage(cg, new SizeF(cg.Width, cg.Height));
}
}
return nsImage;
}
}
System.Drawing.ImageからのNSImageへの変換はともかく、byte[]からNSImageインスタンスの生成は、プログラム中でウェブなどからファイルを落としてきて表示するようなアプリの場合にはほぼ登場する手法になると思われる。
関連項目[編集 | ソースを編集]
- Xamarin.Mac
- Xamarin.Mac/NSImageをSystem.Drawing.Imageに変換する
- Xamarin.Mac/NSImageをファイルに保存する
- Xamarin.Mac/CGImageをNSImageに変換する