예제 #1
0
        public async Task<ActionResult> Edit(ProfileViewModel model, HttpPostedFileBase upload)
        {
            var user = _userManager.FindById(User.Identity.GetUserId());
            if (user == null)
            {
                return RedirectToAction("Start", "Main");
            }

            if (upload != null && upload.ContentLength > 0)
            {
                WebImage img = new WebImage(upload.InputStream);
                if (img.Width > 32)
                    img.Resize(32, 32);
                user.Avatar = img.GetBytes();
            }

            user.FirstName = model.FirstName;
            user.LastName = model.LastName;
            user.UserName = model.Username;
            user.Email = model.Email;

            await _userManager.UpdateAsync(user);

            return RedirectToAction("Details", "Profile");
        }
예제 #2
0
        /// <summary>
        /// Reference this in HTML as <img src="/Photo/WatermarkedImage/{ID}" />
        /// Simplistic example supporting only jpeg images.
        /// </summary>
        /// <param name="ID">Photo ID</param>
        public ActionResult WatermarkedImage(int id)
        {
            // Attempt to fetch the photo record from the database using Entity Framework 4.2.
            var file = FileManagerRepository.GetSingle(id);

            if (file != null) // Found the indicated photo record.
            {
                var dic = new Dictionary <String, String>();
                // Create WebImage from photo data.
                // Should have 'using System.Web.Helpers' but just to make it clear...
                String url       = String.Format("https://docs.google.com/uc?id={0}", file.GoogleImageId);
                byte[] imageData = GeneralHelper.GetImageFromUrlFromCache(url, dic);
                var    wi        = new System.Web.Helpers.WebImage(imageData);

                // Apply the watermark.
                wi.AddTextWatermark("EMIN YUCE");

                // Extract byte array.
                var image = wi.GetBytes("image/jpeg");

                // Return byte array as jpeg.
                return(File(image, "image/jpeg"));
            }
            else // Did not find a record with passed ID.
            {
                return(null); // 'Missing image' icon will display on browser.
            }
        }
예제 #3
0
        public ActionResult Download(int id, bool? thumb)
        {
            var context = HttpContext;
            var mediaItem = Database.MediaItems.SingleOrDefault(m => m.Id == id);
            if (mediaItem == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.NotFound);
            }
            var filePath = Path.Combine(StorageRoot(mediaItem.MediaType), mediaItem.FileName);
            if (!System.IO.File.Exists(filePath))
                return new HttpStatusCodeResult(HttpStatusCode.NotFound);

            const string contentType = "application/octet-stream";

            if (thumb.HasValue && thumb == true)
            {
                var img = new WebImage(filePath);
                if (img.Width > 120)
                    img.Resize(120, 110).Crop(1, 1);
                return new FileContentResult(img.GetBytes(), contentType)
                    {
                        FileDownloadName = mediaItem.FileName
                    };
            }
            else
            {
                return new FilePathResult(filePath, contentType)
                    {
                        FileDownloadName = mediaItem.FileName
                    };
            }
        }
예제 #4
0
        public ActionResult FileUpload(HttpPostedFileBase file)
        {
            if (file != null && file.ContentType.StartsWith("image/"))
            {
                WebImage img = new WebImage(file.InputStream);
                if (img.Width > 178)
                {
                    img.Resize(178, img.Height);
                }

                if (img.Height > 178)
                {
                    img.Resize(img.Width, 178);
                }

                //string path = "C:\\Users\\dzlatkova\\Desktop\\Images";

                //if (!Directory.Exists(path))
                //{
                //    DirectoryInfo di = Directory.CreateDirectory(path);
                //    di.Attributes &= ~FileAttributes.ReadOnly;
                //}

                //string filePath = Path.Combine(path, Path.GetFileName(file.FileName));

                //file.SaveAs(path);

                db.Employers.FirstOrDefault(x => x.UserId == WebSecurity.CurrentUserId).Picture = img.GetBytes();
                db.SaveChanges();
            }
            return RedirectToAction("Profile");
        }
예제 #5
0
        public static void UploadImage(this CloudBlobContainer storageContainer, string blobName, WebImage image)
        {
            var blob = storageContainer.GetBlockBlobReference(blobName);
            blob.Properties.ContentType = "image/" + image.ImageFormat;

            using (var stream = new MemoryStream(image.GetBytes(), writable: false))
            {
                blob.UploadFromStream(stream);
            }
        }
        public JsonResult RotateImage(string url)
        {
            var image = new WebImage(_userImagesService.GetImageStream(url));
            image.FileName = "rotated." + image.ImageFormat;
            image.RotateLeft();

            return
                Json(
                    _userImagesService.SaveUserImageStream(
                        new MemoryStream(image.GetBytes()),
                        image.FileName,
                        image.ImageFormat, image.Height, image.Width),
                    "text/plain");
        }
        // GET: Photos
        public ActionResult GetSize(int id)
        {
            Staff staff = db.StaffList.Find(id);
            if (staff.Photo != null)
            {
                var img = new WebImage(staff.Photo);
                img.Resize(100, 100, true, true);
                var imgBytes = img.GetBytes();

                return File(imgBytes, "image/" + img.ImageFormat);
            }
            else
            {
                return null;
            }
        }
예제 #8
0
        public ActionResult GetUserThumbnailImage(int userId, Guid userGuid)
        {
            try
            {
                UserDTO user = _managerService.UserDetails(userId, userGuid);
                var img = new WebImage(user.AvatarImage);
                img.Resize(32, 32, true, true);

                return File(img.GetBytes("png"), "image/png");
            }
            catch (Exception ex)
            {
                Logger.LogError("GetUserImage: Exception while retrieving user avatar image data", ex);
                return null;
            }
        }
        public ActionResult Show(Guid speakerId, int width, int height, string mode = "")
        {
            SpeakerPicture speakerPicture = service.TryGetPicture(speakerId);
            if (speakerPicture == null)
                return new HttpNotFoundResult();

            var image = new WebImage(speakerPicture.Picture);
            if (width > 0 && height > 0)
            {
                if (mode == "crop")
                    image = CropImage(image, width, height);
                else
                    image = image.Resize(width, height);
            }

            return File(image.GetBytes(), image.ImageFormat);
        }
예제 #10
0
 public static byte[] AddWaterMark(string filePath, string text)
 {
     using (var img = System.Drawing.Image.FromFile(filePath))
     {
         using (var memStream = new MemoryStream())
         {
             using (var bitmap = new Bitmap(img)) // to avoid GDI+ errors
             {
                 bitmap.Save(memStream, ImageFormat.Png);
                 var content = memStream.ToArray();
                 var webImage = new WebImage(memStream);
                 webImage.AddTextWatermark(text, verticalAlign: "Top", horizontalAlign: "Left", fontColor: "Brown");
                 return webImage.GetBytes();
             }
         }
     }
 }
        public JsonResult CropImage(string coords, string url)
        {
            var coordinates = new JavaScriptSerializer().Deserialize<Dictionary<string, int>>(coords);
            var image = new WebImage(_userImagesService.GetImageStream(url));
            image.FileName = "cropped." + image.ImageFormat;
            image.Crop(
                coordinates["y1"],
                coordinates["x1"],
                image.Height - coordinates["y2"],
                image.Width - coordinates["x2"]);

            return
                Json(
                    _userImagesService.SaveUserImageStream(
                        new MemoryStream(image.GetBytes()),
                        image.FileName,
                        image.ImageFormat, image.Height, image.Width),
                    "text/plain");
        }
예제 #12
0
        public ActionResult ShowGuidWithWatermark(string guid, string path, string width, string height)
        {
            int intWidth = 0;
            int intHeight = 0;

            if (!int.TryParse(width, out intWidth))
            {
                return null;
            }

            if (!int.TryParse(height, out intHeight))
            {
                return null;
            }

            if (string.IsNullOrWhiteSpace(guid) || string.IsNullOrWhiteSpace(path))
            {
                return null;
            }

            string photoName = "";
            string coordinate = "";

            var dc = new DbWithBasicFunction();
            var db = dc.db;

            if (path.ToLower() == "gallery")
            {
                var galleryItem = db.tbl_gallery.Where(a => a.guid == guid).FirstOrDefault();

                if (galleryItem == null)
                {
                    return null;
                }

                photoName = galleryItem.photo;
                coordinate = galleryItem.photoCoordinate;

            }

            var item = getFileCoordinated(photoName, coordinate, path);

            if (item != null)
            {
                var settings = new ResizeSettings();

                int widthInt = int.Parse(width);
                int heightInt = int.Parse(height);

                settings.Width = widthInt;
                settings.Height = heightInt;
                settings.Mode = FitMode.Stretch;

                WebImage waterMarkImage;

                using (MemoryStream st = new MemoryStream())
                {

                    ImageBuilder.Current.Build(item.First().Key, st, settings);
                    st.Position = 0;

                    waterMarkImage = new WebImage(st);

                }

                waterMarkImage.AddTextWatermark("www.titizkromaksesuar.com", fontColor: "#ffe27b", fontSize: 10, verticalAlign: "Middle", opacity: 60);

                return File(waterMarkImage.GetBytes(), item.First().Value);

            }
            else
            {
                return null;
            }
        }
        private Byte[] WaterMark(Stream s,string color)
        {
            MemoryStream str = new MemoryStream();
            System.Web.Helpers.WebImage webimg = new System.Web.Helpers.WebImage(s);
            String wm = WebSecurity.CurrentUserName;
            webimg.AddTextWatermark(wm, color, 16, "Regular", "Microsoft Sans Serif", "Right", "Bottom", 50, 10);

            return webimg.GetBytes();
        }
예제 #14
0
 public virtual UserPictureModel GetDefaultPicture(int size)
 {
     var image = new WebImage(HostingEnvironment.MapPath(Constants.DefaultProfilePicturePath));
       image.Resize(size + 1, size + 1).Crop(1, 1);
       return new UserPictureModel { Data = image.GetBytes(), ContentType = image.ImageFormat };
 }
        public ActionResult EditNews(AddAchievement a)
        {
            var achievement = db.Achivements.Find(a.AchievementItem.AchievementID);

            if (a.ImageFile != null)
            {
                var image = new WebImage(a.ImageFile.InputStream);
                image.Resize(200, 133);

                achievement.PhotoType = a.ImageFile.ContentType;
                achievement.PhotoFile = image.GetBytes();
            }

            achievement.Title = a.AchievementItem.Title;
            achievement.Description = a.AchievementItem.Description;

            TryUpdateModel<Achievement>(achievement);
            db.Entry<Achievement>(achievement).State = System.Data.EntityState.Modified;
            db.SaveChanges();

            return RedirectToAction("SystemNewsCreation");
        }
        public JsonResult UploadFile(HttpPostedFileBase file, PageRegistration pageRegistration)
        {
            if (file.ContentLength > 4194304)
            {
                return Json(new { Error = "Cannot upload files bigger than 4MB in size. Please select a smaller image" });
            }

            var formats = new[] { ".jpg", ".png", ".gif", ".jpeg", ".bmp" };
            if (!file.ContentType.Contains("image") || !formats.Any(item => file.FileName.EndsWith(item, StringComparison.OrdinalIgnoreCase)))
            {
                return Json(new { Error = "Only image files of type JPEG, GIF, PNG or BMP can be uploaded" });
            }

            var image = new WebImage(file.InputStream) { FileName = file.FileName };
            return
               Json(
                   _userImagesService.SaveUserImageStream(
                       new MemoryStream(image.GetBytes()),
                       image.FileName,
                       image.ImageFormat, image.Height, image.Width),
                   "text/plain");
        }
        private ActionResult GetFileInternal(string type, string url, int width = 0, int height = 0)
        {
            url = url.Replace("&#47;", "/");

            if (!this._fileService.CheckAccessFile(url))
            {
                this.Response.StatusCode = 401;
                return new HttpUnauthorizedResult();
            }

            string path = null;

            if (width > 0 && height > 0)
            {
                path = this._imageConverter.GetThumbPath(url, width, height);
                var pathParts = path.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
                url = pathParts.Last();
                path = string.Format("/{0}/", Web.Helpers.GetVirtualPath(string.Join("\\", pathParts.Take(pathParts.Length - 1))));
            }
            else
            {
                path = this.Request.Url.Segments.Contains(string.Format("{0}/", CmsConstants.SECURE)) ? string.Format("~/Content/{0}/{1}/", type, CmsConstants.SECURE) : string.Format("~/Content/{0}/", type);
            }

            // Todo: logic te determine which images should be watermarked. Use an event?
            if (false)
            {
                var webImage = new WebImage(path);
                string waterMarkPath = string.Format("{0}{1}", Server.MapPath("~"), StrixCms.Config.Files.WaterMarkPath.Replace('/', '\\'));
                webImage.AddImageWatermark(waterMarkPath);
                return this.File(webImage.GetBytes(), MimeMapping.GetMimeMapping(url));
            }

            return this.File(this.Server.MapPath(path) + url, MimeMapping.GetMimeMapping(url));
        }
        public ActionResult CreateNews(AddAchievement achievement, int ecologicalProblemID)
        {
            ViewBag.problemID = ecologicalProblemID;            
            int currentAdminId;

            if (int.TryParse(Session["SystemUserId"].ToString(), out currentAdminId))
            {
                try
                {
                    achievement.AchievementItem.Administrator = db.Administrators.Find(currentAdminId);
                    achievement.AchievementItem.EcologicalProblem = db.EcologicalProblems.Find(ecologicalProblemID);

                    if (achievement.ImageFile != null)
                    {
                        var image = new WebImage(achievement.ImageFile.InputStream);
                        image.Resize(200, 133);

                        achievement.AchievementItem.PhotoType = achievement.ImageFile.ContentType;
                        achievement.AchievementItem.PhotoFile = image.GetBytes();
                    }

                    db.Achivements.Add(achievement.AchievementItem);
                    db.SaveChanges();

                    return RedirectToAction("SystemNewsCreation");
                }
                catch { }
            }

            return View();
        }
예제 #19
0
		public ActionResult PicturePageForVideoID (String TableName, String TableID, String ThumbOrFull)
			{
			StandbildInformationModel StBModel = new StandbildInformationModel (String.Empty, String.Empty);
			bool ThumbOrFullBool = (ThumbOrFull == "True");
			WebImage CreatedWebImage = new WebImage (StBModel.CreatePictureData (TableName, TableID, ThumbOrFullBool));
			return new FileContentResult (CreatedWebImage.GetBytes ("image/jpeg"), "image/jpeg");
			}
예제 #20
0
        public bool SaveImage(CloudBlobContainer container, string userId, UserImageTypes userImageType, string sourceHash, string suffix, WebImage image, ImageFormat format, string sourceFormat, out Uri uri)
        {
            uri = null;
            try
            {
                CloudBlockBlob blockBlob = container.GetBlockBlobReference(string.Format("{0}-{1}-{2}-{3}.{4}", userId.Replace('/', '-'), (int)userImageType, sourceHash, suffix, sourceFormat));
                var bytes = image.GetBytes();
                blockBlob.UploadFromByteArray(bytes, 0, bytes.Length);
                uri = blockBlob.Uri;
            }
            catch (Exception exception)
            {
                _logger.Error(exception, "Error when save on Azure");
                return false;
            }

            return true;
        }
예제 #21
0
        public ActionResult PicturePageForFile(String PictureFileName, String ThumbOrFull)
            {
	        lock (Data.DbServer3)
		        {
		        BeitragInformationModel StBModel = new BeitragInformationModel(String.Empty, String.Empty);
		        bool ThumbOrFullBool = (ThumbOrFull == "True");
		        WebImage CreatedWebImage = new WebImage(StBModel.CreatePictureData(PictureFileName, ThumbOrFullBool));
		        return new FileContentResult(CreatedWebImage.GetBytes("image/jpeg"), "image/jpeg");
		        }
            }
예제 #22
0
		public ActionResult PicturePageForID(String TableName, String MMPartID, String PageNumber, String ThumbOrFull)
			{
	        lock (Data.DbServer3)
		        {
		        BeitragInformationModel StBModel = new BeitragInformationModel(String.Empty, String.Empty);
		        bool ThumbOrFullBool = (ThumbOrFull == "True");
		        MMPart partToShow = Data.DbServer3.MultiMedia.MMParts.FindOrLoad(Guid.Parse(MMPartID));
		        if (partToShow == null)
			        return null;
				WebImage CreatedWebImage =
			        new WebImage(partToShow.FullBitmapSource.ConvertTo_JpgByteArray());
		        return new FileContentResult(CreatedWebImage.GetBytes("image/jpeg"), "image/jpeg");
		        }
			}
        public ActionResult leggNyttProdukt(DBModel.Product prod,HttpPostedFileBase productBilde)
        {
            if (ModelState.IsValid)
            {
                if (productBilde != null && productBilde.ContentLength > 0)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        productBilde.InputStream.CopyTo(ms);
                        prod.Picture = ms.GetBuffer();
                        WebImage t = new WebImage(prod.Picture);
                        t.Resize(150, 113, true, false);
                        prod.Picture = t.GetBytes();

                    }
                    if (_produktBLL.leggTilNyttProdukt(prod))
                        return View();
                }
            }

            return View(prod);
        }
예제 #24
0
        private string EncodeFile(string fileName)
        {
            WebImage img = new WebImage(fileName);
            if (img.Width > 80)
                img.Resize(80, 60).Crop(1, 1);

            return Convert.ToBase64String(img.GetBytes());
        }
예제 #25
0
        public static void ResizeImage(ref WebImage webImage, int maxWidth, int maxHeight)
        {
            var transparencyFormats = new Dictionary<string, ImageFormat>(StringComparer.OrdinalIgnoreCase)
            {
                {"png", ImageFormat.Png},
                {"gif", ImageFormat.Gif}
            };

            ImageFormat format;

            float originalWidth = webImage.Width;
            float originalHight = webImage.Height;
            var hw = originalHight/originalWidth;
            var wh = originalWidth/originalHight;
            if (webImage.Width > webImage.Height)
            {
                originalWidth = maxWidth;
                originalHight = originalWidth*hw;

                if (originalHight > maxHeight)
                {
                    originalHight = maxHeight;
                    originalWidth = originalHight*wh;
                }
            }
            else
            {
                originalHight = maxHeight;
                originalWidth = originalHight*wh;
                if (webImage.Width > webImage.Height)
                {
                    originalWidth = maxWidth;
                    originalHight = originalWidth*hw;
                }
            }

            if (transparencyFormats.TryGetValue(webImage.ImageFormat.ToLower(), out format))
            {
                using (var resizedImage = new Bitmap((int) originalWidth, (int) originalHight))
                {
                    using (var source = new Bitmap(new MemoryStream(webImage.GetBytes())))
                    {
                        using (var g = Graphics.FromImage(resizedImage))
                        {
                            g.SmoothingMode = SmoothingMode.AntiAlias;
                            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            g.DrawImage(source, 0, 0, (int) originalWidth, (int) originalHight);
                        }
                    }

                    using (var ms = new MemoryStream())
                    {
                        resizedImage.Save(ms, format);
                        webImage = new WebImage(ms.ToArray());
                    }
                }
            }
            else
            {
                webImage.Resize((int) originalWidth, (int) originalHight, false, true);
            }
        }
        public ActionResult endreProdukt(DBModel.Product item, HttpPostedFileBase productBilde)
        {
            if (ModelState.IsValid)
            {
                if (Request.IsAuthenticated)
                {
                    if (_adminBLL.erAnsatt(User.Identity.Name))
                    {
                        if (productBilde != null && productBilde.ContentLength > 0)
                        {
                            using (MemoryStream ms = new MemoryStream())
                            {
                                productBilde.InputStream.CopyTo(ms);
                                item.Picture = ms.GetBuffer();
                                WebImage t = new WebImage(item.Picture);
                                t.Resize(150, 113, true, false);
                                item.Picture = t.GetBytes();

                            }
                        }

                        if (_produktBLL.endreProdukt(item))
                            return RedirectToAction("Produkt", "Admin");

                        return View(item);
                    }
                    return View(item);
                }
            }
            return View(item);
        }
예제 #27
0
        public async Task<string> GetPhotoString(string filePath)
        {
            var rootFilePath = ConfigurationManager.AppSettings["RootFilePath"];

            var fileFullPath = Path.Combine(rootFilePath, filePath);

            var img = new WebImage(File.ReadAllBytes(fileFullPath));
            if (img.Width > 300)
                img.Resize(300, 300);
            return await Task.Run(() => "data:image/png;base64," + Convert.ToBase64String(img.GetBytes()));
            //return await Task.Run(() => "data:image/png;base64," + Convert.ToBase64String(File.ReadAllBytes(fileFullPath)));
        }
예제 #28
0
        private void UploadWholeFile(int assetCategoryId, HttpRequestBase request, ICollection<ViewDataUploadFilesResult> statuses)
        {
            var currentOrganizationId = AppService.GetCurrentOrganizationId();
            var assetCategory = AssetCategoryService.FindById(assetCategoryId, currentOrganizationId);

            for (var i = 0; i < request.Files.Count; i++)
            {
                var file = request.Files[i];

                var webImage = new WebImage(file.InputStream);

                //var data = new byte[file.ContentLength];
                //file.InputStream.Read(data, 0, file.ContentLength);

                var data = webImage.GetBytes();
                var asset = Asset.Create(assetCategory, file.FileName, data.Length, data, file.ContentType);

                AssetService.Save(asset);

                statuses.Add(new ViewDataUploadFilesResult
                {
                    name = file.FileName,
                    size = file.ContentLength,
                    type = file.ContentType,
                    url = "/admin/media/download/" + file.FileName,
                    delete_url = "/admin/media/delete/" + file.FileName,
                    thumbnail_url = @"data:image/png;base64," + Convert.ToBase64String(asset.Data),
                    delete_type = "GET",
                });
            }
        }
예제 #29
0
        /// <summary>
        /// Posts this instance.
        /// </summary>
        /// <returns></returns>
        public Task<IEnumerable<Asset>> Post()
        {
            if (!Request.Content.IsMimeMultipartContent()) {

                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));

            }

            var task = Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider()).ContinueWith(t =>
                {

                    var session = StructureMap.ObjectFactory.GetInstance<IDocumentSession>();

                    var virtualPathProvider = HostingEnvironment.VirtualPathProvider as CommonVirtualPathProvider;

                    if (t.IsFaulted || t.IsCanceled || virtualPathProvider == null) {
                        throw new HttpResponseException(HttpStatusCode.InternalServerError);
                    }

                    var asset = t.Result.Contents.Select(httpContent =>
                    {
                        // Read the stream
                        var stream = httpContent.ReadAsStreamAsync().Result;
                        var length = stream.Length;

                        // Get root directory of the current virtual path provider
                        var virtualDirectory = virtualPathProvider.GetDirectory(virtualPathProvider.VirtualPathRoot) as CommonVirtualDirectory;

                        if (virtualDirectory == null) {
                            throw new HttpResponseException(HttpStatusCode.InternalServerError);
                        }

                        // Set the name and if not present add some bogus name
                        var name = !string.IsNullOrWhiteSpace(httpContent.Headers.ContentDisposition.FileName)
                                           ? httpContent.Headers.ContentDisposition.FileName
                                           : "NoName";

                        // Clean up the name
                        name = name.Replace("\"", string.Empty);

                        // Create a new name for the file stored in the vpp
                        var uniqueFileName = Guid.NewGuid().ToString("n");

                        // Create the file in current directory
                        var virtualFile = virtualDirectory.CreateFile(string.Format("{0}{1}",uniqueFileName, VirtualPathUtility.GetExtension(name)));

                        // Write the file to the current storage
                        using (var s = virtualFile.Open(FileMode.Create)) {
                            var bytesInStream = new byte[stream.Length];
                            stream.Read(bytesInStream, 0, bytesInStream.Length);
                            s.Write(bytesInStream, 0, bytesInStream.Length);
                        }

                        Asset file;
                        if (httpContent.Headers.ContentType.MediaType.Contains("image")) {
                            file = new Image();
                            using (var image = System.Drawing.Image.FromStream(stream, false, false)) {
                                ((Image)file).Width = image.Width;
                                ((Image)file).Height = image.Height;
                            }
                            var mediumThumbnail = new WebImage(stream).Resize(111, 101).Crop(1, 1);
                            file.Thumbnail = mediumThumbnail.GetBytes();
                        }
                        else if (httpContent.Headers.ContentType.MediaType.Contains("video")) {
                            var icon = new WebImage(HttpContext.Current.Server.MapPath("~/areas/ui/content/images/document.png"));
                            file = new Video { Thumbnail = icon.GetBytes() };
                        }
                        else if (httpContent.Headers.ContentType.MediaType.Contains("audio")) {
                            var icon = new WebImage(HttpContext.Current.Server.MapPath("~/areas/ui/content/images/document.png"));
                            file = new Video { Thumbnail = icon.GetBytes() };
                        } else {
                            var icon = new WebImage(HttpContext.Current.Server.MapPath("~/areas/ui/content/images/document.png"));
                            file = new Video { Thumbnail = icon.GetBytes() };
                        }

                        file.Name = name;
                        file.ContentType = httpContent.Headers.ContentType.MediaType;
                        file.ContentLength = length;
                        file.DateUploaded = DateTime.Now;
                        file.VirtualPath = virtualFile.VirtualPath;
                        file.Url = virtualFile.Url;

                        session.Store(file);
                        session.SaveChanges();

                        return file;
                    });

                    return asset;
                });

            return task;
        }
예제 #30
0
        /// <summary>
        /// Created image thmbnail in PNG format: resizes the image and crops to fit.
        /// </summary>
        /// <param name="sourceStream">The source stream.</param>
        /// <param name="destinationStream">The destination stream.</param>
        /// <param name="size">The size.</param>
        private void CreatePngThumbnail(Stream sourceStream, Stream destinationStream, Size size)
        {
            using (var tempStream = new MemoryStream())
            {
                sourceStream.Seek(0, SeekOrigin.Begin);
                sourceStream.CopyTo(tempStream);               

                var image = new WebImage(tempStream);
               
                using (Image resizedBitmap = new Bitmap(size.Width, size.Height))
                {
                    using (Bitmap source = new Bitmap(new MemoryStream(image.GetBytes())))
                    {
                        using (Graphics g = Graphics.FromImage(resizedBitmap))
                        {
                            var destination = source;

                            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                            var diff = (image.Width - image.Height) / 2.0;
                            if (diff > 0)
                            {
                                var x1 = Convert.ToInt32(Math.Floor(diff));
                                var y1 = 0;
                                var x2 = image.Height;
                                var y2 = image.Height;
                                var rect = new Rectangle(x1, y1, x2, y2);
                                destination = CropImage(destination, rect);
                            }
                            else if (diff < 0)
                            {
                                diff = Math.Abs(diff);

                                var x1 = 0;
                                var y1 = Convert.ToInt32(Math.Floor(diff));
                                var x2 = image.Width;
                                var y2 = image.Width;
                                var rect = new Rectangle(x1, y1, x2, y2);
                                destination = CropImage(destination, rect);
                            }

                            g.DrawImage(destination, 0, 0, size.Width, size.Height);
                        }
                    }
                    using (MemoryStream ms = new MemoryStream())
                    {
                        resizedBitmap.Save(ms, ImageFormat.Png);

                        var resizedImage = new WebImage(ms);
                        var bytes = resizedImage.GetBytes();
                        destinationStream.Write(bytes, 0, bytes.Length);      
                    }
                }
            }
        }
예제 #31
-1
        public static void Save(Stream inputStream, string fileName, out string imagePath, out string thumpPath, out byte[] binary, out string mimeType)
        {
            ImageSetting setting = GetSetting();

            var fullPath = HttpContext.Current.Server.MapPath("/");

            CreateFolder(setting);

            if (inputStream == null) throw new ArgumentNullException("inputStream");
            var image = new WebImage(inputStream);

            binary = image.GetBytes();
            mimeType = fileName.GetMimeType();

            image.FileName = fileName;

            if (image.Width > 500)
            {
                image.Resize(500, ((500 * image.Height) / image.Width));
            }

            var fn = Guid.NewGuid() + "-" + CommonHelper.RemoveMarks(Path.GetFileName(fileName));

            thumpPath = imagePath = fn;

            image.Save(fullPath + setting.ImagePath + fn);

            image.Resize(132, 102);
            image.Save(fullPath + setting.ThumpPath + "/1__" + fn);

            image.Resize(53, 53);
            image.Save(fullPath + setting.ThumpPath + "/2__" + fn);
        }