在c# xaml中读取图像并将其存储到数组中

本文关键字:存储 数组 图像 xaml 读取 | 更新日期: 2023-09-27 18:04:44

我正在尝试打开图像文件(JPEG或JPG)并将图像存储到c# xaml中的数组中。虽然我可以打开文件并将其转换为位图图像,但我不能将其存储到数组中。下面是我的代码:

    public int row;
    public int column;
    public byte[] bmp;
    public byte[,] data;
    public double width;
    public double height;
        private void button1_Click(object sender, RoutedEventArgs e)
    {
        // Create OpenFileDialog
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        // Set filter for file extension and default file extension
        dlg.FileName = "";
        //dlg.DefaultExt = ".jpg";
        dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
        // Display OpenFileDialog by calling ShowDialog method
        Nullable<bool> result = dlg.ShowDialog();
        if (result == true)
        {
            string filename = dlg.FileName;
            bmp = readfile(filename);
            int x = bmp.Length;
            data = new byte[(int)Math.Sqrt(x), (int)Math.Sqrt(x)];
            row = 0;
            column = 0;
            for (int i = 0; i < x; i++)
            {
                row = i % (int)Math.Sqrt(x);
                column = i /(int)Math.Sqrt(x);
                data[row, column] = bmp[i];
            }

        }
        }
    public byte[] readfile(String filename)
    {
        Image img = new Image();
        BitmapImage bitmapImage = new BitmapImage();
        Uri uri = new Uri(filename);
        bitmapImage.UriSource = uri;
        img.Source = bitmapImage;
        MemoryStream memStream = new MemoryStream();              
        JpegBitmapEncoder encoder = new JpegBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
        encoder.Save(memStream);
        return memStream.GetBuffer();
        width = bitmapImage.Width;
        height = bitmapImage.Height;

在c# xaml中读取图像并将其存储到数组中

我不明白你为什么用这么复杂的方式做这件事。如果你想创建一个BitmapImage,并且你有一个文件系统的路径,为什么不使用:

BitmapImage bImage = new BitmapImage(new Uri(dlg.FileName));

然后你可以很容易地将图像存储在数组/列表通过列表/数组:

List<BitmapImage> _images = new List<BitmapImage>();
_images.Add(bImage);

注意,在数组/列表中存储大图像可能会消耗大量内存。

编辑

如果您想简单地存储字节数组,请使用:

byte[] buff = File.ReadAllBytes(dlg.FileName)

注意,byte[]包含一个文件,所以如果您想存储多个文件,请使用二维byte[] (byte[][])或List<byte[]>

获取图像的高度和宽度:

System.Drawing.Image img = System.Drawing.Image.FromFile(dlg.FileName);
Console.Write("Width: " + img.Width + ", Height: " + img.Height);