【问题标题】:The value was either too small or too large for an unsigned byte C#对于无符号字节 C#,该值太小或太大
【发布时间】:2017-10-01 19:31:52
【问题描述】:

我有 2 种方法,如下所示,但我无法让它工作。我正在尝试从OpenFileDialog 打开一个.png 文件并将其显示在ImageBox 上:

public static Bitmap ToBitmap(this string input)
{
    List<byte> splitBytes = new List<byte>();
    string byteString = "";
    foreach (char i in input)
    {
        byteString += i;
        if (byteString.Length == 3)
        {
            splitBytes.Add(Convert.ToByte(byteString));
            byteString = "";
        }
    }
    if (byteString != "")
        splitBytes.AddRange(Encoding.ASCII.GetBytes(byteString));
    using (var ms = new MemoryStream(splitBytes.ToArray()))
    {
        var img = Image.FromStream(ms);
        Bitmap output = new Bitmap(img);
        return output;
    }
}

public static string StringFromFile(string input)
{
    StreamReader sr = new StreamReader(input);
    string file = string.Empty;
    while (sr.EndOfStream == false)
    {
        file += sr.Read();
    }
    return file;
}

在另一个文件中我尝试使用该方法:

OpenFileDialog OFD = new OpenFileDialog();
OFD.Filter = "Images (*.png)|*.png";
OFD.ShowDialog();
pictureBox1.BackgroundImageLayout = ImageLayout.Stretch;
pictureBox1.BackgroundImage = StringToBitmapConverter.ToBitmap(StringToBitmapConverter.StringFromFile(OFD.FileName));

但我得到了这个例外:

System.OverflowException: '对于无符号字节而言,值太大或太小。'

请帮忙! 我在一个名为StringToBitmapConverter 的类中使用这些方法,但有一个错误给我带来了麻烦,谁能帮助我?

【问题讨论】:

    标签: c# winforms byte overflowexception


    【解决方案1】:

    所以根据documentationConvert.ToByte(string value)

    将数字的指定字符串表示形式转换为等效的 8 位无符号整数。

    如果:

    该方法将抛出OverflowException

    value 表示小于 Byte.MinValue 或大于 Byte.MaxValue 的数字。

    所以byteString的值在这一行必须小于0或大于255:

    splitBytes.Add(Convert.ToByte(byteString));

    【讨论】:

    • 但是我该如何解决这个问题,这就是我正在寻求帮助的原因。
    • @Techcraft7 这取决于你想要做什么,目前还不清楚你想用splitBytes.Add(Convert.ToByte(byteString)); 做什么。编辑:我刚刚查看了您的代码,您正在尝试使用 Encoding.ASCII.GetBytes(byteString) 读取文件的字节以将其作为位图打开,这将永远无法工作。 Encoding.ASCII 不能代表所有可能的字节值。
    • 那我该怎么做呢?你能做一个代码示例吗?
    • @Techcraft7 做什么?您需要更新您的问题,解释文件格式是什么以及您尝试使用它做什么。
    【解决方案2】:

    您可以使用 try { } catch 捕获错误或使用 byte.TryParse 仅转换那些实际可转换的数字。

    File.ReadAllText可以从文件中读取文本

    您的算法将读取的文本拆分为 3 个字符块并将文本解释为字节:

    "23405716119228936" -> 234,57,161,192,289,36 .... 289 不适合字节 -> 异常。检查文件内容。

    if (byte.TryParse(byteString, out var b))
    {
        splitBytes.Add(b);
    }
    else
    {
        // this thing is not convertable to byte, do something with it....
    }
    

    编辑#1:

    我猜想在 PNG 文件中读取为“字符串”并按照您的方式转换它们是行不通的。

    PNG 文件具有内部格式,它们是经过编码的。看 https://www.w3.org/TR/PNG/ 要么 https://de.wikipedia.org/wiki/Portable_Network_Graphics

    它们不是字符串,您可以简单地分组为 3 个字符,转换为字节并重新解释为内存字符串。

    对于咯咯笑,在你的文件上试试这个,看看你的输入是什么。:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    
    internal class Program
    {
        static void Main(string[] args)
        {
            foreach (var s in Make3CharChunks(File.ReadAllText( /*your file path here*/ ""))
                Console.WriteLine(s);
    
            Console.ReadLine();
        }
    
        static IEnumerable<string> Make3CharChunks(string s)
                            => s.Aggregate(new List<string>(), (acc, c) =>
                    {
                        if (acc.Any() && acc.Last().Count() < 3)
                            acc[acc.Count - 1] = $"{acc.Last()}{c}";
                        else
                            acc.Add(c.ToString());
    
                        return acc;
                    });
    }
    

    【讨论】:

    • 当我说
      splitBytes.Add(Byte.TryParse(byteString, out byte result));
      它说它不能将字节转换为布尔值。 (CS1503)
    • 当我执行该代码时,它会在此行引发另一个错误: var img = Image.FromStream(ms);它说“参数无效”
    【解决方案3】:

    如果您所做的只是尝试打开一个 png,您可以丢弃大部分代码并将其简化为

    OpenFileDialog OFD = new OpenFileDialog();
    OFD.Filter = "Images (*.png)|*.png";
    var result = OFD.ShowDialog()    
    if(result == DialogResult.OK) //You need to check to see if they clicked OK or Cancel.
    {
        pictureBox1.BackgroundImageLayout = ImageLayout.Stretch;
    
        var oldImage = pictureBox1.BackgroundImage
        pictureBox1.Image = new Bitmap(OFD.FileName); //Shouold be Image, not BackgroundImage for a picture box.
        if(oldImage != null)
        {
            oldImage.Dispose();
        }
    
    }
    

    【讨论】:

    • 好吧,我正在尝试制作一包人们可以用于软件的 .dll 文件,我的第一个是字符串到位图。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    • 2011-09-14
    • 2017-06-08
    相关资源
    最近更新 更多