C#保存图片
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
保存图片两种办法,一种字节流存,一种存路径。
大多数人的做法是保存路径,这也是最好的方法。
用字节流操作很繁琐,而且效率不高。。。
两种方法的优势很明显,如果学习,两个都可以看看,如果是项目中肯定选择后者。给你一个帮助类吧...无论是图黑市文件都可以用:
using System;
using System.Collections.Generic; using ponentModel; using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; using System.Data.SqlClient;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string inputFile = string.Empty;
static SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Northwind;User ID=sa;Password=sa"); public Form1()
{
InitializeComponent();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
richTextBox1.AppendText("");
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "图像文件(*.jpg)|*.jpg|gif文件(*.gif)|*.*|所有文件(*.*)|*.*";
openFileDialog1.Title = "Select a JPG File";
openFileDialog1.FileName = "";
if (openFileDialog1.ShowDialog() == DialogResult.OK)------------------------------------选择本地文件
{
richTextBox1.Text = openFileDialog1.FileName;
inputFile = openFileDialog1.FileName;
InsertDB(inputFile);
}
}
private static void InsertDB(string file)
{
FileInfo finfo = new FileInfo(file); //绝对路径
if (finfo.Exists)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
mandText = "Insert into Categories(CategoryName,Picture) values('test',@Content)";
cmd.Parameters.Add("@Content", SqlDbType.Image, (int)finfo.Length, "Image字段名"); //注意,此处参数Size为写
入的字节数
//读取文件内容,写入byte数组---------------------------------------------------将文件存入数据库图片字段
byte[] content = new byte[finfo.Length];
FileStream stream = finfo.OpenRead();
stream.Read(content, 0, content.Length);
stream.Close();
cmd.Parameters["@Content"].Value = content; //为参数赋值
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
finally
{ conn.Close();}
}
}
private void button2_Click(object sender, EventArgs e)
{
SqlCommand myCommand = new SqlCommand("Select top 1 Picture from Categories order by CategoryID desc", conn);
--------------------------------------------------------------------------------从数据库中找到图片字段
try
{
conn.Open();
SqlDataReader myDataReader;
myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (myDataReader.Read())
{
byte[] bin = (byte[])myDataReader["Picture"];
MemoryStream stream = new MemoryStream(bin, true);
stream.Write(bin, 0, bin.Length);
pictureBox1.BackgroundImageLayout = ImageLayout.Center;
pictureBox1.Image = Bitmap.FromStream(stream); ---------------------------------------------------将图片显示在pictureBox
stream.Close();
}
conn.Close(); }
catch (SqlException SQLexc)
{ } } }
}