public FileStorage(ISettings settings)
        {
            _settings = settings;
            
            _resizeSettings = new ResizeSettings {
                    MaxWidth = settings.ThumbnailSize,
                    MaxHeight = settings.ThumbnailSize, 
                    Format = "jpg"
                };
            _resizeSettings.Add("quality", ImageQuality);

            //create FullsizedImagesFolder & SmallImagesFolder subfolders
            string largeFilesFolder = Path.Combine(settings.ImagesLocalFolder, FullsizedImagesFolder);
            string smallFilesFolder = Path.Combine(settings.ImagesLocalFolder, SmallImagesFolder);

            if (!Directory.Exists(largeFilesFolder))
                Directory.CreateDirectory(largeFilesFolder);
            if (!Directory.Exists(smallFilesFolder))
                Directory.CreateDirectory(smallFilesFolder);
            
            _lastPhoto = Directory
                .GetFiles(largeFilesFolder, "*.jpg")
                .Select(i => int.Parse(Path.GetFileNameWithoutExtension(i).ToLower().Replace(".jpg", "")))
                .OrderByDescending(i => i)
                .FirstOrDefault();

            if (_lastPhoto < 1)
                _lastPhoto = 1;
        }
Example #2
0
 public ImageRequestAction(string virtualPath, NameValueCollection query, IPipelineConfig conf = null)
 {
     this.conf = (conf == null) ? Config.Current.Pipeline : conf;
     ReauthorizeFinalPath = true;
     Source = virtualPath;
     Settings = new ResizeSettings(query);
 }
Example #3
0
        public Image SaveImage(HttpServerUtilityBase server, HttpPostedFileBase file)
        {
            string largeUploadFolder = server.MapPath("~/assets/images/large");
            string mediumUploadFolder = server.MapPath("~/assets/images/medium");
            string thumbUploadFolder = server.MapPath("~/assets/images/thumb");
            if (!Directory.Exists(largeUploadFolder)) Directory.CreateDirectory(largeUploadFolder);
            if (!Directory.Exists(mediumUploadFolder)) Directory.CreateDirectory(mediumUploadFolder);
            if (!Directory.Exists(thumbUploadFolder)) Directory.CreateDirectory(thumbUploadFolder);

            //The resizing settings can specify any of 30 commands.. See http://imageresizing.net for details.
            ResizeSettings largeSettings = new ResizeSettings("maxwidth=800&maxheight=800");
            ResizeSettings mediumSettings = new ResizeSettings("maxwidth=300&maxheight=300&scale=both");
            ResizeSettings thumbSettings = new ResizeSettings("width=100&height=100&crop=auto");

            //var uniqueName = System.Guid.NewGuid().ToString();
            string uniqueName = PathUtils.RemoveExtension(file.FileName) + "_" + DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss");
            string largeFilePath = Path.Combine(largeUploadFolder, uniqueName);
            string mediumFilePath = Path.Combine(mediumUploadFolder, uniqueName);
            string thumbFilePath = Path.Combine(thumbUploadFolder, uniqueName);

            //Let the image builder add the correct extension based on the output file type (which may differ).
            var large = ImageBuilder.Current.Build(file, largeFilePath, largeSettings, false, true);
            var med = ImageBuilder.Current.Build(file, mediumFilePath, mediumSettings, false, true);
            var thumb = ImageBuilder.Current.Build(file, thumbFilePath, thumbSettings, false, true);

            Image img = new Image(PathUtils.RemoveExtension(file.FileName), ResolveRelativePath(server, large), ResolveRelativePath(server, med), ResolveRelativePath(server, thumb));
            Repo.Save(img);
            return img;
        }
Example #4
0
 public IEncoder CreateIfSuitable(ResizeSettings settings, object original)
 {
     if ("webp".Equals(settings.Format, StringComparison.OrdinalIgnoreCase)) {
         return new WebPEncoderPlugin(settings);
     }
     return null;
 }
Example #5
0
		public ActionResult Edit(EditModel model)
		{
			if (!ModelState.IsValid)
			{
				return View(model);
			}

			// Get the About entity if it exists, so ImageUrl doesn't get overriden to null if no image is selected and user is saving in json instead of sql.
			var about = Services.About.Exists(model.Title) ? Services.About.GetByTitle(model.Title) : new About();
			about.Name = model.Name;
			about.Title = model.Title;
			about.Content = model.Content;
			// Save the image in blob storage
			if (model.Image != null)
			{
				var image = new NBlog.Web.Application.Service.Entity.Image();
				var fileName = Path.GetFileName(model.Image.FileName);
				// Scale the image before saving
				using (var scaledImageStream = new MemoryStream())
				{
					var settings = new ResizeSettings(200, 150, FitMode.None, "jpg");
					ImageBuilder.Current.Build(model.Image.InputStream, scaledImageStream, settings);
					image.StreamToUpload = scaledImageStream;
					// Set FileName to save as, gets read as a repository key
					image.FileName = fileName;
					Services.Image.Save(image);
				}
				// Get the url to link to the About Entity
				about.ImageUrl = Services.Image.GetByFileName(fileName).Uri;
			}
			Services.About.Save(about);

			return RedirectToAction("Index", "About");
		}
Example #6
0
        public HttpResponseMessage Get(Guid imageId, int width, int height)
        {
            using (var context = new ApplicationDbContext())
            {
                var image = context.Images
                    .Single(i => i.Id == imageId);

                var settings = new ResizeSettings
                {
                    Format = "jpg",
                    Mode = FitMode.Stretch,
                    Width = width,
                    Height = height,
                    Scale = ScaleMode.Both
                };

                var stream = new MemoryStream();
                ImageBuilder.Current.Build(image.Data, stream, settings);
                stream.Position = 0;

                var result = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StreamContent(stream)
                };
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                return result;
            }

        }
Example #7
0
        public FileContentResult Index(string filename, int w = 0, int h = 0)
        {
            try
            {
                string contentType = "";
                var filePath = new FileInfo(Server.MapPath("~/App_Data/") + filename);

                var index = filename.LastIndexOf(".") + 1;
                var extension = filename.Substring(index).ToUpperInvariant();

                // Fix for IE not handling jpg image types
                contentType = string.Compare(extension, "JPG") == 0 ? "image/jpeg" : string.Format("image/{0}", extension);

                Bitmap bmImage = null;
                if (w > 0 && h > 0)
                {
                    //&format={3}
                    string querySetting = String.Format("width={0};height={1};crop={2}", w, h, "auto");
                    var resizeSetting = new ResizeSettings(querySetting);
                    bmImage = ImageBuilder.Current.Build(filePath.FullName, resizeSetting);
                }
                else
                {
                    bmImage = ImageBuilder.Current.LoadImage(filePath.FullName, new ResizeSettings());
                }
                byte[] byteArray = ImageHelpers.BitmapToBytes(bmImage);
                return File(byteArray, contentType);
            }
            catch
            {
                throw new FileNotFoundException();

            }
        }
Example #8
0
        public FreeImageEncoderPlugin(ResizeSettings settings, object original)
        {
            ImageFormat originalFormat = DefaultEncoder.GetOriginalFormat(original);
            if (!IsValidOutputFormat(originalFormat)) originalFormat = ImageFormat.Jpeg;//No valid info available about the original format. Use Jpeg.

            //What format was specified?
            ImageFormat requestedFormat = DefaultEncoder.GetRequestedFormat(settings.Format, originalFormat); //fallback to originalFormat if not specified.
            if (!IsValidOutputFormat(requestedFormat))
                throw new ArgumentException("An unrecognized or unsupported output format (" + (settings.Format != null ? settings.Format : "(null)") + ") was specified in 'settings'.");
            this.format =  FreeImage.GetFormat(requestedFormat);

            //Parse JPEG settings.
            int quality = 90;
            if (string.IsNullOrEmpty(settings["quality"]) || !int.TryParse(settings["quality"], NumberStyles.Number, NumberFormatInfo.InvariantInfo, out quality)) quality = 90;
            if (format == FREE_IMAGE_FORMAT.FIF_JPEG) {
                if (quality >= 100) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYSUPERB;
                else if (quality >= 75)
                    encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD;
                else if (quality >= 50) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYNORMAL;
                else if (quality >= 25) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYAVERAGE;
                else encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYBAD;

                if ("true".Equals(settings["progressive"])) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_PROGRESSIVE;

                if ("411".Equals(settings["subsampling"])) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_411;
                if ("420".Equals(settings["subsampling"])) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_420;
                if ("422".Equals(settings["subsampling"])) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_422;
                if ("444".Equals(settings["subsampling"])) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_444;
            }
            if (string.IsNullOrEmpty(settings["colors"]) || !int.TryParse(settings["colors"], NumberStyles.Number, NumberFormatInfo.InvariantInfo, out colors)) colors = -1;

            if (format == FREE_IMAGE_FORMAT.FIF_GIF) {
                //encodingOptions = FREE_IMAGE_SAVE_FLAGS.
            }
        }
Example #9
0
        public void UploadFiles(string settingsForImages)
        {
            if (!IsPostBack) return;

            Guid lastUpload = Guid.Empty;
            //Loop through each uploaded file
            foreach (string fileKey in HttpContext.Current.Request.Files.Keys) {
                HttpPostedFile file = HttpContext.Current.Request.Files[fileKey];
                if (file.ContentLength <= 0) continue; //Yes, 0-length files happen.

                if (Config.Current.Pipeline.IsAcceptedImageType(file.FileName) && settingsForImages != null) {
                    //The resizing settings can specify any of 30 commands.. See http://imageresizing.net for details.
                    ResizeSettings resizeCropSettings = new ResizeSettings(settingsForImages);

                    using (MemoryStream ms = new MemoryStream()) {
                        //Resize the image
                        ImageBuilder.Current.Build(file, ms, resizeCropSettings);
                        //Upload the byte array to SQL
                        lastUpload = StoreFile(ms.ToArray(), ImageBuilder.Current.EncoderProvider.GetEncoder(resizeCropSettings, file.FileName).Extension, file.FileName);
                    }
                } else {
                    //It's not an image - upload as-is.
                    lastUpload = StoreFile(StreamExtensions.CopyToBytes(file.InputStream), PathUtils.GetExtension(file.FileName).TrimStart('.'), file.FileName);

                }
            }

            if (lastUpload != Guid.Empty) Response.Redirect(ResolveUrl("~/"));
        }
Example #10
0
        //
        // GET: /Image/

        public FileResult Generate(string source, int width, int height)
        {
            string url = Uri.UnescapeDataString(source);
            HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse();
            Stream stream = httpWebReponse.GetResponseStream();

            var quality = 80;
            byte[] resized;
            using (var outStream = new MemoryStream())
            {
                var settings = new ResizeSettings
                {
                    Mode = FitMode.Crop,
                    Width = width,
                    Height = height,
                    Format = "jpg"
                };
                settings.Add("quality", quality.ToString());
                ImageBuilder.Current.Build(stream, outStream, settings);
                resized = outStream.ToArray();
            }

            stream.Dispose();

            return new FileStreamResult(new MemoryStream(resized, 0, resized.Length), "image/jpeg");
        }
Example #11
0
        public PrettyGifs(ResizeSettings settings, object original)
        {
            this.query = new ResizeSettings(settings);
            ResizeSettings q = settings;
            //Parse output format
            OutputFormat = GetFormatIfSuitable(settings, original);
            //Parse colors
            int colors = -1;
            if (!string.IsNullOrEmpty(q["colors"]))
                if (int.TryParse(q["colors"], NumberStyles.Integer,NumberFormatInfo.InvariantInfo, out colors))
                    this.Colors = colors;
            //Parse dither settings
            if (!string.IsNullOrEmpty(q["dither"])) {
                if ("true".Equals(q["dither"], StringComparison.OrdinalIgnoreCase))
                    this.Dither = true;
                else if ("4pass".Equals(q["dither"], StringComparison.OrdinalIgnoreCase))
                    this.FourPassDither = true;
                else {
                    int dither;
                    if (int.TryParse(q["dither"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out dither)) {
                        DitherPercent = dither;
                        Dither = true;
                    }
                }

            }

            PreservePalette = q.Get<bool>("preservePalette", PreservePalette);
            if (PreservePalette && original is Image && ((Image)original).Palette.Entries.Length > 0) {
                originalPalette = ((Image)original).Palette;
            }
        }
Example #12
0
        public static string SaveFile(HttpPostedFileBase hpf, Photo_types type)
        {
            string filename = "",
                   ext = "",
                   savedFileName = "";

            if (hpf.ContentLength == 0)
                return "";

            var settings = new ResizeSettings
            {
                MaxWidth = 450,
                MaxHeight = 350,
                Format = "jpg"
            };

            DateTime now = DateTime.Now;
            ext = Path.GetExtension(hpf.FileName);
            filename = type.ToString() + "-" + now.Millisecond + now.Second + now.Hour + now.Minute + now.Day + now.Year + ext;

            savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + CMS_TEMP_PATH, filename);

            ImageBuilder.Current.Build(hpf.InputStream, savedFileName, settings);
            //hpf.SaveAs(savedFileName);

            return filename;
        }
Example #13
0
 public ImageLayer(NameValueCollection attrs, Config c)
     : base(attrs)
 {
     Path = attrs["path"];
         this.c = c;
         if (!string.IsNullOrEmpty(attrs["imageQuery"])) ImageQuery = new ResizeSettings(attrs["imageQuery"]);
 }
Example #14
0
        public Task<HttpResponseMessage> GetImage(string artistName, CancellationToken token)
        {
            return GetImageList(artistName, token).ContinueWith(imageTask =>
            {
                var response = new HttpResponseMessage();
                var client = new WebClient();
                var firstImage = imageTask.Result.FirstOrDefault();

                if (!string.IsNullOrEmpty(firstImage))
                {
                    var uri = new Uri(firstImage, UriKind.RelativeOrAbsolute);

                    if (!uri.IsAbsoluteUri)
                    {
                        uri = new Uri("http://2fm.rte.ie/images/default-album-art.jpg");
                    }

                    var query = Request.RequestUri.ParseQueryString();
                    var settings = new ResizeSettings(query);
                    var remote = RemoteReaderPlugin.Current.CreateSignedUrl(uri.ToString().Replace(" ", "%20"), settings);
                    var r = Request.CreateResponse(HttpStatusCode.Moved);
                    r.Headers.Location = new Uri(remote, UriKind.RelativeOrAbsolute);

                    return r;
                    //var imageStream = client.OpenRead(firstImage);
                    //response.Content = new StreamContent(imageStream);
                    //response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                    //return response;
                }

                response.Content = new StreamContent(new MemoryStream());
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                return response;
            });
        }
        /// <summary>
        /// The resize image.
        /// </summary>
        /// <param name="source">
        /// The source.
        /// </param>
        /// <param name="width">
        /// The width.
        /// </param>
        /// <param name="height">
        /// The height.
        /// </param>
        /// <returns>
        /// The <see cref="byte[]"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// </exception>
        public byte[] ResizeImage(byte[] source, int width, int height)
        {
            byte[] result = null;
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            using (var sourceStream = new MemoryStream(source.Length))
            {
                sourceStream.Write(source, 0, source.Length);
                sourceStream.Seek(0, SeekOrigin.Begin);
                var settings = new ResizeSettings();
                settings.Width = width;
                settings.Height = height;
                settings.Mode = FitMode.Crop;
                using (var destinationStream = new MemoryStream())
                {
                    ImageBuilder.Current.Build(sourceStream, destinationStream, settings);
                    result = destinationStream.ToArray();
                }

                return result;
            }
        }
Example #16
0
        public static Bitmap ResizeImage(Stream imageStream, PhotoSize size)
        {
            var maxHeight = 0;
            var maxWidth = 0;

            switch (size)
            {
                case PhotoSize.Medium:
                    maxHeight = 225;
                    maxWidth = 225;
                    break;

                case PhotoSize.Fullsize:
                    break;

                default:
                    maxHeight = 125;
                    maxWidth = 125;
                    break;
            }
            var rs = new ResizeSettings();
            if (maxHeight > 0)
            {
                rs.MaxHeight = maxHeight;
                rs.MaxWidth = maxWidth;
            }            
            return ImageBuilder.Current.Build(imageStream, rs);
        }
Example #17
0
        protected override RequestedAction PostDecodeStream(ref Bitmap b, ResizeSettings settings)
        {
            if (!"true".Equals(settings["autorotate"], StringComparison.OrdinalIgnoreCase)) return RequestedAction.None;

            int propertyId = 0x0112;
            PropertyItem pi;
            try {
                pi = b.GetPropertyItem(propertyId);
            } catch (ArgumentException) {
                return RequestedAction.None;
            }
            if (pi == null) return RequestedAction.None;

            int total = 0;

            foreach (byte by in pi.Value) total += by; //Does not handle values larger than 255, but it doesn't need to, and is endian-agnostic.

            if (total == 8) b.RotateFlip(RotateFlipType.Rotate270FlipNone);
            if (total == 3) b.RotateFlip(RotateFlipType.Rotate180FlipNone);
            if (total == 6) b.RotateFlip(RotateFlipType.Rotate90FlipNone);

            if (total == 2) b.RotateFlip(RotateFlipType.RotateNoneFlipX);
            if (total == 4) b.RotateFlip(RotateFlipType.Rotate180FlipX);
            if (total == 5) b.RotateFlip(RotateFlipType.Rotate270FlipY);
            if (total == 7) b.RotateFlip(RotateFlipType.Rotate90FlipY);

            b.RemovePropertyItem(propertyId);

            return RequestedAction.None;
        }
        // POST: api/SaveImages + ?id!
        //[Route("api/SaveImages/{id:int}")]
        public async Task<IHttpActionResult> PostSalonImage(int id, Boolean main, [FromUri]string username)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            // Check if the request contains multipart/form-data.
            if (Request.Content.IsMimeMultipartContent())
            {
                var streamProvider = new MultipartMemoryStreamProvider();
                streamProvider = await Request.Content.ReadAsMultipartAsync(streamProvider);

                foreach (var item in streamProvider.Contents.Where(c => !string.IsNullOrEmpty(c.Headers.ContentDisposition.FileName)))
                {
                    Stream stPictureSource = new MemoryStream(await item.ReadAsByteArrayAsync());

                    // Resize for Picture
                    MemoryStream stPictureDest = new MemoryStream();
                    var pictureSettings = new ResizeSettings
                    {
                        MaxWidth = 1000,
                        MaxHeight = 1000,
                        Mode = FitMode.Max
                    };
                    ImageBuilder.Current.Build(stPictureSource, stPictureDest, pictureSettings);

                    string fileName = item.Headers.ContentDisposition.FileName;

                    fileName = fileName.Replace("\"", string.Empty);

                    string ext = Path.GetExtension(fileName);

                    string newFileName = Guid.NewGuid().ToString() + ext;

                    File.WriteAllBytes(HostingEnvironment.MapPath("~/Images/SalonImages/" + newFileName), stPictureDest.ToArray());

                    db.SalonImages.Add(new SalonImage
                    {
                        AddedOn = DateTime.Now,
                        CreateBy = username,
                        ImageName = fileName,
                        ImagePath = newFileName,
                        IsDeleted = false,
                        IsMain = main,
                        SalonID = id,

                    });
                }

                await db.SaveChangesAsync();
                return Ok();
            }
            else
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

        }
        public static void ImageBuilder(string imageFile, ImageType type, bool IsInTempFolder,AspxCommonInfo aspxCommonObj)
        {

            try
            {
                bool disposeSource = true;
                bool addFileExtensions = true;
                string tempFolder = string.Empty;
                string filename = imageFile;
                bool isExistImage = false;
                var resizeSetings = new ResizeSettings();
                resizeSetings.Format = "jpg";
                resizeSetings.Mode = FitMode.Max;
                switch (type)
                {
                    case ImageType.Large:
                        {
                            isExistImage = CheckIfImageExists(ImageType.Large, filename);
                            if (!(isExistImage))
                            {
                               ImageSettings imgStng=new ImageSettings(aspxCommonObj);
                               resizeSetings.MaxWidth = imgStng.itemLargeThumbNailWidth;
                               resizeSetings.MaxHeight = imgStng.itemLargeThumbNailHeight;
                               copyOriginalImageToRespectives(ImageType.Large, filename, resizeSetings,disposeSource, addFileExtensions);
                            }
                            break;
                        }
                    case ImageType.Medium:
                        {
                            isExistImage = CheckIfImageExists(ImageType.Medium, filename);
                            if (!(isExistImage))
                            {
                                ImageSettings imgStng = new ImageSettings(aspxCommonObj);
                                resizeSetings.MaxWidth = imgStng.itemMediumThumbNailWidth;
                                resizeSetings.MaxHeight = imgStng.itemMediumThumbNailHeight;
                                copyOriginalImageToRespectives(ImageType.Medium, filename, resizeSetings, disposeSource, addFileExtensions);
                            }
                            break;
                        }
                    case ImageType.Small:
                        {
                            isExistImage = CheckIfImageExists(ImageType.Medium, filename);
                            if (!(isExistImage))
                            {
                                ImageSettings imgStng = new ImageSettings(aspxCommonObj);
                                resizeSetings.MaxWidth = imgStng.itemSmallThumbNailWidth;
                                resizeSetings.MaxHeight = imgStng.itemSmallThumbNailHeight;
                                copyOriginalImageToRespectives(ImageType.Medium, filename, resizeSetings, disposeSource, addFileExtensions);
                            }
                            break;
                        }

                }

            }
            catch
            {
            }
        }
Example #20
0
 public Stream ResizeToStream(string instructions)
 {
     var settings = new ResizeSettings(instructions);
     var ostream = new MemoryStream();
     ImageBuilder.Current.Build(Bits, ostream, settings);
     ostream.Position = 0;
     return ostream;
 }
Example #21
0
 public void TestCropValues()
 {
     ResizeSettings s = new ResizeSettings();
     s.CropBottomRight = new System.Drawing.PointF(50, 50);
     s.CropTopLeft = new System.Drawing.PointF(0, 0);
     Assert.AreEqual<string>( "?crop=0,0,50,50", s.ToString());
     s.CropMode = CropMode.Auto;
     Assert.AreEqual<string>("?crop=auto", s.ToString());
 }
Example #22
0
 /// <summary>
 /// Extend this to support alternate image source formats. 
 /// If the Bitmap class is used for decoding, read gdi-bugs.txt and make sure you set b.Tag to new BitmapTag(optionalPath,stream);
 /// </summary>
 /// <param name="s"></param>
 /// <param name="settings"></param>
 /// <param name="optionalPath"></param>
 /// <returns></returns>
 public virtual Bitmap DecodeStream(Stream s, ResizeSettings settings, string optionalPath)
 {
     if (exts == null) return null;
     foreach (AbstractImageProcessor p in exts) {
         Bitmap b = p.DecodeStream(s,settings, optionalPath);
         if (b != null) return b;
     }
     return null;
 }
Example #23
0
        public override Bitmap DecodeStreamFailed(Stream s, ResizeSettings settings, string optionalPath)
        {
            //Catch WebP files not ending in .webp
            try {
                return Decode(s);
            } catch {

                return null;
            }
        }
        public byte[] ResizeImage(byte[] bytes, int maxWidth, int maxHeight)
        {
            using (var sourceImage = new MemoryStream(bytes))
            using (var destinationImage = new MemoryStream())
            {
                var resizeSettings = new ResizeSettings { MaxHeight = maxHeight, MaxWidth = maxWidth };

                ImageBuilder.Current.Build(sourceImage, destinationImage, resizeSettings);
                return destinationImage.ToArray();
            }
        }
        public static string SquareCropping(this UmbracoHelper umbracoHelper, IPublishedContent publishedContent)
        {
            var r = new ResizeSettings();
            r.MaxWidth = 200;
            r.MaxHeight = 300;

            ImageBuilder.Current.Build("~/images/photo.jpg", "~/images/photo.jpg",
                               new ResizeSettings("width=100&height=200&crop=auto"));

            return null;
        }
Example #26
0
 // metoda zmieniajaca rozmiar zdjec przy pomocy biblioteki ImageResizer
 public static byte[] OptimizeImageFromBytes(int imgWidth, int imgHeight, byte[] imgBytes)
 {
     var settings = new ResizeSettings
     {
         MaxWidth = imgWidth,
         MaxHeight = imgHeight
     };
     MemoryStream ms = new MemoryStream();
     ImageBuilder.Current.Build(imgBytes, ms, settings);
     return ms.ToArray(); // zwraca pomniejszone zdjecie w postaci tablicy bajtow
 }
Example #27
0
        public override Bitmap DecodeStream(Stream s, ResizeSettings settings, string optionalPath)
        {
            bool requested = "webp".Equals(settings["decoder"], StringComparison.OrdinalIgnoreCase);
            if (!string.IsNullOrEmpty(settings["decoder"]) && !requested) return null; //Don't take it away from the requested decoder

            //If a .webp is coming in, try first, before Bitmap tries to parse it.
            if (requested || (optionalPath != null && optionalPath.EndsWith(".webp", StringComparison.OrdinalIgnoreCase))) {
                return Decode(s);
            }
            return null;
        }
 public byte[] GenerateThumbnail(byte[] sourceArray)
 {
     using (var outStream = new MemoryStream())
     {
         using (var inStream = new MemoryStream(sourceArray))
         {
             var settings = new ResizeSettings("height=" + MaxHeight + "&mode=pad&bgcolor=FFFFFF&anchor=middlecenter&scale=upscalecanvas");
             ImageBuilder.Current.Build(inStream, outStream, settings);
             return outStream.ToArray();
         }
     }
 }
Example #29
0
        public void TestMergingConstructor(string q, string defaults, string expected)
        {
            ResizeSettings defaultSettings = new ResizeSettings(defaults);
            ResizeSettings mergedSettings = new ResizeSettings(q, defaultSettings);
            ResizeSettings expectedSettings = new ResizeSettings(expected);

            Assert.AreEqual(expectedSettings.Count, mergedSettings.Count);
            foreach (string key in expectedSettings.AllKeys)
            {
                Assert.AreEqual(expectedSettings[key], mergedSettings[key]);
            }
        }
Example #30
0
 public override System.Drawing.Bitmap DecodeStream(System.IO.Stream s, ResizeSettings settings, string optionalPath)
 {
     bool useICM = true;
     if (settings != null && "true".Equals(settings["ignoreicc"], StringComparison.OrdinalIgnoreCase)) useICM = false;
     Bitmap b;
     //NDJ - May 24, 2011 - Copying stream into memory so the original can be closed safely.
     MemoryStream ms = StreamUtils.CopyStream(s);
     //b = new Bitmap(ms, useICM);
     b = FastBitmapLoader(ms, useICM);
     b.Tag = new BitmapTag(optionalPath, ms); //May 25, 2011: Storing a ref to the MemorySteam so it won't accidentally be garbage collected.
     return b;
 }
Example #31
0
        public FileContentResult GetQuestionImage(int id)
        {
            var v = _examinationRepository.GetExamQuestion(id);

            if (v != null)
            {
                byte[] byteArray = v.ImageData;
                using (var outStream = new MemoryStream())
                {
                    using (var inStream = new MemoryStream(byteArray))
                    {
                        //
                        var settings = new ResizeSettings("maxwidth=400&maxheight=100");
                        ImageBuilder.Current.Build(inStream, outStream, settings);
                        var outBytes = outStream.ToArray();
                        return(new FileContentResult(outBytes, "image/jpeg"));
                    }
                }
            }

            return(null);
        }
Example #32
0
        public void ProcessForceWriteCacheRemovalsTest()
        {
            // Arrange
            int actual   = 0;
            var rs       = new ResizerSection(ConfigXml);
            var c        = new Config(rs);
            var target   = c.Plugins.Get <TinyCachePlugin>();
            int expected = target.MaxItems + 50;

            ResizeSettings settings = new ResizeSettings();

            settings.Cache = ServerCacheMode.Default;
            ResponseArgs args = new ResponseArgs();

            args.RewrittenQuerystring = settings;

            File.Delete(target.PhysicalCacheFile);
            target.VirtualCacheFile = "folder/TooMany.txt";
            if (Directory.Exists(Path.GetDirectoryName(target.PhysicalCacheFile)))
            {
                Directory.Delete(Path.GetDirectoryName(target.PhysicalCacheFile), true);
            }

            // Act
            for (int i = 0; i < target.MaxItems + 50; i++)
            {
                args.ResizeImageToStream = (Stream ms) =>
                {
                    ms.WriteByte(99);
                    actual++;
                };
                args.RequestKey = string.Format(CultureInfo.InvariantCulture, "test{0}", i);
                target.Process(HttpContext.Current, args);
            }

            // Assert
            Assert.True(File.Exists(target.PhysicalCacheFile));
            Assert.Equal <int>(expected, actual);
        }
        public ActionResult Create([Bind(Include = "TrainingID,NameMon,NameEng,ContentMon,ContentEng,Where,When,Duration,Status,Type,Image")] Training Training, HttpPostedFileBase ImageFile)
        {
            if (ModelState.IsValid)
            {
                if (ImageFile != null)
                {
                    string subPath = "/Content/Images/NewsImage"; // your code goes here

                    bool exists = System.IO.Directory.Exists(Server.MapPath(subPath));

                    if (!exists)
                    {
                        System.IO.Directory.CreateDirectory(Server.MapPath(subPath));
                    }

                    string fileName  = Path.GetFileNameWithoutExtension(ImageFile.FileName);
                    string extension = Path.GetExtension(ImageFile.FileName);
                    fileName       = fileName + DateTime.Now.ToString("yymmssfff") + extension;
                    Training.Image = "/Content/Images/NewsImage/" + fileName;
                    fileName       = Path.Combine(Server.MapPath("~/Content/Images/NewsImage/"), fileName);
                    ImageFile.SaveAs(fileName);

                    ResizeSettings resizeSetting = new ResizeSettings
                    {
                        Width  = 1920,
                        Height = 1280,
                        Format = "png"
                    };
                    ImageBuilder.Current.Build(fileName, fileName, resizeSetting);
                }

                Training.Status = 0;
                db.Trainings.Add(Training);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(Training));
        }
Example #34
0
        public void ApplyFilter(FilterContext context)
        {
            string format  = context.State.Format;
            int    quality = context.State.Quality;

            var settings = new ResizeSettings {
                Quality = quality,
                Format  = format
            };

            var result = new MemoryStream();

            if (context.Media.CanSeek)
            {
                context.Media.Seek(0, SeekOrigin.Begin);
            }

            ImageBuilder.Current.Build(context.Media, result, settings);

            context.FilePath = Path.ChangeExtension(context.FilePath, format);
            context.Media    = result;
        }
Example #35
0
        /// <summary>
        /// Load initial data from last used settings
        /// </summary>
        void LoadSettings()
        {
            // if settings are not saved, create default settings
            if (string.IsNullOrEmpty(Properties.Settings.Default.querystring))
            {
                Properties.Settings.Default.querystring = "maxwidth=1024&maxheight=768";
                Properties.Settings.Default.Save();
            }


            ResizeSettings rs = new ResizeSettings(Properties.Settings.Default.querystring);

            // set settings to the GUI
            tbox_width.Text  = (rs.Width != -1) ? rs.Width.ToString() : rs.MaxWidth.ToString();
            tbox_height.Text = (rs.Height != -1) ? rs.Height.ToString() : rs.MaxHeight.ToString();

            if (Properties.Settings.Default.querystring.Contains("maxheight"))
            {
                aOptions.cbox_resizeMode.SelectedIndex = 0;
            }
            else if (Properties.Settings.Default.querystring.Contains("crop=auto"))
            {
                aOptions.cbox_resizeMode.SelectedIndex = 2;
            }
            else
            {
                aOptions.cbox_resizeMode.SelectedIndex = 1;
            }

            if (Properties.Settings.Default.querystring.Contains("scale=both"))
            {
                aOptions.cbUpscale.IsChecked = true;
            }

            if (!string.IsNullOrEmpty(Properties.Settings.Default.saveFolderPath))
            {
                tbox_savePath.Text = Properties.Settings.Default.saveFolderPath;
            }
        }
 public FileContentResult byteArrayToImageResized(int id, string w, string h)
 {
     byte[] byteArray = db.GetElementById(id).Pictures;
     try
     {
         using (var outStream = new MemoryStream())
         {
             using (var inStream = new MemoryStream(byteArray))
             {
                 var settings = new ResizeSettings(String.Format("width={0}&height={1}", w, h));
                 ImageResizer.ImageBuilder.Current.Build(inStream, outStream, settings);
                 var outBytes = outStream.ToArray();
                 return(new FileContentResult(outBytes, "image/jpeg"));
             }
         }
     }
     catch (ArgumentNullException)
     {
         Console.WriteLine("Null reference exeption");
         return(null);
     }
 }
Example #37
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            var inputStream = await req.Content.ReadAsStreamAsync();

            log.Info("START");
            byte[] bytes;

            // Generate a thumbnail and save it in the "thumbnails" container
            using (var outputStream = new MemoryStream())
            {
                var settings = new ResizeSettings {
                    MaxWidth = 192, Format = "png"
                };
                ImageBuilder.Current.Build(inputStream, outputStream, settings);
                outputStream.Seek(0L, SeekOrigin.Begin);
                bytes = outputStream.ToArray();
            }

            log.Info("Generated bytes");

            return(req.CreateResponse(bytes));
        }
Example #38
0
        public string UploadImage(HttpPostedFileBase hinhanh)
        {
            string pic   = Path.GetFileName(hinhanh.FileName);
            string pfull = System.IO.Path.Combine(Server.MapPath(urlImage));

            if (!Directory.Exists(pfull))
            {
                Directory.CreateDirectory(pfull);
            }
            string path = System.IO.Path.Combine(Server.MapPath(urlImage), pic);

            hinhanh.SaveAs(path);
            ResizeSettings resizeSetting = new ResizeSettings
            {
                Width  = 320,
                Height = 320,
                Format = "png"
            };

            ImageBuilder.Current.Build(path, path, resizeSetting);
            return(urlImage + pic);
        }
Example #39
0
        public async Task <IActionResult> Avatar(int id, IFormFile avatar)
        {
            var player = await LoadAndEnsurePlayerExists(id);

            if (avatar.Length > 0)
            {
                var settings = new ResizeSettings
                {
                    MaxWidth  = 150,
                    MaxHeight = 150,
                    Format    = "png"
                };

                var outputStream = new MemoryStream();
                ImageBuilder.Current.Build(avatar.OpenReadStream(), outputStream, settings);

                player.Image = outputStream.ToArray();
                await _db.SaveChangesAsync();
            }

            return(RedirectToAction("Index", new { id }));
        }
Example #40
0
        public ActionResult GalleryCreate([Bind(Include = "GalleryID,TitleMon,TitleEng,Image,Tags")] Gallery Gallery, HttpPostedFileBase ImageFile)
        {
            if (ModelState.IsValid)
            {
                if (ImageFile != null)
                {
                    string subPath = "/Content/Images/GalleryImage"; // your code goes here

                    bool exists = System.IO.Directory.Exists(Server.MapPath(subPath));

                    if (!exists)
                    {
                        System.IO.Directory.CreateDirectory(Server.MapPath(subPath));
                    }

                    string fileName  = Path.GetFileNameWithoutExtension(ImageFile.FileName);
                    string extension = Path.GetExtension(ImageFile.FileName);
                    fileName      = fileName + DateTime.Now.ToString("yymmssfff") + extension;
                    Gallery.Image = "/Content/Images/GalleryImage/" + fileName;
                    fileName      = Path.Combine(Server.MapPath("~/Content/Images/GalleryImage/"), fileName);
                    ImageFile.SaveAs(fileName);

                    ResizeSettings resizeSetting = new ResizeSettings
                    {
                        Width  = 1920,
                        Height = 1280,
                        Format = "png"
                    };
                    ImageBuilder.Current.Build(fileName, fileName, resizeSetting);
                }
                db.Galleries.Add(Gallery);
                db.SaveChanges();
                NorthwindDataProvider.InsertTagDetail(Gallery.GalleryID, Gallery.Tags, "Galleries");
                SendNotificationMessage();
                return(RedirectToAction("Gallery"));
            }

            return(View(Gallery));
        }
Example #41
0
        public MemoryStream GenerateThumbnail(string videoId, int size)
        {
            try
            {
                var url = "http://vimeo.com/api/oembed.json?url=http%3A//vimeo.com/" + videoId;

                var    request = WebRequest.Create(url);
                string text;
                var    response = (HttpWebResponse)request.GetResponse();

                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    text = sr.ReadToEnd();
                }

                dynamic job = JObject.Parse(text);

                var    webClient  = new WebClient();
                byte[] imageBytes = webClient.DownloadData(job.thumbnail_url.ToString());

                //var source = ResizeStream(imageBytes, 300);
                var ms   = new MemoryStream(imageBytes);
                var dest = new MemoryStream();

                var r = new ResizeSettings()
                {
                };
                r.MaxWidth = size;
                r.Format   = "jpg";
                var eee = new ImageResizer.ImageJob(ms, dest, r);
                eee.Build();
                return(dest);
            }
            catch (Exception)
            {
                return(null);
            }
        }
        /// <summary>
        /// Overloaded method to handle MemoryStream data taken from clipboard etc.
        /// </summary>
        /// <param name="sourceStream"></param>
        /// <param name="target"></param>
        /// <param name="resizeSetting"></param>
        public void ResizeImageBytes(MemoryStream sourceStream, string target)
        {
            if (string.IsNullOrEmpty(target))
            {
                throw new ArgumentNullException();
            }

            //load bitmap to get image attributes
            Bitmap img = new Bitmap(sourceStream);

            //initialise resize settings
            ResizeSettings resizeSetting = new ResizeSettings
            {
                Width  = img.Width,
                Height = img.Height
            };

            //backup sourceStream
            MemoryStream sourceBackup = new MemoryStream();

            sourceStream.CopyTo(sourceBackup);

            //set memory stream read position back to the beginning
            sourceStream.Seek(0, SeekOrigin.Begin);
            sourceBackup.Seek(0, SeekOrigin.Begin);

            //Define a targetStream
            MemoryStream targetStream = new MemoryStream();

            //Execute initial Image builder as the different compression may reduce file size without changing dimensions.
            ImageBuilder.Current.Build(sourceStream, targetStream, resizeSetting);

            //Determine ResizeSettings required to meet file size criteria
            resizeSetting = GetMaxImageSettings(targetStream, resizeSetting);

            //Perform final Image resize and move to target.
            ImageBuilder.Current.Build(sourceBackup, target, resizeSetting);
        }
Example #43
0
        public PostImageController(IAdImageServices adImageServices)
        {
            if (adImageServices == null)
            {
                throw new ArgumentNullException("adImageServices");
            }

            _adImageServices    = adImageServices;
            _postImagesFilePath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Content", "PostImages");

            // Set the default resizing settings once and for all
            _postImageResizeSettings           = new ResizeSettings();
            _postImageResizeSettings.MaxWidth  = 600;
            _postImageResizeSettings.MaxHeight = 400;
            _postImageResizeSettings.Format    = "jpg";
            _postImageResizeSettings.Mode      = FitMode.Max;

            _postImageThumbnailResizeSettings          = new ResizeSettings();
            _postImageThumbnailResizeSettings.MaxWidth = 160;
            _postImageThumbnailResizeSettings.Height   = 120;
            _postImageThumbnailResizeSettings.Format   = "jpg";
            _postImageThumbnailResizeSettings.Mode     = FitMode.Max;
        }
Example #44
0
        private static void ResizeImage(int maxWidth, int maxHeight, int quality, string path)
        {
            //keep ratio
            var tempBitmap = new Bitmap(path);
            var ratioX     = (double)maxWidth / tempBitmap.Width;
            var ratioY     = (double)maxHeight / tempBitmap.Height;
            var ratio      = Math.Min(ratioX, ratioY);

            var newWidth  = (int)(tempBitmap.Width * ratio);
            var newHeight = (int)(tempBitmap.Height * ratio);

            tempBitmap.Dispose();

            var resizeSetting = new ResizeSettings
            {
                Width   = newWidth,
                Height  = newHeight,
                Quality = quality,
                Format  = "jpg"
            };

            ImageBuilder.Current.Build(path, path, resizeSetting);
        }
Example #45
0
        public static void BenchmarkEncoderInMemory(Config c, Image img, ResizeSettings settings)
        {
            MemoryStream ms = new MemoryStream();

            int       loops = 20;
            Stopwatch s     = new Stopwatch();

            s.Start();
            c.CurrentImageBuilder.EncoderProvider.GetEncoder(settings, img).Write(img, ms);
            s.Stop();
            Console.Write("First: " + s.ElapsedMilliseconds.ToString() + "ms");
            s.Reset();
            s.Start();
            for (int i = 0; i < loops; i++)
            {
                ms.Seek(0, SeekOrigin.Begin);
                ms.SetLength(0);
                IEncoder ie = c.CurrentImageBuilder.EncoderProvider.GetEncoder(settings, img);
                ie.Write(img, ms);
            }
            s.Stop();
            Console.WriteLine("Avg(" + loops + "): " + (s.ElapsedMilliseconds / loops).ToString() + "ms");
        }
Example #46
0
        public ImageLayer(NameValueCollection attrs, ResizeSettings defaultImageQuery, Config c)
            : base(attrs)
        {
            this.c = c;

            var configPath       = attrs["path"];
            var configImageQuery = attrs["imageQuery"];

            if (!string.IsNullOrEmpty(configPath))
            {
                this.Path = PathUtils.RemoveQueryString(configPath);
            }

            // Combine the ResizeSettings from 'path', 'imageQuery', and any
            // 'defaultImageQuery' settings as well.  Settings from 'imageQuery'
            // take precedence over 'path', and both take precedence over the
            // 'defaultImageQuery' settings.
            var pathSettings       = new ResizeSettings(configPath ?? string.Empty);
            var imageQuerySettings = new ResizeSettings(configImageQuery ?? string.Empty);
            var mergedSettings     = new ResizeSettings(imageQuerySettings, pathSettings);

            this.ImageQuery = new ResizeSettings(mergedSettings, defaultImageQuery);
        }
Example #47
0
        protected override void AssertLayout(string sourceSize, string resizeSettings, Action <System.Drawing.RectangleF> assertImage, Action <System.Drawing.SizeF> assertCanvas)
        {
            // build the source image
            var sourceSizeSettings = new ResizeSettings(sourceSize);
            var sourceBitmap       = CreateSourceBitmap(new Size(sourceSizeSettings.Width, sourceSizeSettings.Height));

            // resize
            var result = _ImageManipulator.Manipulate(sourceBitmap, new ImageManipulationSettings(resizeSettings));

            // save the result
            var fileName = sourceSize + "--" + resizeSettings + ".bmp";
            var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            result.Save(filePath, result.RawFormat);

            Trace.WriteLine("Source:        " + sourceSize);
            Trace.WriteLine("Destination:   " + resizeSettings);
            Trace.WriteLine("   Result:     " + filePath);
        }
        private static bool ShouldApplyFocalPoint(IFocalPointData focalPointData, ResizeSettings resizeSettings)
        {
            if (resizeSettings == null || resizeSettings.Count <= 0)
            {
                return(false);
            }
            if (resizeSettings.Mode == FitMode.Max)              // If using fitmode Max, the image won't be cropped, only resized, and focal point serves no purpose.
            {
                return(false);
            }
            if (resizeSettings.Width < 0 && resizeSettings.Height < 0)
            {
                return(false);
            }
            var targetWidthIsLargerThanOriginal  = resizeSettings.Width >= (focalPointData.OriginalWidth ?? 1);
            var targetHeightIsLargerThanOriginal = resizeSettings.Height >= (focalPointData.OriginalHeight ?? 1);

            if (targetWidthIsLargerThanOriginal && targetHeightIsLargerThanOriginal)              // If the target is bigger in both dimensions, it will result in a scaling operation, and the focal point serves no purpose.
            {
                return(false);
            }
            return(true);
        }
Example #49
0
        public static ResizeSettings CreateResizeSettings(object settings)
        {
            ResizeSettings resizeSettings;

            if (settings is string)
            {
                resizeSettings = new ResizeSettings((string)settings);
            }
            else if (settings is NameValueCollection)
            {
                resizeSettings = new ResizeSettings((NameValueCollection)settings);
            }
            else if (settings is ResizeSettings)
            {
                resizeSettings = (ResizeSettings)settings;
            }
            else
            {
                resizeSettings = new ResizeSettings();
            }

            return(resizeSettings);
        }
Example #50
0
        private RectangleF determineManualCropWindow(ResizeSettings settings)
        {
            RectangleF cropWindow = copyRect;

            if (cropWindow.IsEmpty)
            {
                //Use the crop size if present.
                cropWindow = new RectangleF(new PointF(0, 0), originalSize);
                if (settings.GetList <double>("crop", 0, 4) != null)
                {
                    cropWindow = PolygonMath.ToRectangle(settings.getCustomCropSourceRect(originalSize)); //Round the custom crop rectangle coordinates
                    //Ensure right/bottom bounded after rounding completes
                    cropWindow.Width  = Math.Min(originalSize.Width - cropWindow.Left, cropWindow.Width);
                    cropWindow.Height = Math.Min(originalSize.Height - cropWindow.Top, cropWindow.Height);

                    if (cropWindow.Size.IsEmpty)
                    {
                        throw new Exception("You must specify a custom crop rectangle if crop=custom");
                    }
                }
            }
            return(cropWindow);
        }
Example #51
0
 /// <summary>
 /// Allows .Build and .LoadImage to resize remote URLs
 /// </summary>
 /// <param name="source"></param>
 /// <param name="settings"></param>
 /// <param name="disposeStream"></param>
 /// <param name="path"></param>
 /// <param name="restoreStreamPosition"></param>
 /// <returns></returns>
 protected override Stream GetStream(object source, ResizeSettings settings, ref bool disposeStream, out string path, out bool restoreStreamPosition)
 {
     //Turn remote URLs into URI instances
     if (source is string && (((string)source).StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
                              ((string)source).StartsWith("https://", StringComparison.OrdinalIgnoreCase)))
     {
         if (Uri.IsWellFormedUriString((string)source, UriKind.Absolute))
         {
             source = new Uri((string)source);
         }
     }
     restoreStreamPosition = false;
     path = null;
     //Turn URI instances into streams
     if (source is Uri)
     {
         using (var s = GetUriStream(source as Uri))
         {
             return(s.CopyToMemoryStream());
         }
     }
     return(null);
 }
Example #52
0
        public ActionResult Create([Bind(Include = "DID,Pnamemon,Pnameeng,ParagraphMon,ParagraphEng,PositionMon,PositionEng,Image")] Donor donor, HttpPostedFileBase ImageFile)
        {
            if (ModelState.IsValid)
            {
                if (ImageFile != null)
                {
                    string subPath = "/Content/Images/DonorSay"; // your code goes here

                    bool exists = System.IO.Directory.Exists(Server.MapPath(subPath));

                    if (!exists)
                    {
                        System.IO.Directory.CreateDirectory(Server.MapPath(subPath));
                    }

                    string fileName  = Path.GetFileNameWithoutExtension(ImageFile.FileName);
                    string extension = Path.GetExtension(ImageFile.FileName);
                    fileName    = fileName + DateTime.Now.ToString("yymmssfff") + extension;
                    donor.Image = "/Content/Images/DonorSay/" + fileName;
                    fileName    = Path.Combine(Server.MapPath("~/Content/Images/DonorSay/"), fileName);
                    ImageFile.SaveAs(fileName);

                    ResizeSettings resizeSetting = new ResizeSettings
                    {
                        Width  = 1920,
                        Height = 1280,
                        Format = "png"
                    };
                    ImageBuilder.Current.Build(fileName, fileName, resizeSetting);
                }
                db.Donor.Add(donor);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(donor));
        }
Example #53
0
        private static object ToneMap(ref FIBITMAP b, bool mayUnloadOriginal, ResizeSettings settings, DecodeCallback callback)
        {
            return(callback(ref b, mayUnloadOriginal));//Tone mapping is disabled, not yet functional

            FIBITMAP m = FIBITMAP.Zero;

            try {
                var alg = settings.Get <ToneMappingAlgorithm>("fi.tonemap", ToneMappingAlgorithm.None);
                if (alg == ToneMappingAlgorithm.Drago)
                {
                    m = FreeImage.TmoDrago03(b, 2.2, 0);
                }
                else if (alg == ToneMappingAlgorithm.Reinhard)
                {
                    m = FreeImage.TmoReinhard05(b, 0, 0);
                }
                else if (alg == ToneMappingAlgorithm.Fattal)
                {
                    m = FreeImage.TmoFattal02(b, 0.5, 0.85);
                }
                else
                {
                    return(callback(ref b, mayUnloadOriginal));
                }
                if (mayUnloadOriginal)
                {
                    FreeImage.UnloadEx(ref b);
                }

                return(callback(ref m, true));
            } finally {
                if (!m.IsNull)
                {
                    FreeImage.UnloadEx(ref m);
                }
            }
        }
Example #54
0
        protected void ParseXml(Node n, Config conf)
        {
            if (n == null)
            {
                return;
            }
            OnlyAllowPresets = NameValueCollectionExtensions.Get(n.Attrs, "onlyAllowPresets", OnlyAllowPresets);
            if (n.Children == null)
            {
                return;
            }
            foreach (Node c in n.Children)
            {
                string name = c.Attrs["name"];
                if (c.Name.Equals("preset", StringComparison.OrdinalIgnoreCase))
                {
                    //Verify the name is specified and is unique.
                    if (string.IsNullOrEmpty(name) || defaults.ContainsKey(name) || settings.ContainsKey(name))
                    {
                        conf.configurationSectionIssues.AcceptIssue(new Issue("Presets", "The name attribute for each preset must be specified, and must be unique.",
                                                                              "XML: " + c.ToString(), IssueSeverity.ConfigurationError));
                        continue;
                    }

                    if (!string.IsNullOrEmpty(c.Attrs["defaults"]))
                    {
                        defaults[name] = new ResizeSettings(c.Attrs["defaults"]);
                    }
                    if (!string.IsNullOrEmpty(c.Attrs["settings"]))
                    {
                        settings[name] = new ResizeSettings(c.Attrs["settings"]);
                    }
                }
            }
            return;
        }
Example #55
0
        public JsonResult FileUpload()
        {
            try
            {
                HttpPostedFile file = null;
                if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
                {
                    file = System.Web.HttpContext.Current.Request.Files["HttpPostedFileBase"];
                }
                string stamp        = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now);
                string filename     = file.FileName;
                string pic          = System.IO.Path.GetFileName(filename);
                string thumbnailpic = System.IO.Path.GetFileName(file.FileName.Split('.')[0] + "_thumb." + file.FileName.Split('.')[1]);

                string path = System.IO.Path.Combine(
                    Server.MapPath("~/images/lots"), pic);
                string thumbpath = System.IO.Path.Combine(
                    Server.MapPath("~/images/lots"), thumbnailpic);
                // file is uploaded
                file.SaveAs(path);

                ResizeSettings resizeSetting = new ResizeSettings
                {
                    Width  = 220,
                    Height = 220,
                    Format = file.FileName.Split('.')[1]
                };
                ImageBuilder.Current.Build(path, thumbpath, resizeSetting);
                // after successfully uploading redirect the user
                return(Json("File Uploaded", JsonRequestBehavior.AllowGet));
            }
            catch
            {
                return(Json("Eror"));
            }
        }
Example #56
0
        public MemoryStream ResizeImage(Stream source, int?maxWidth = null, int?maxHeight = null, int?quality = 0, object settings = null)
        {
            Guard.ArgumentNotNull(() => source);

            ResizeSettings resizeSettings = ImageResizerUtils.CreateResizeSettings(settings);

            if (quality.HasValue)
            {
                resizeSettings.Quality = quality.Value;
            }
            if (maxHeight.HasValue)
            {
                resizeSettings.MaxHeight = maxHeight.Value;
            }
            if (maxWidth.HasValue)
            {
                resizeSettings.MaxWidth = maxWidth.Value;
            }

            var resultStream = new MemoryStream();

            ImageBuilder.Current.Build(source, resultStream, resizeSettings);
            return(resultStream);
        }
Example #57
0
        public JsonResult FileUpload()
        {
            HttpPostedFile file = null;

            if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
            {
                file = System.Web.HttpContext.Current.Request.Files["HttpPostedFileBase"];
            }
            string pic  = System.IO.Path.GetFileName(file.FileName);
            string path = System.IO.Path.Combine(
                Server.MapPath("~/images"), pic);

            // file is uploaded
            file.SaveAs(path);
            ResizeSettings resizeSetting = new ResizeSettings
            {
                Width  = 300,
                Height = 200,
                Format = file.FileName.Split('.')[1]
            };

            ImageBuilder.Current.Build(path, path, resizeSetting);

            // save the image path path to the database or you can send image
            // directly to database
            // in-case if you want to store byte[] ie. for DB
            using (MemoryStream ms = new MemoryStream())
            {
                file.InputStream.CopyTo(ms);
                byte[] array = ms.GetBuffer();
            }


            // after successfully uploading redirect the user
            return(Json("Նկարը վերբեռնված է", JsonRequestBehavior.AllowGet));
        }
Example #58
0
        /// <summary>
        /// Resizes and returns the resized content
        /// </summary>
        /// <param name="queryString">The query string.</param>
        /// <param name="fileContent">Content of the file.</param>
        /// <returns></returns>
        private Stream GetResized(NameValueCollection queryString, Stream fileContent)
        {
            try
            {
                ResizeSettings settings = new ResizeSettings(queryString);

                if (settings["mode"] == null || settings["mode"] == "clip")
                {
                    settings.Add("mode", "max");

                    if (!string.IsNullOrEmpty(settings["width"]) && !string.IsNullOrEmpty(settings["height"]))
                    {
                        if (settings["width"].AsInteger() > settings["height"].AsInteger())
                        {
                            settings.Remove("height");
                        }
                        else
                        {
                            settings.Remove("width");
                        }
                    }
                }

                settings.Add("autorotate.default", "true");

                MemoryStream resizedStream = new MemoryStream();

                ImageBuilder.Current.Build(fileContent, resizedStream, settings);
                return(resizedStream);
            }
            catch
            {
                // if resize failed, just return original content
                return(fileContent);
            }
        }
Example #59
0
        private static ResizeSettings CreateResizerSettings(byte photoNum, int photoOnPage)
        {
            ResizeSettings settings = new ResizeSettings {
                ResizeMode = ResizeMode.Rectangle, ScaleMode = ScaleMode.Both
            };

            if (photoOnPage == 4)
            {
                settings.Height = 204;
                settings.Width  = 272;
            }
            else if (photoOnPage == 3)
            {
                if (photoNum == 1)
                {
                    settings.Height = 300;
                    settings.Width  = 400;
                }
                else
                {
                    settings.Height = 204;
                    settings.Width  = 272;
                }
            }
            else if (photoOnPage == 2)
            {
                settings.Height = 255;
                settings.Width  = 340;
            }
            else
            {
                settings.Height = 346;
                settings.Width  = 462;
            }
            return(settings);
        }
        public ActionResult FileUpload(int id)
        {
            HttpPostedFile myFile = System.Web.HttpContext.Current.Request.Files["UploadedImage"];// Request.Files["MyFile"];

            string fName          = myFile.FileName;
            string fileExtenstion = FileProcessor.GetFileExtension(fName);

            string path     = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("/Content/Assets/Images"), Path.GetFileName(myFile.FileName));
            string purePath = System.Web.HttpContext.Current.Server.MapPath("/Content/Assets/Images");


            var fileUpload = new FileUpload();

            fileUpload.Upload(myFile, path);



            #region Generate small and large image

            ResizeSettings settings_sm = new ResizeSettings();
            ResizeSettings settings_lg = new ResizeSettings();

            switch (fileExtenstion)
            {
            case ".png":
                settings_sm = new ResizeSettings("width=60&height=60&crop=auto&format=png");
                settings_lg = new ResizeSettings("width=400&height=300&crop=auto&format=png");
                break;

            case ".jpg":
                settings_sm = new ResizeSettings("width=60&height=60&crop=auto&format=jpg");
                settings_lg = new ResizeSettings("width=400&height=300&crop=auto&format=jpg");
                break;

            case ".jepg":
                settings_sm = new ResizeSettings("width=60&height=60&crop=auto&format=jpg");
                settings_lg = new ResizeSettings("width=400&height=300&crop=auto&format=jpg");
                break;

            case ".gif":
                settings_sm = new ResizeSettings("width=60&height=60&crop=auto&format=gif");
                settings_lg = new ResizeSettings("width=400&height=300&crop=auto&format=gif");
                break;

            default:
                settings_sm = new ResizeSettings("width=60&height=60&crop=auto&format=jpg");
                settings_lg = new ResizeSettings("width=400&height=3000&crop=auto&format=jpg");
                break;
            }

            string fileName_sm = "category_" + id + "_sm";
            string fileName_lg = "category_" + id + "_lg";

            string newFileName_sm = Path.Combine(purePath, fileName_sm);
            string newFileName_lg = Path.Combine(purePath, fileName_lg);

            ImageBuilder.Current.Build(myFile, newFileName_sm, settings_sm, false,
                                       true);
            ImageBuilder.Current.Build(myFile, newFileName_lg, settings_lg, false,
                                       true);


            //int fileDim_sm_x = 60;
            //int fileDim_sm_y = 60;

            //string fileName_sm = "category_"  + id + "_sm" + fileExtenstion;



            //Image img = Image.FromFile(path);


            //if (img.Width > fileDim_sm_x || img.Height > fileDim_sm_y)
            //{
            //    //resize image
            //    //

            //    ImageProcessor.SaveResizedImage(purePath, fName, fileName_sm, fileDim_sm_x, fileDim_sm_y);
            //}

            #endregion



            //Update image url in db
            var category = _categoryService.FindCategoryById(id);

            category.ProductCategoryImgSamllUrl = "/Content/Assets/Images/" + fileName_sm + fileExtenstion;
            category.ProductCategoryImgLargeUrl = "/Content/Assets/Images/" + fileName_lg + fileExtenstion;

            _categoryService.UpdateCategory(category);

            return(Json("Image has been updated!"));
        }