本文主要是介绍GIS笔记_普通tif文件转成array数组 c#,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
引用的库文件:
using System;
using System.Collections;using System.Windows.Media.Imaging;
using System.Drawing;
using System.Drawing.Imaging;
主要功能函数 :
public static System.Array TifToArray(string tifPath)
{//tif -> bitmapImage tifImage = Image.FromFile(tifPath);Bitmap bitmap = new Bitmap(tifImage);int height = (int)bitmap.Height;int width = (int)bitmap.Width;System.Array pixelsArray = Array.CreateInstance(typeof(float), height, width);GrayBitmapData grayBitmapdata = new GrayBitmapData(bitmap);byte[,] bitData = null;bitData = grayBitmapdata.GetData();for (int i = 0; i < height; i++){for (int j = 0; j < width; j++){int[] indices = { i, j };pixelsArray.SetValue(bitData[i, j], indices);}}return pixelsArray;
}
辅助类:
(此处假设输入的tif文件是32位的图像,format32bppArgbFlag)
class GrayBitmapData
{private byte[,] Data;private int Width;private int Height;public GrayBitmapData(){this.Width = 0;this.Height = 0;this.Data = null;}public GrayBitmapData(Bitmap bmp){//from Bitmap to BitmapDataBitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);this.Width = bmpData.Width;this.Height = bmpData.Height;Data = new byte[Height, Width];int temp = 0;unsafe{byte* ptr = (byte*)bmpData.Scan0.ToPointer();for (int i = 0; i < Height; i++){for (int j = 0; j < Width; j++){temp = (int)(0.114 * (*ptr++)) + (int)(0.587 * (*ptr++)) + (int)(0.299 * (*ptr++));//skip the blank or unused space bits ptr++;Data[i, j] = (byte)temp;}//skip the blank space bit//if (format24bppRgbFlag) ptr += bmpData.Stride - Width * 3;//if (format32bppArgbFlag) ptr += 0; // += bmpData.Stride - Width * 4; // https://www.cnblogs.com/dearzhoubi/p/8553763.html}}bmp.UnlockBits(bmpData);}public byte [,] GetData(){return Data;}
}
其他可能有用函数:(Bitmap <= 相互转换=> BitmapSource)
public static System.Drawing.Bitmap ToBitmap(BitmapSource source)
{using (System.IO.MemoryStream ms = new System.IO.MemoryStream()){BitmapEncoder encoder = new BmpBitmapEncoder();encoder.Frames.Add(BitmapFrame.Create(source));encoder.Save(ms);return new System.Drawing.Bitmap(ms);}
}public static BitmapSource ToBitmapSource(System.Drawing.Bitmap bmp)
{System.IntPtr hBitmap = bmp.GetHbitmap();try{return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, System.IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());}finally{DeleteObject(hBitmap);}
}[System.Runtime.InteropServices.DllImport("Gdi32.dll")]
private static extern bool DeleteObject(System.IntPtr hObject);
这篇关于GIS笔记_普通tif文件转成array数组 c#的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!