技术开发 频道

详解C#数据库存取图片三大方式

  大家看一下效果吧

直接把图片的Base64String码进行存取
 

  在这里我们只要单击选择图片直接就可以更换。这些很简单但是我个人感觉还是很常用的,而且网上关于这块的例子着实不少,不过真正能帮上忙的还真不多,因为我们的好几个项目里用到了这些方法,或多或少的还是有些员工不怎么会, 在这里贴一贴方便新手查看吧。呵呵

  下面的本例子的所有代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace WindowsFormsApplication1
{
    
public partial class Form1 : Form
    {
        
public Form1()
        {
            InitializeComponent();
        }

        
string pic = "";
        
//加载图片
        
private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                
if (!string.IsNullOrEmpty(pic))
                {
                    
byte[] imageBytes = Convert.FromBase64String(pic);
                    MemoryStream memoryStream
= new MemoryStream(imageBytes, 0, imageBytes.Length);
                    memoryStream.Write(imageBytes,
0, imageBytes.Length);
                    Image image
= Image.FromStream(memoryStream);

                    
// 将图片放置在 PictureBox 中
                    this.pictureBox1.SizeMode
= PictureBoxSizeMode.Zoom;
                    this.pictureBox1.Image
= image;
                }
            }
            catch { }
        }

        
//选择图片
        
private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openfile
= new OpenFileDialog();
            openfile.Title
= "请选择客户端longin的图片";
            openfile.Filter
= "Login图片(*.jpg;*.bmp;*png)|*.jpeg;*.jpg;*.bmp;*.png|AllFiles(*.*)|*.*";
            
if (DialogResult.OK == openfile.ShowDialog())
            {
                try
                {
                    Bitmap bmp
= new Bitmap(openfile.FileName);
                    pictureBox1.Image
= bmp;
                    pictureBox1.SizeMode
= PictureBoxSizeMode.Zoom;
                    MemoryStream ms
= new MemoryStream();
                    bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                    
byte[] arr = new byte[ms.Length];
                    ms.Position
= 0;
                    ms.Read(arr,
0, (int)ms.Length);
                    ms.Close();
                    pic
= Convert.ToBase64String(arr);
                }
                catch { }
            }
        }
    }
}

0
相关文章