Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Hubert Thalmann 57 posts 263 karma points
    Jan 20, 2020 @ 13:26
    Hubert Thalmann
    0

    Resize images on upload in Umbraco 8

    Dear Umbraco Community

    I want to resize images on upload in umbraco 8, maybe to a maximal width of 1920px or a maximal height of 2400px.

    Whats the best practice to do this? (in Umbraco 8)

    Thanks in advance Hubert

  • Jamie Townsend 59 posts 279 karma points c-trib
    Jan 21, 2020 @ 15:05
  • Magnus Eriksson 122 posts 362 karma points
    Jan 21, 2020 @ 15:14
    Magnus Eriksson
    0

    Hubert, what is the need for having a size limit?

    Regards, Magnus

  • Hubert Thalmann 57 posts 263 karma points
    Jan 22, 2020 @ 16:22
    Hubert Thalmann
    0

    The thing is that my client wants to upload images to use it in a gallery.

    I want to override the default upload to the media library and want to compress/resize the images, because they are to heavy like 5000px to 5000px.

    I want them to be stored in the media library in umbraco at about 1920px to 2400px.

  • Magnus Eriksson 122 posts 362 karma points
    Jan 22, 2020 @ 16:37
    Magnus Eriksson
    0

    Is it a storage problem?

    My experience is rather that the clients are uploading too small/low resolution images. I resize all images used on the page to optimal sizes with imageprocessor (often in different sizes for different devices), so big sized images (within reason) are then normally not a problem.

    Regards, Magnus

  • Graham Davis 110 posts 376 karma points
    Jan 21, 2020 @ 15:44
    Graham Davis
    0

    Hi Hubert!

    I have a set of classes that I use to resize images and upload them to a CDN in Azure. From them I have pulled the code I think you will need and posted it below. In order for it to work, you will need to add a reference to System.Drawing and System.Drawing.Imaging in Visual Studio and tweak it to your situation.

    Graham

     public class UploadController : Controller
    {
        // GET: temp
        [HttpPost]
        // *** object name MUST MATCH the "name" attribute of the upload<input> tag
        // *** object name MUST ALSO be an array for Multiple files "name[]" and Server Side declared as-> "(List<HttpPostedFileBase> name)"
        public JsonResult ImageUpload(System.Web.HttpPostedFileBase photo, string agentID)
        {
            APIResponse result = new APIResponse();
            try
            {
                zbdLibrary.Azure.Storage cdn = new zbdLibrary.Azure.Storage();
                string contentType;
                byte[] imageBytes;
    
    
                if (photo != null && photo.FileName != "")
                {
                    contentType = Path.GetExtension(photo.FileName).ToLower();
    
                    using (Stream inputStream = photo.InputStream)
                    {
                        MemoryStream memoryStream = inputStream as MemoryStream;
                        if (memoryStream == null)
                        {
                            memoryStream = new MemoryStream();
                            inputStream.CopyTo(memoryStream);
                        }
                        imageBytes = memoryStream.ToArray();
                    }
    
                    string fileName =  [FilePath] = @"YourFileName" + contentType; //+ "?dt=" + DateTime.Now.ToString("o");
                    string photoURL = cdn.containerUri + fileName.Replace(@"\", "/") + "?dt=" + DateTime.Now.ToString("o");
    
                    cdn.Delete(fileName);
    
                    cdn.Upload(fileName, ResizeImage(imageBytes, [photoHeight], [photoWidth]));
    
                    result.status = PostStatus.Success;
                    result.value = photoURL;
    
                }
                else
                {
                    result.status = PostStatus.Fail;
                    result.value = "retry";
                    //return Json(result, JsonRequestBehavior.AllowGet);
                }
    
                return Json(result, JsonRequestBehavior.AllowGet);
            }
    
            catch (Exception ex)
            {
                result.status = PostStatus.Fail;
                result.value = "retry";
                result.message = ex.Message;
                return Json(result, JsonRequestBehavior.AllowGet);
            }
        }
    
    
        public byte[] ResizeImage(Image img, int iMaxHeight, int iMaxWidth)
        {
            return CompressLossy(Resize(img, iMaxHeight, iMaxWidth));
        }
    
        public byte[] CompressLossy(Image img)
        {
    
            ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
            Encoder myEncoder = Encoder.Quality;
    
            EncoderParameters myEncoderParameters = new EncoderParameters(1);
            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
            myEncoderParameters.Param[0] = myEncoderParameter;
    
            byte[] byteArray = new byte[0];
            using (MemoryStream stream = new MemoryStream())
            {
                img.Save(stream, jgpEncoder, myEncoderParameters);
                stream.Close();
                byteArray = stream.ToArray();
            }
            return byteArray;
        }
        private ImageCodecInfo GetEncoder(ImageFormat format)
        {
    
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
    
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }
        private Image Resize(Image img, int iMaxHeight, int iMaxWidth)
        {
            int iNewHeight;
            int iNewWidth;
            int lMaxDimension;
            double dblPercent;
    
            try
            {
                if (img.Height > img.Width)
                {
                    lMaxDimension = iMaxHeight;
                    //Don't let picture become distorted if size is less than the max
                    if (img.Height < lMaxDimension)
                    {
                        lMaxDimension = img.Height;
                    }
                    dblPercent = ((double)lMaxDimension / (double)img.Height);
                }
                else
                {
                    lMaxDimension = iMaxWidth;
                    if (img.Width < lMaxDimension)
                    {
                        lMaxDimension = img.Width;
                    }
                    dblPercent = (double)lMaxDimension / (double)img.Width;
                }
    
                iNewWidth = (int)(img.Width * dblPercent);
                iNewHeight = (int)(img.Height * dblPercent);
    
                Image newImage = new Bitmap(iNewWidth, iNewHeight);
                Graphics convert;
    
                convert = Graphics.FromImage(newImage);
                convert.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                convert.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                convert.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                convert.DrawImage(img, 0, 0, newImage.Width, newImage.Height);
    
                return newImage;
    
            }
            catch (Exception ex)
            {
                return img;
                throw ex;
                //string sError = ex.Message
            }
            finally
            {
                img.Dispose();
    
            }
    
        }
    
    }
    
  • Hubert Thalmann 57 posts 263 karma points
    Jan 22, 2020 @ 16:22
    Hubert Thalmann
    0

    The thing is that my client wants to upload images to use it in a gallery.

    I want to override the default upload to the media library and want to compress/resize the images, because they are to heavy like 5000px to 5000px.

    I want them to be stored in the media library in umbraco at about 1920px to 2400px.

  • Graham Davis 110 posts 376 karma points
    Jan 22, 2020 @ 16:44
    Graham Davis
    0

    I'm not sure about the best way to override Umbraco's default photo upload(if that is what you are using), but the path to the media folder can be found by:

    System.Web.Hosting.HostingEnvironment.MapPath(@"~\Media")

    Once you know how to override, covert the file to bytes and resize it using the methods I gave you above:

    var resizeFile = ResizeImage(imageBytes, 2400, 1920);

Please Sign in or register to post replies

Write your reply to:

Draft