我想用图片创建用户个人资料。该用户可以上传他的照片,在他的个人资料中会有这张照片,在论坛中会有原始照片创建的小图片。我没有问题显示图像,但调整大小。我在控制器中有这个代码,用户可以在其中更改他的信息(姓名,年龄......)并可以上传照片:
[HttpPost, ValidateInput(false)]
public ActionResult Upravit(int id, FormCollection collection, HttpPostedFileBase file)
{
try
{
var user = repo.Retrieve(id);
if (TryUpdateModel(user))
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Fotky/Profilove/"), (user.Name.Name + " " + user.Name.Surname + Path.GetExtension(fileName)));
file.SaveAs(path);
user.ImagePath = "/Fotky/Profilove/" + user.Name.Name + " " + user.Name.Surname + Path.GetExtension(fileName);
}
repo.Save(user);
return RedirectToAction("Index");
}
return View();
}
catch
{
return View();
}
}
我的观点如下:
@using (Html.BeginForm("Upravit", "Uzivatel", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>User</legend>
@Html.HiddenFor(model => model.UserID)
<div class="editor-label">
@Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
</div>
.
.
<input type="file" name="file" id="file" />
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
正如我所说,我只需要帮助将控制器添加到控制器中,从原始图像创建小图像并将其保存到。谢谢你的帮助
答案 0 :(得分:1)
在C#中有大量关于重新调整图像大小的例子。所以只需选择一种你喜欢的方法。这里是@Craig Stuntz链接到您的问题的评论。如果您不喜欢这种方法,只需选择another one并进行调整。
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
// TODO: adjust the filenames here
var path = Path.Combine(Server.MapPath("~/"), fileName);
using (var input = new Bitmap(file.InputStream))
{
int width;
int height;
if (input.Width > input.Height)
{
width = 128;
height = 128 * input.Height / input.Width;
}
else
{
height = 128;
width = 128 * input.Width / input.Height;
}
using (var thumb = new Bitmap(width, height))
using (var graphic = Graphics.FromImage(thumb))
{
graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
graphic.DrawImage(input, 0, 0, width, height);
using (var output = System.IO.File.Create(path))
{
thumb.Save(output, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
}