Marshal を使用するコードを、BinaryReader などを介した基になるストリームの明示的な読み取りに置き換えることができるはずです。アンマネージド メモリに既にあるコピーにすばやくアクセスできることに依存するのではなく、ストリームを完全にマネージド メモリに読み込むかシークする必要があるため、これは遅くなる可能性がありますが、基本的にはこれが唯一のオプションです。
読み取り操作のみを実行する場合でも、中程度の信頼コンテキストからアンマネージ メモリに潜入することはできません。
リンクされたコードを見ると、この種のことを行うことが許可されていない理由があります。手始めに、彼は IntPtr の 64/32 ビットの側面を無視しています!
彼が使用している基礎となる BitMapData クラスは、任意のメモリへの自由な読み取りアクセスを持つことを完全に前提としています。これは中程度の信頼の下では決して起こりません。
BitMap を (遅い GetPixel 呼び出しで) 直接使用するか、従来のストリーム API を介してデータを直接読み取り、それを配列にドロップしてから自分で解析するには、彼の基本機能を大幅に書き直す必要があります。これらはどちらも楽しいものではありません。前者ははるかに遅くなり(ピクセル読み取りごとのオーバーヘッドが高いため、桁違いになると予想されます)、後者はそれほど遅くはありませんが(それでも遅いですが)、画像データの低レベルの解析を書き換えるという点で、はるかに多くの関連する労力がかかります.
現在のコードに基づいて何を変更する必要があるかについての大まかなガイドを次に示します。
Quantizer.cs から
public Bitmap Quantize(Image source)
{
// Get the size of the source image
int height = source.Height;
int width = source.Width;
// And construct a rectangle from these dimensions
Rectangle bounds = new Rectangle(0, 0, width, height);
// First off take a 32bpp copy of the image
Bitmap copy = new Bitmap(width, height, PixelFormat.Format32bppArgb);
// And construct an 8bpp version
Bitmap output = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
// Now lock the bitmap into memory
using (Graphics g = Graphics.FromImage(copy))
{
g.PageUnit = GraphicsUnit.Pixel;
// Draw the source image onto the copy bitmap,
// which will effect a widening as appropriate.
g.DrawImage(source, bounds);
}
//!! BEGIN CHANGES - no locking here
//!! simply use copy not a pointer to it
//!! you could also simply write directly to a buffer then make the final immage in one go but I don't bother here
// Call the FirstPass function if not a single pass algorithm.
// For something like an octree quantizer, this will run through
// all image pixels, build a data structure, and create a palette.
if (!_singlePass)
FirstPass(copy, width, height);
// Then set the color palette on the output bitmap. I'm passing in the current palette
// as there's no way to construct a new, empty palette.
output.Palette = GetPalette(output.Palette);
// Then call the second pass which actually does the conversion
SecondPass(copy, output, width, height, bounds);
//!! END CHANGES
// Last but not least, return the output bitmap
return output;
}
//!! Completely changed, note that I assume all the code is changed to just use Color rather than Color32
protected virtual void FirstPass(Bitmap source, int width, int height)
{
// Loop through each row
for (int row = 0; row < height; row++)
{
// And loop through each column
for (int col = 0; col < width; col++)
{
InitialQuantizePixel(source.GetPixel(col, row));
} // Now I have the pixel, call the FirstPassQuantize function...
}
}
他の関数でもほぼ同じことを行う必要があります。これにより、Color32 の必要がなくなります。Bitmap クラスがすべてを処理します。
Bitmap.SetPixel()2 番目のパスを処理します。これは移植する最も簡単な方法ですが、中程度の信頼環境内で移植するための最速の方法ではないことに注意してください。