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

huangapple go评论73阅读模式
英文:

How to assign an image value from a stream from a text file

问题

以下是您要翻译的部分:

"我正在尝试在一个项目中实现一个功能,允许用户上传他们自己的图像文件作为头像。我从图像中获取流并将其保存为 jpg 格式的文本文件,与用户的用户名一起保存在同一行。但是,当我尝试将图片框的图像设置为这个流时,我一直收到“参数无效”的错误消息。有没有人知道我做错了什么?

保存流到文本文件的代码:

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(textfile);
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;
    }
}

希望这可以帮助您解决问题。

英文:

I'm trying to implement a feature in a project where the user can upload their own image files to be used as an avatar, I get the stream from the image as jpg format and save it in a text file on the same line with the user's username where it's retrieved but I keep getting the error message "Parameter is not valid" when I try to set the image of a picturebox to the stream, does anyone know what I'm doing wrong?

The code that saves the stream to the text file;

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}");
}

The code setting the image of a picturebox to the stream, where the error appears;

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;
    }
}

答案1

得分: 1

根据Fildor的建议,使用base64对图像进行编码。

我使用winform(.Net Framework 4.8)进行了测试,并修改了您的代码。

我自定义了文本文件的保存地址和用户名的名称,并使用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());

        // 创建文件,如果文件存在则覆盖。
        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;
        }
    }
}

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

英文:

As Fildor said, use base 64 to encode the image.

I tested with winform (.Net Framework4.8) and modified your code.

I customized the save address of a txt file and the name of a username. And use openfiledialog to select the image address that needs to be uploaded.

The following is my demo:

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;
        }
    }
}

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

huangapple
  • 本文由 发表于 2023年2月27日 02:09:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75574040.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定