This question already has answers here:
How to download and view images from SQL Server table?

(1个答案)



Image Resize while file upload

(1个答案)


6年前关闭。




在我的wpf mvvm应用程序中,我编写了一个用于图像上传并保存到数据库的代码。
该代码工作正常,并且图像保存到数据库中。
在这里我需要从数据库中检索图像并显示在图像框中。这是我的插入代码
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;
    }
}

如何将这个字节数据转换为图像

提前致谢

最佳答案

使用以下代码

            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;

编辑:,您可以See the Solution here fro WPF

09-26 19:21
查看更多