图像到字节到字符串 [英] Image to byte to string
问题描述
您好!我现在能够将DB中的图像保存并查看为字节,现在我需要将其转换为字符串,我收到错误。任何帮助或更正将不胜感激。谢谢。
我尝试了什么:
private void button1_Click (对象发送者,EventArgs e)
{
图像myImage = pictureBox1.Image;
byte []数据;
using(MemoryStream ms = new MemoryStream())
{
myImage.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
data = ms.ToArray();
string s3 = Convert.ToBase64String(data);
data = Convert.FromBase64String(s3);
}
con.Open();
cmd = new SqlCommand(INSERT INTO kenny(id,picture)VALUES(@ id,@ IM),con);
{
cmd.Parameters。 AddWithValue(@ IM,s3);
cmd.Parameters.AddWithValue(@ id,textBox1.Text);
cmd.ExecuteNonQuery();
}
con.Close();
}
Hello! I am now able to save and view Image from DB as a byte, now I need to convert it into string and I am receiving error. Any help or correction will be appreciated. Thank you.
What I have tried:
private void button1_Click(object sender, EventArgs e)
{
Image myImage = pictureBox1.Image;
byte[] data;
using (MemoryStream ms = new MemoryStream())
{
myImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
data = ms.ToArray();
string s3 = Convert.ToBase64String(data);
data = Convert.FromBase64String(s3);
}
con.Open();
cmd = new SqlCommand("INSERT INTO kenny (id,picture) VALUES (@id,@IM)", con);
{
cmd.Parameters.AddWithValue("@IM", s3);
cmd.Parameters.AddWithValue("@id", textBox1.Text);
cmd.ExecuteNonQuery();
}
con.Close();
}
推荐答案
拜托,帮自己一个忙,回顾一下C#基础知识:这是我本周末第三次看到这段代码,而你正在做的是犯了一个根本性的错误 - 然后忽略你得到的错误信息。
s3
是button1_Click
方法中的局部变量:
Please, do yourself a favour and review the C# basics: this is the third time I've seen that code this weekend, and what you are doing is making a fundamental mistake - then ignoring the error message you get.
s3
is a local variable in thebutton1_Click
method:
private void button1_Click(object sender, EventArgs e)
{
Image myImage = pictureBox1.Image;
byte[] data;
using (MemoryStream ms = new MemoryStream())
{
myImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
data = ms.ToArray();
string s3 = Convert.ToBase64String(data);
data = Convert.FromBase64String(s3);
}
并且它的范围仅限于声明它的代码块:包含大括号的集合。
因此,它不存在在你的之外使用
块,并且你得到编译器错误。
使用$ c $将定义移到之外c>阻止,它将编译:
And it's scope is restricted to the code block in which it is declared: the containing set of curly brackets.
As such, it doesn't exist outside your using
block, and you get a compiler error.
Move the definition outside the using
block, and it will compile:
private void button1_Click(object sender, EventArgs e)
{
Image myImage = pictureBox1.Image;
byte[] data;
string s3;
using (MemoryStream ms = new MemoryStream())
{
myImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
data = ms.ToArray();
s3 = Convert.ToBase64String(data);
data = Convert.FromBase64String(s3);
}
这篇关于图像到字节到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!