Image Resize while file upload

2019-09-07 04:31发布

I my wpf mvvm application I am trying to upload an image to the database.The code is working fine and the image save to the db as image.I need to implement resize the image while upload.I mean When click upload the image will resize dynamically and save to db Here is my 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;
    }
}  

Please help

Thanks in advance

标签: c# wpf image mvvm
1条回答
该账号已被封号
2楼-- · 2019-09-07 05:23

I don't know exactly for which platform you're programming, but I know of a method that involves adding a check, to measure the width and height of an UIImage. If it's greater than a certain pixels, you can resize it with help of the UIGraphics. It should look something like this:

if (image.Size.Width >= 1000 || image.Size.Height >= 1000) 
{
    var width = images [i].Size.Width;
    var height = images [i].Size.Height;
    var newWidth = 900;
    var newHeigth = height * newWidth / width;

    UIGraphics.BeginImageContext (new SizeF (newWidth, newHeigth));
    image.Draw (new RectangleF (0, 0, newWidth, newHeigth));
    image = UIGraphics.GetImageFromCurrentImageContext ();
    UIGraphics.EndImageContext ();
}

Again, I don't know if this method works for the platform you're programming, but you could give it a try.

Hope this helps. Good luck!

查看更多
登录 后发表回答