您当前的位置: 首页 >  ar

惊鸿一博

暂无认证

  • 4浏览

    0关注

    535博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

GIS笔记_普通tif文件转成array数组 c#

惊鸿一博 发布时间:2020-09-06 23:19:05 ,浏览量:4

引用的库文件:

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 -> bitmap
	Image 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 BitmapData
		BitmapData 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);

 

关注
打赏
1663399408
查看更多评论
立即登录/注册

微信扫码登录

0.0348s