WPF用流的方式上传/显示/下载图片文件(保存在数据库)

1.xaml

<Window x:Class="WpfUploadDispalyIMG.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="800">
    <Grid>
        <TextBox Height="23" HorizontalAlignment="Left" Margin="14,12,0,0" Name="FileNameTextBox" VerticalAlignment="Top" Width="394" IsEnabled="False" />
        <Button Content="浏览" Height="23" HorizontalAlignment="Left" Margin="414,12,0,0" Name="btBrowse" VerticalAlignment="Top" Width="49" Click="btBrowse_Click" />
        <Button Content="上传" Height="23" HorizontalAlignment="Left" Margin="469,12,0,0" Name="btUpdate" VerticalAlignment="Top" Width="49" Click="btUpdate_Click" />
        <Image   Margin="12,41,0,0" Name="image1" Stretch="Fill"  Width="200" Height="200" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="590,13,0,0" Name="tbName" VerticalAlignment="Top" Width="46" />
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="529,16,0,0" Name="textBlock1" Text="输入姓名:" VerticalAlignment="Top" />
        <Button Content="查看照片" Height="23" HorizontalAlignment="Left" Margin="642,13,0,0" Name="btShow" VerticalAlignment="Top" Width="65" Click="btShow_Click" />
        <Button Content="保存" Height="23" HorizontalAlignment="Left" Margin="708,13,0,0" Name="btSave" VerticalAlignment="Top" Width="65" Click="btSave_Click" />
    Grid>
Window>

2.cs

using System;
using System.Linq;
using System.Windows;
using System.Windows.Media.Imaging;
using System.IO;
using System.Data.Linq;

namespace WpfUploadDispalyIMG
{

    public partial class MainWindow : Window
    {
        DataClasses1DataContext db = new DataClasses1DataContext();
        public MainWindow()
        {
            InitializeComponent();
        }    
        //添加图片并浏览
        private void btBrowse_Click(object sender, RoutedEventArgs e)
        {
            //创建"打开文件"对话框
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            //设置文件类型过滤
            dlg.Filter = "图片|*.jpg;*.png;*.gif;*.bmp;*.jpeg";

            // 调用ShowDialog方法显示"打开文件"对话框
            Nullable<bool> result = dlg.ShowDialog();

            if (result == true)
            {
                //获取所选文件名并在FileNameTextBox中显示完整路径
                string filename = dlg.FileName;
                FileNameTextBox.Text = filename;

                //在image1中预览所选图片
                BitmapImage image = new BitmapImage(new Uri(filename));
                image1.Source = image;
                image1.Width = image.Width;
                image1.Height = image.Height;
            }
        }

        //上传图片至数据库
        private void btUpdate_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(FileNameTextBox.Text))
            {
                 UploadIMG();
                MessageBox.Show("OK!");
                FileNameTextBox.Text = string.Empty;

            }
            else
                MessageBox.Show("请选择图片!");
        }
        private void UploadIMG()
        {
            //将所选文件的读入字节数组img
            byte[] img = File.ReadAllBytes(FileNameTextBox.Text);
            string fileName = System.IO.Path.GetFileNameWithoutExtension(FileNameTextBox.Text);
                //FileNameTextBox.Text.Substring(FileNameTextBox.Text.LastIndexOf('\\')+1);
            Crew newCrew = new Crew()
            {
                //[key]=[value]
                photo = img,//将图片写入数据库
                name = fileName
            };
            db.Crew.InsertOnSubmit(newCrew);
            db.SubmitChanges();
        }


        //显示图片
        private void btShow_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //根据文件名读取二进制形式的图片
                Binary p = db.Crew.FirstOrDefault(c => c.name == tbName.Text.Trim()).photo;
                byte[] img = p.ToArray();
                ShowSelectedIMG(img);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void ShowSelectedIMG(byte[] img)
        {
            BitmapImage image = new BitmapImage();
            //以流的形式初始化图片
            image.BeginInit();
            image.StreamSource = new MemoryStream(img);
            image.EndInit();

            image1.Source = image;
            image1.Width = image.PixelWidth;
            image1.Height = image.PixelHeight;
        }


        //保存为文件
        private void btSave_Click(object sender, RoutedEventArgs e)
        {
            //创建"保存文件"对话框

            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            //设置默认文件类型
            dlg.DefaultExt = ".png";
            Nullable<bool> result = dlg.ShowDialog();

            if (result == true)
            {
                //获取要保存文件名的完整路径
                string filename = dlg.FileName;
                //将文件流写入文件
                FileStream write = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, System.IO.FileShare.Read);
                Binary p = db.Crew.FirstOrDefault(c => c.name == tbName.Text.Trim()).photo;
                byte[] img = p.ToArray();
                write.Write(img, 0, img.Count());
               write.Close();
               MessageBox.Show("成功保存");
            }
        }
    }
}

文章转自:http://www.cnblogs.com/Laro/archive/2011/05/23/2054009.html

你可能感兴趣的:(C#学习和进阶)