我的wpf mvvm应用程序我正在尝试将图像上传到数据库。代码工作正常,图像保存到数据库作为图像。我需要实现在上传时调整图像大小。我的意思是当点击上传时image将动态调整大小并保存到db 这是我的代码
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;
}
}
请帮忙
提前致谢
答案 0 :(得分:0)
我不确切知道您正在编程的平台,但我知道一种方法,包括添加一个检查,以测量UIImage的宽度和高度。如果它大于某个像素,您可以借助UIGraphics调整其大小。看起来应该是这样的:
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 ();
}
同样,我不知道这种方法是否适用于您正在编程的平台,但您可以尝试一下。
希望这会有所帮助。祝你好运!