Visual Studio 如何从文本文件的流中分配图像值

gijlo24d  于 2023-03-03  发布在  其他
关注(0)|答案(1)|浏览(140)

我试图在一个项目中实现一个功能,用户可以上传自己的图像文件作为化身使用,我从图像中获取jpg格式的流,并将其保存在文本文件中,与检索到它的用户名在同一行,但当我试图将picturebox的图像设置为流时,我一直收到错误消息“参数无效”,有人知道我哪里做错了吗
将流保存到文本文件的代码;

customavatar = Image.FromFile(filename);

var stream = new System.IO.MemoryStream();
customavatar.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;

if(!File.Exists( textfile))
{
    File.Create( textfile);
}
using (StreamWriter sw = File.AppendText( textfile))
{
    sw.WriteLine("");
    sw.WriteLine($"{username},{stream}");
}

将图片框的图像设置到出现错误的流的代码;

string[] filelinesarray = File.ReadAllLines(text file);
foreach (string str in filelinesarray)
{
    if (str.Split(",")[0] == username)
    {
        byte[] byteArray = Encoding.ASCII.GetBytes(str.Split(",")[1]);
        MemoryStream stream = new MemoryStream(byteArray);

        Image img = Image.FromStream(stream);
        picturebox.Image = img;
    }
}
ryhaxcpt

ryhaxcpt1#

正如Fildor所说,使用base 64对图像进行编码。
我用winform(. Net Framework4.8)进行了测试,并修改了您的代码。
我自定义了一个txt文件的保存地址和用户名。并使用openfiledialog来选择需要上传的图像地址。
下面是我的演示:

private void button1_Click(object sender, EventArgs e)
{
    var openFileDialog = new OpenFileDialog();
    openFileDialog.Filter = "All Files (*.*)|*.*";
    openFileDialog.Title = "Select a file";
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        string filename = openFileDialog.FileName;
        var stream = new System.IO.MemoryStream();
        using (var customavatar = Image.FromFile(filename))
        {
            customavatar.Save(stream, ImageFormat.Jpeg);
        }
        var base64String = Convert.ToBase64String(stream.ToArray());

        // Create the file, or overwrite if the file exists.
        using (var fstream = new FileStream(textfile, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            using (var writer = new StreamWriter(fstream))
            {
                writer.Write($"{username},{base64String}");
            }
        }
    }
}
private void button2_Click(object sender, EventArgs e)
{
    string[] filelinesarray = File.ReadAllLines(textfile);
    foreach (string str in filelinesarray)
    {
        if (str.Split(',')[0] == username)
        {
            byte[] byteArray = Convert.FromBase64String(str.Split(',')[1]);
            MemoryStream stream = new MemoryStream(byteArray);
            Image img = Image.FromStream(stream);
            pictureBox1.Image = img;
        }
    }
}

相关问题