C# winform 上传图片 显示图片

原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。 http://long7s.blog.51cto.com/2889364/587090
最近正在用C#做一个小的程序,其中用涉及到了照片的存取与显示,在网上搜索了很多有关的代码,但是几乎没有完整,大部分只是其中的存取或者显示代码,笔者将其整理了一下,形成了一个集照片上传到数据库、照片显示于一体的小模块。
  
  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Text;  
  7. using System.Windows.Forms;  
  8. using System.IO;  
  9. using System.Data.SqlClient;  
  10.  
  11. namespace WindowsApplication1  
  12. {  
  13.     public partial class Form1 : Form  
  14.     {  
  15.         public Form1()  
  16.         {  
  17.             InitializeComponent();  
  18.         }  
  19.         //选择按钮事件处理  
  20.         private void button1_Click(object sender, EventArgs e)  
  21.         {  
  22.             openFileDialog1.InitialDirectory = "C:\\";  
  23.             openFileDialog1.Filter = "图片文件 (*.jpg)|*.jpg";  
  24.             openFileDialog1.FilterIndex = 1;  
  25.             openFileDialog1.RestoreDirectory = true;  
  26.             openFileDialog1.Multiselect = true;  
  27.             if (openFileDialog1.ShowDialog() == DialogResult.OK)  
  28.             {  
  29.                 textBox1.Text = openFileDialog1.FileName;  
  30.             }  
  31.         }  
  32.         //上传按钮事件处理  
  33.         private void button2_Click(object sender, EventArgs e)  
  34.         {  
  35.             Save(PhotoToArray(textBox1.Text.ToString()));  
  36.         }  
  37.         //将图片信息转换成二进制信息  
  38.         private byte[] PhotoToArray(string path)  
  39.         {  
  40.             FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);  
  41.             byte[] bufferPhoto = new byte[stream.Length];  
  42.             stream.Read(bufferPhoto, 0, Convert.ToInt32(stream.Length));  
  43.             stream.Flush();  
  44.             stream.Close();  
  45.             return bufferPhoto;  
  46.         }  
  47.         //把二进制的图片插到数据库  
  48.         private void Save(byte[] image)  
  49.         {  
  50.             string sql = "insert into Photo(photo_Info) values(@photo)";  
  51.             SqlParameter param = new SqlParameter();  
  52.             param = new SqlParameter("@photo", SqlDbType.Image);  
  53.             param.Value = image;  
  54.             SqlCommand commd = new SqlCommand(sql, DBhelper.con);  
  55.             commd.Parameters.Add(param);  
  56.             try 
  57.             {  
  58.                 DBhelper.con.Open();  
  59.                 commd.ExecuteNonQuery();  
  60.                 MessageBox.Show("您已经把图片成功的插入数据库!");  
  61.             }  
  62.             catch (Exception ex)  
  63.             {  
  64.                 MessageBox.Show(ex.Message);  
  65.             }  
  66.             finally 
  67.             {  
  68.                 DBhelper.con.Close();  
  69.             }  
  70.         }  
  71.         //显示图片按钮事件处理  
  72.         private void button3_Click(object sender, EventArgs e)  
  73.         {  
  74.             string strSQL = "Select   [photo_Info]   From   [Photo]   Where   [photo_Id]=(@photo)";  
  75.             SqlParameter param = new SqlParameter();  
  76.             param = new SqlParameter("@photo", SqlDbType.Int);  
  77.             param.Value = comboBox1.Text.ToString();  
  78.             SqlCommand cmd = new SqlCommand(strSQL, DBhelper.con);  
  79.             cmd.Parameters.Add(param);  
  80.             DBhelper.con.Open();  
  81.             System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader();  
  82.             try 
  83.             {  
  84.                 reader.Read();  
  85.                 MemoryStream ms = new MemoryStream((byte[])reader["photo_Info"]);  
  86.                 System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);  
  87.                 this.pictureBox1.Image = image;  
  88.             }  
  89.             catch (Exception ex)  
  90.             {  
  91.                 MessageBox.Show(ex.Message);  
  92.             }  
  93.             finally 
  94.             {  
  95.                 DBhelper.con.Close();  
  96.             }  
  97.         }  
  98.         private void Form1_Load(object sender, EventArgs e)  
  99.         {  
  100.             // TODO: 这行代码将数据加载到表“myPhotoDataSet.Photo”中。您可以根据需要移动或移除它。  
  101.             this.photoTableAdapter.Fill(this.myPhotoDataSet.Photo);  
  102.         }  
  103.     }  
  104. }  
  105.  
  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是C# WinForm上传文件的示例代码: ```csharp private void btnUpload_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); if (openFileDialog.ShowDialog() == DialogResult.OK) { string filePath = openFileDialog.FileName; string url = "http://localhost/UploadFileWeb/WebForm1.aspx"; string paramName = "file"; HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); request.ContentType = "multipart/form-data; boundary=" + boundary; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n"; string header = string.Format(headerTemplate, paramName, Path.GetFileName(filePath)); byte[] headerBytes = Encoding.UTF8.GetBytes(header); requestStream.Write(headerBytes, 0, headerBytes.Length); using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, bytesRead); } } byte[] trailerBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); requestStream.Write(trailerBytes, 0, trailerBytes.Length); } using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string responseText = reader.ReadToEnd(); MessageBox.Show(responseText); } } } } ``` 该示例代码使用HttpWebRequest类向指定的URL上传文件。在上传文件之前,需要设置请求的Method为POST,ContentType为multipart/form-data,并设置请求头部的边界(boundary)。然后,将文件内容写入请求流中,最后发送请求并获取响应。在获取响应后,可以从响应流中读取服务器返回的内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值