图像文件上传时调整大小 [英] Image Resize while file upload

查看:124
本文介绍了图像文件上传时调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的wpf mvvm应用程序我正在尝试将图像上传到数据库。代码工作正常,图像保存到数据库作为图像。我需要在上传时实现调整图像大小。我的意思是当点击上传时图像将动态调整大小并保存到db
这是我的代码

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;
    }
}  

请帮助

提前致谢

推荐答案

我不知道你编程的是哪个平台,但是我知道一个涉及添加检查的方法,以测量UIImage的宽度和高度。如果它大于某个像素,您可以在UIGraphics的帮助下调整它的大小。它看起来应该是这样的:

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!

这篇关于图像文件上传时调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆