2017-12-29 110 views
0

KBitmap.Bytesは、読み込み専用です。どのようにMarshal.Copyバイト配列をSKBitmapにするかに関する提案はありますか?私は以下のコードスニペットを使用していますが、動作しません。SkiaSharpでバイト配列をSKBitmapに変換するには?

コードスニペット:

SKBitmap bitmap = new SKBitmap((int)Width, (int)Height); 
    bitmap.LockPixels(); 
    byte[] array = new byte[bitmap.RowBytes * bitmap.Height]; 
    for (int i = 0; i < pixelArray.Length; i++) 
    { 
     SKColor color = new SKColor((uint)pixelArray[i]); 
     int num = i % (int)Width; 
     int num2 = i/(int)Width; 
     array[bitmap.RowBytes * num2 + 4 * num] = color.Blue; 
     array[bitmap.RowBytes * num2 + 4 * num + 1] = color.Green; 
     array[bitmap.RowBytes * num2 + 4 * num + 2] = color.Red; 
     array[bitmap.RowBytes * num2 + 4 * num + 3] = color.Alpha; 
    } 
    Marshal.Copy(array, 0, bitmap.Handle, array.Length); 
    bitmap.UnlockPixels(); 

答えて

0

あなたは常にビットマップアンマネージ/ネイティブメモリ内に住んでいるとバイト配列は、マネージコードであるとして、いくつかのマーシャリングを行う必要があります。しかし、あなたは次のようなことをすることができます:

// the pixel array of uint 32-bit colors 
var pixelArray = new uint[] { 
    0xFFFF0000, 0xFF00FF00, 
    0xFF0000FF, 0xFFFFFF00 
}; 

// create an empty bitmap 
bitmap = new SKBitmap(); 

// pin the managed array so that the GC doesn't move it 
var gcHandle = GCHandle.Alloc(pixelArray, GCHandleType.Pinned); 

// install the pixels with the color type of the pixel data 
var info = new SKImageInfo(2, 2, SKImageInfo.PlatformColorType, SKAlphaType.Unpremul); 
bitmap.InstallPixels(info, gcHandle.AddrOfPinnedObject(), info.RowBytes, null, delegate { gcHandle.Free(); }, null); 

これはマネージメモリをピンし、ポインタをビットマップに渡します。この方法では、両方とも同じメモリデータにアクセスしており、実際に変換(またはコピー)する必要はありません。 (メモリがGCで解放することができるように固定されたメモリーは、使用後に固定されていないことが不可欠である。)

また、ここで:https://github.com/mono/SkiaSharp/issues/416

関連する問題