以下是示例代码:

using System;
using System.IO;
using System.Windows.Forms;

namespace RasterDataAnalyzer
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void openButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Raster data files (*.tif, *.img)|*.tif;*.img";
            openFileDialog.Title = "Select a raster data file";

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string filePath = openFileDialog.FileName;
                try
                {
                    // Open the raster data file as binary
                    using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
                    {
                        // Read the header information (assuming it is a simple format like ESRI GRID)
                        int ncols = reader.ReadInt32();
                        int nrows = reader.ReadInt32();
                        double xllcorner = reader.ReadDouble();
                        double yllcorner = reader.ReadDouble();
                        double cellsize = reader.ReadDouble();
                        double nodataValue = reader.ReadDouble();

                        // Loop through each row and column to calculate the sum of pixel values
                        double sum = 0;
                        for (int row = 0; row < nrows; row++)
                        {
                            for (int col = 0; col < ncols; col++)
                            {
                                double pixelValue = reader.ReadDouble();
                                if (pixelValue != nodataValue)
                                {
                                    sum += pixelValue;
                                }
                            }
                        }

                        // Display the result
                        MessageBox.Show("The sum of pixel values is: " + sum.ToString());
                    }
                }
                catch (IOException ex)
                {
                    MessageBox.Show("Error reading file: " + ex.Message);
                }
            }
        }
    }
}

这个代码打开一个OpenFileDialog对话框,用户可以选择一个栅格数据文件。然后,它读取文件头信息和像素值,并计算像素值的总和。最后,它显示一个消息框,显示总和。请注意,这个代码假设栅格数据文件的格式是简单的,如ESRI GRID。如果您有不同的格式,请相应地修改代码

给出代码实现功能:C#中通过open file dialog读取栅格数据并计算其像元值总和

原文地址: http://www.cveoy.top/t/topic/d5mh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录