static void SaveImage(byte[] imageBytes, string path) { using (var stream = new MemoryStream(imageBytes)) using (var img = Image.FromStream(stream)) { Size size = new Size(ImageWidth, (int)img.Height * ImageWidth / img.Width); using (Image thumbnail = new ImageThumbnailCreator(img).CreateImageThumbnail(size)) ImageUtils.SaveImage(thumbnail, path); } }
public IActionResult UploadFormFile(IFormFile file) { if (file == null) { throw new HttpBadRequestException("请将Content-Type设置application/x-www-form-urlencoded,然后在formData的file附上图标文件"); } string iconExt = ""; Microsoft.Extensions.Primitives.StringValues headerVar; Request.Headers.TryGetValue("fileExt", out headerVar); if (headerVar.Count > 0) { iconExt = headerVar[0].Trim(); } if (string.IsNullOrWhiteSpace(iconExt)) { throw new HttpBadRequestException("请在Headers上添加fileExt标识icon的扩展名"); } iconExt = iconExt.Replace(".", string.Empty); //先把文件保存到临时文件夹,计算md5 var tmpPath = Path.Combine(tmpFileFolder, $"{Guid.NewGuid()}.{iconExt}"); using (FileStream fs = System.IO.File.Create(tmpPath)) { file.CopyTo(fs); // 清空缓冲区数据 fs.Flush(); } var md5 = MD5Gen.CalcFile(tmpPath); var fileName = $"{md5}.{iconExt}"; var iconPath = Path.Combine(iconFolder, fileName); //如果文件不存在资源文件夹,拷贝存储 if (!System.IO.File.Exists(iconPath)) { System.IO.File.Copy(tmpPath, iconPath); } //为文件生成缩略图标 ImageThumbnailCreator.SaveImageThumbnails(iconPath); //删除临时文件 if (System.IO.File.Exists(tmpPath)) { System.IO.File.Delete(tmpPath); } return(Ok($"/{OSSConst.AppRouteArea}/{OSSConst.IconFolder}/{fileName}")); }
protected void fileUpload_FileUploadComplete(object sender, FileUploadCompleteEventArgs e) { try { using (System.Drawing.Image original = System.Drawing.Image.FromStream(e.UploadedFile.FileContent)) using (System.Drawing.Image thumbnail = new ImageThumbnailCreator(original).CreateImageThumbnail(new Size(100, 100))) Session["logo"] = imageToByteArray(thumbnail); } catch (Exception ex) { throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException); } }
protected string SavePostedFile(UploadedFile uploadedFile) { if (!uploadedFile.IsValid) { return(string.Empty); } string fileName = Path.ChangeExtension(Path.GetRandomFileName(), ".png"); string fullFileName = ""; switch (ImageType) { case "Profile": fullFileName = CombinePath(fileName, UploadDirectoryProfileImages); break; case "Company": fullFileName = CombinePath(fileName, UploadDirectoryCompanyImages); break; } using (System.Drawing.Image original = System.Drawing.Image.FromStream(uploadedFile.FileContent)) { if (IsThumbnail) { using (System.Drawing.Image thumbnail = new ImageThumbnailCreator(original).CreateImageThumbnail(new Size(ThumbnailWidth, ThumbnailHeight))) ImageUtils.SaveImage((Bitmap)thumbnail, fullFileName); } else { ImageUtils.SaveImage((Bitmap)original, fullFileName.Insert(fullFileName.IndexOf(".png"), "_original")); System.Drawing.Image resizedPic = PictureHelper.ResizePicture(original, Width, Height); ImageUtils.SaveImage((Bitmap)resizedPic, fullFileName); } } ImageFullFileName = fullFileName; ImageFileName = fileName; ImageFullFileName = ImageFullFileName.Replace(AppDomain.CurrentDomain.BaseDirectory, "/").Replace("\\", "/"); return(ImageFullFileName); }
public void TestForWidthLargerThanHeight() { Image oldImage = (Image)_resourceManager.GetObject("TestJpeg3"); Assert.IsNotNull(oldImage); Assert.AreEqual(5, oldImage.Height); Assert.AreEqual(10, oldImage.Width); ImageThumbnailCreator creator = new ImageThumbnailCreator(); Image newSmallImage = creator.CreateThumbnail(oldImage, 2); Assert.AreEqual(2, newSmallImage.Height); Assert.AreEqual(4, newSmallImage.Width); Image newLargeImage = creator.CreateThumbnail(oldImage, 20); Assert.AreEqual(20, newLargeImage.Height); Assert.AreEqual(40, newLargeImage.Width); }
public void TestThumbnailCreation() { Image oldImage = (Image)_resourceManager.GetObject("TestPhoto"); Assert.IsNotNull(oldImage); Assert.AreEqual(100, oldImage.Height); Assert.AreEqual(100, oldImage.Width); ImageThumbnailCreator creator = new ImageThumbnailCreator(); Image newSmallImage = creator.CreateThumbnail(oldImage, 50); Assert.AreEqual(50, newSmallImage.Height); Assert.AreEqual(50, newSmallImage.Width); Image newLargeImage = creator.CreateThumbnail(oldImage, 200); Assert.AreEqual(200, newLargeImage.Height); Assert.AreEqual(200, newLargeImage.Width); }
/// <summary> /// 真实保存上传文件过程 /// </summary> /// <param name="saveFile"></param> /// <param name="owner"></param> /// <returns></returns> private async Task <IActionResult> SaveUpload(Action <string> saveFile, Account owner) { string fileState = ""; string fileExt = ""; string localPath = ""; string description = ""; Microsoft.Extensions.Primitives.StringValues headerVar; Request.Headers.TryGetValue("fileState", out headerVar); if (headerVar.Count > 0) { fileState = headerVar[0].Trim(); } Request.Headers.TryGetValue("fileExt", out headerVar); if (headerVar.Count > 0) { fileExt = headerVar[0].Trim(); } Request.Headers.TryGetValue("localPath", out headerVar); if (headerVar.Count > 0) { localPath = headerVar[0].Trim(); } Request.Headers.TryGetValue("description", out headerVar); if (headerVar.Count > 0) { description = headerVar[0].Trim(); } //几个头信息decode if (!string.IsNullOrWhiteSpace(fileState)) { fileState = System.Web.HttpUtility.UrlDecode(fileState); } if (!string.IsNullOrWhiteSpace(fileExt)) { fileExt = System.Web.HttpUtility.UrlDecode(fileExt); } if (!string.IsNullOrWhiteSpace(localPath)) { localPath = System.Web.HttpUtility.UrlDecode(localPath); } if (!string.IsNullOrWhiteSpace(description)) { description = System.Web.HttpUtility.UrlDecode(description); } //确保扩展名以 .开头,比如.jpg if (fileExt.Length > 0 && fileExt[0] != '.') { fileExt = "." + fileExt; } FileAsset res = new FileAsset(); res.Id = GuidGen.NewGUID(); //先生成临时ID,用于保存文件 res.Name = localPath.Length > 0 ? Path.GetFileName(localPath) : res.Id; res.Url = "/upload/" + res.Id; int fstate = 0; res.FileState = int.TryParse(fileState, out fstate) ? fstate : 0; res.FileExt = fileExt; res.LocalPath = localPath; res.Description = description; res.Creator = owner.Id; res.Modifier = owner.Id; res.OrganizationId = owner.OrganizationId; //保存 string savePath = Path.Combine(uploadPath, res.Id); try { saveFile(savePath); } catch { res.Id = ""; res.Url = ""; return(Ok(res)); } FileInfo fi = new FileInfo(savePath); res.Size = fi.Length; res.Md5 = Md5.CalcFile(savePath); //计算md5 res.Id = res.Md5; //将ID和url改为md5 res.Url = "/upload/" + res.Id + res.FileExt; string renamedPath = Path.Combine(uploadPath, res.Id + res.FileExt); //图片文件生成缩略图 var createThumbnails = new Action(() => { if (res.FileExt.Equals(".jpg", StringComparison.CurrentCultureIgnoreCase) || res.FileExt.Equals(".png", StringComparison.CurrentCultureIgnoreCase) || res.FileExt.Equals(".jpeg", StringComparison.CurrentCultureIgnoreCase) || res.FileExt.Equals(".gif", StringComparison.CurrentCultureIgnoreCase) || res.FileExt.Equals(".bmp", StringComparison.CurrentCultureIgnoreCase) ) { ImageThumbnailCreator.SaveImageThumbnails(renamedPath); } }); // 检查是否已经上传过此文件 var existRecord = await _Repository._DbContext.Set <FileAsset>().FindAsync(res.Id); if (existRecord != null) { // 数据库记录还在,但是文件不在了,重新保存下文件。 if (System.IO.File.Exists(renamedPath) == false) { //重命名文件 System.IO.File.Move(savePath, renamedPath); createThumbnails(); } else { //删除冗余文件 System.IO.File.Delete(savePath); } return(Ok(existRecord)); } else // 没有上传记录 { //没上传记录,但是已经有这个文件了,先删除已有的文件,使用用户的文件覆盖 if (System.IO.File.Exists(renamedPath)) { System.IO.File.Delete(renamedPath); } System.IO.File.Move(savePath, renamedPath); //重命名文件 createThumbnails(); } await _Repository.CreateAsync(owner.Id, res); //记录到数据库 return(Ok(res)); }
public async Task <IActionResult> AddPost(Post post, List <IFormFile> files, bool sage, bool isWrittenByOp = false) { try { var ipHash = _md5.ComputeHash(HttpContext.Connection.RemoteIpAddress.GetAddressBytes()) .GetString(); var anon = new Anon(ipHash, IpCheck.UserIsBanned(_db, ipHash)); if (anon.IsBanned) { return(RedirectToAction("YouAreBanned", "Ban")); } post.Comment = PostFormatter.GetHtmlTrimmedString(post.Comment); post.AnonIpHash = ipHash; post.TimeInUnixSeconds = DateTimeOffset.Now.ToUnixTimeSeconds(); if (User.Identity.IsAuthenticated) { var admin = _db.Admin.First(a => a.Email == User.Identity.Name); post.AnonName = admin.Login; post.Admin = admin; } if (ModelState.IsValid) { DbAccess.AddPostToThread(_db, post, sage, isWrittenByOp); if (files.Count > 0) { var fileDirectory = Path.Combine(_env.WebRootPath, "postImages"); var thumbNailDirectory = Path.Combine(_env.WebRootPath, "thumbnails"); foreach (var file in files) { if (file.Length > 0) { switch (Path.GetExtension(file.FileName)) { case ".jpeg": case ".jpg": case ".png": { var imageThumbnailCreator = new ImageThumbnailCreator(file, fileDirectory, thumbNailDirectory); imageThumbnailCreator.CreateThumbnail(); DbAccess.AddFilesToPost(_db, post, imageThumbnailCreator.FileInfo); break; } case ".gif": { var gifThumbnailCreator = new GifThumbnailCreator(file, fileDirectory, thumbNailDirectory); gifThumbnailCreator.CreateThumbnail(); DbAccess.AddFilesToPost(_db, post, gifThumbnailCreator.FileInfo); break; } } } else { ModelState.AddModelError("FileLengthNotValid", "Файл пустой."); } } } await LogIntoFile(_logDirectory, string.Concat("Added new post: ", post.PostId, "at thread: ", post.ThreadId), LoggingInformationKind.Info); } else { return(StatusCode(500)); } } catch (InvalidOperationException) { return(NotFound()); } catch (Exception e) { await LogIntoFile(_logDirectory, string.Concat(e.Message, "\n", e.StackTrace), LoggingInformationKind.Error); } return(RedirectToAction("Thread", new { id = post.ThreadId })); }
public async Task <IActionResult> AddThread(Post post, List <IFormFile> files) { try { var ipHash = _md5.ComputeHash(HttpContext.Connection.RemoteIpAddress.GetAddressBytes()) .GetString(); var anon = new Anon(ipHash, IpCheck.UserIsBanned(_db, ipHash)); if (anon.IsBanned) { return(RedirectToAction("YouAreBanned", "Ban")); } if (ModelState.IsValid) { var board = _db.Board.First(b => b.BoardId == post.BoardId); if (_db.Thread.Count(t => t.BoardId == post.BoardId) >= 20) { return(RedirectToAction("Board", new { prefix = board.Prefix })); } post.AnonIpHash = ipHash; if (!string.IsNullOrEmpty(post.AnonName)) { post.AnonName = PostFormatter.GetHtmlTrimmedString(post.AnonName); } post.Comment = PostFormatter.GetHtmlTrimmedString(post.Comment); post.IsWrittenByOp = true; if (User.Identity.IsAuthenticated) { var admin = _db.Admin.First(a => a.Email == User.Identity.Name); post.AnonName = admin.Login; post.Admin = admin; } DbAccess.AddThreadToBoard(_db, ref post); if (files.Count > 0) { var fileDirectory = Path.Combine(_env.WebRootPath, "postImages"); var thumbNailDirectory = Path.Combine(_env.WebRootPath, "thumbnails"); foreach (var file in files) { if (file.Length > 0) { switch (Path.GetExtension(file.FileName)) { case ".jpeg": case ".jpg": case ".png": { var imageThumbnailCreator = new ImageThumbnailCreator(file, fileDirectory, thumbNailDirectory); imageThumbnailCreator.CreateThumbnail(); DbAccess.AddFilesToPost(_db, post, imageThumbnailCreator.FileInfo); break; } case ".gif": { var gifThumbnailCreator = new GifThumbnailCreator(file, fileDirectory, thumbNailDirectory); gifThumbnailCreator.CreateThumbnail(); DbAccess.AddFilesToPost(_db, post, gifThumbnailCreator.FileInfo); break; } } } else { ModelState.AddModelError("FileLengthNotValid", "Файл пустой."); } } } await LogIntoFile(_logDirectory, string.Concat("Added new thread: ", post.ThreadId), LoggingInformationKind.Info); return(RedirectToAction("Thread", "Thread", new { id = post.ThreadId })); } } catch (Exception e) { await LogIntoFile(_logDirectory, string.Concat(e.Message, "\n", e.StackTrace), LoggingInformationKind.Error); Console.WriteLine(e); return(StatusCode(500)); } return(RedirectToAction("Board")); }