當要處理超大型資料,如上萬解析度的影像,有時候無法以一般手法載入到記憶體裡面做編輯,所以必須使用此手法。直接對硬碟的記憶體位址作存取修改。
修改範例
此一範例為處理超大型Bitmap影像,offset需要重新定義,參考BitmapHeadFile結構,之後對整張影像的調色盤進行加亮的方法。
private void button1_Click(object sender, EventArgs e) { long offset; // 記憶體起始位移位置(byte) long length; // 整份檔案大小(byte) if (openFileDialog.ShowDialog() != DialogResult.Cancel) { // 以FileStream取得檔案長度 using (FileStream ReadStream = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.ReadWrite)) { offset = 0x37B; // 隨機偏移量 length = (int)ReadStream.Length; } // 初始化mappedFile using (var mappedFile = MemoryMappedFile.CreateFromFile(openFileDialog.FileName, FileMode.Open, null,length)) { // Create writer to MMF using (var writer = mappedFile.CreateViewAccessor(offset, length, MemoryMappedFileAccess.ReadWrite)) { // 取得MyColor結構大小 int colorSize = Marshal.SizeOf(typeof(MyColor)); MyColor color; // Make changes to the view. for (long i = 0; i < length; i += colorSize) { writer.Read(i, out color); color.Brighten(30); writer.Write(i, ref color); } } return; } } // 自定義顏色以及加亮方法 public struct MyColor { // Bitmap 順序結構為B.G.R public Byte Blue; public Byte Green; public Byte Red; // Make the view brigher. public void Brighten(short value) { Red = (Byte)Math.Min(Byte.MaxValue, (Byte)Red + value); Green = (Byte)Math.Min(Byte.MaxValue, (Byte)Green + value); Blue = (Byte)Math.Min(Byte.MaxValue, (Byte)Blue + value); } }
沒有留言:
張貼留言