2

In my wpf mvvm application I write a code for image upload and save to database. The code is working fine and the image save to the data base. Here I need to retrieve the image from the database and show in a Image box.Here is my Insert code

public void Upload(object obj)
{
    try
    {
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        dlg.DefaultExt = ".png";
        dlg.Filter = "Image files (*.png;*.jpg)|*.png;*.jpg";
        Nullable<bool> result = dlg.ShowDialog();
        if (result == true)
        {
            string filename = dlg.FileName;
            UploadText = filename;
            FileStream FS = new FileStream(filename, FileMode.Open, FileAccess.Read);
            byte[] img = new byte[FS.Length];
            FS.Read(img, 0, Convert.ToInt32(FS.Length));
            UploadLogo = img;
            Stream reader = File.OpenRead(filename);
            System.Drawing.Image photo = System.Drawing.Image.FromStream((Stream)reader);
            MemoryStream finalStream = new MemoryStream();
            photo.Save(finalStream, ImageFormat.Png);
            // translate to image source
            PngBitmapDecoder decoder = new PngBitmapDecoder(finalStream, BitmapCreateOptions.PreservePixelFormat,
                                                BitmapCacheOption.Default);
            ClientLogo = decoder.Frames[0]; ;
        }
    }

    catch (Exception ex)
    {
        throw ex;
    }
}

how can I convert this byte data to image

Thanks in advance

daniele3004
  • 13,072
  • 12
  • 67
  • 75
Arun
  • 1,402
  • 10
  • 32
  • 59
  • Answered this a few weeks ago http://stackoverflow.com/questions/25862980/how-to-download-and-view-images-from-sql-server-table/25863338 – Aymeric Nov 05 '14 at 13:22

1 Answers1

3

Use Below Code

            object binaryData = ("select ImageDataColunm from table where id=yourID");// use your code to retrive image from database and store it into 'object' data type
            byte[] bytes = (byte[])binaryData;
            string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
            AspImageID.ImageUrl= "data:image/png;base64," + base64String;

EDIT: and you can See the Solution here fro WPF

prog1011
  • 3,425
  • 3
  • 30
  • 57
  • Hello I am checking.But it is not working.. I am using image tool in wpf.so it need the image source. AspImageID.ImageUrl is string – Arun Nov 05 '14 at 13:35
  • in my code Uploadlogo having the byte from database This is my imagesource property private ImageSource _clientlogo; public ImageSource ClientLogo { get { return _clientlogo; } set { _clientlogo = value; OnPropertyChanged("ClientLogo"); } } – Arun Nov 05 '14 at 13:36
  • @Arun - see the updated answer link – prog1011 Nov 05 '14 at 13:44
  • Anybody know why "data:image/png;base64," is removed before the image is stored and re-added when it is read? – Zeek2 Jan 12 '21 at 12:06