5
\$\begingroup\$

I want to resize an image with good quality, and the most important thing is having less weight for an image so that webpages will load it faster.

I am using the below method for this. Please check it out, if it is proper or let me know if it needs any modifications. If there is a better method than this, then also please tell me.

public static void ResizeImage(int newWidth, int newHeight, Stream sourcePath, string targetPath)
{
    using (var image = System.Drawing.Image.FromStream(sourcePath))
    {
        Image imgPhoto = Image.FromStream(sourcePath);

        int sourceWidth = imgPhoto.Width;
        int sourceHeight = imgPhoto.Height;

        if (sourceWidth > newWidth || sourceHeight > newHeight)
        {
            //Consider vertical pics
            if (sourceWidth < sourceHeight)
            {
                int buff = newWidth;

                newWidth = newHeight;
                newHeight = buff;
            }

            int destX = 0, destY = 0;
            float nPercent = 0, nPercentW = 0, nPercentH = 0;

            nPercentW = ((float)newWidth / (float)sourceWidth);
            nPercentH = ((float)newHeight / (float)sourceHeight);
            if (nPercentH < nPercentW)
            {
                nPercent = nPercentH;
                destX = System.Convert.ToInt16((newWidth -
                      (sourceWidth * nPercent)) / 2);
            }
            else
            {
                nPercent = nPercentW;
                destY = System.Convert.ToInt16((newHeight -
                      (sourceHeight * nPercent)) / 2);
            }
        }

        var thumbnailImg = new Bitmap(newWidth, newHeight);
        var thumbGraph = Graphics.FromImage(thumbnailImg);
        thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
        thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
        thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
        var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
        thumbGraph.DrawImage(image, imageRectangle);
        thumbnailImg.Save(targetPath, image.RawFormat);
    }
}
\$\endgroup\$
3
  • \$\begingroup\$ Does it work? Then it's OK. \$\endgroup\$
    – CodeCaster
    Commented Jun 29, 2014 at 10:48
  • \$\begingroup\$ @CodeCaster, yes, it is working fine. Is there any improvement need in my code ??? \$\endgroup\$
    – Jeeten Parmar
    Commented Jun 29, 2014 at 10:54
  • \$\begingroup\$ In my opinion, it hasn't been tested enough, as I can see some cases where it doesn't perform correctly. \$\endgroup\$
    – Snowbody
    Commented Jul 18, 2014 at 17:26

2 Answers 2

3
\$\begingroup\$
  • Variable type choice. Why do you use Int16 and float? Most likely you'll be running on a 32-bit or 64-bit machine, and even the 32-bit machines will be optimized for math operations using double. I know you don't need perfect accuracy, but using the smaller types is not likely to save you any space or time. The optimizer will probably convert them to Int32 and double anyway and then just round them off/truncate/extend.
  • You should declare variables as late as possible. Ideally right before they're initialized. In particular, there's no point in declaring a variable, setting its initial value to 0, and then on the next line setting its value to what you really wanted.
  • What is the purpose of nPercent, destX, and destY? You calculate them then throw them away.
  • I don't think you tested this code. You have an if block that swaps newWidth and newHeight, but nothing that ever swaps them back. What's the code intended to do?
\$\endgroup\$
1
\$\begingroup\$

I had to do the same thing for an old project, and that is getting a thumbnail out of an image, and this was my code for it

   public byte[] CreateImageThumbnail(byte[] image, int width = 50, int height = 50)
    {
        using (var stream = new System.IO.MemoryStream(image))
        {
            var img = Image.FromStream(stream);
            var thumbnail = img.GetThumbnailImage(width, height, () => false, IntPtr.Zero);

            using (var thumbStream = new System.IO.MemoryStream())
            {
                thumbnail.Save(thumbStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                return thumbStream.GetBuffer();
            }
        }
    }  

I think its more flexible than yours, because it takes bytes and returns bytes

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Instead of reviewing the OP's code, you just said "Here's the codez! Look at what I did!". I'm sure it's perfectly valid and maybe better than OP's, but you've not taken the time to say why it's better or bothered to critique the code in the question. \$\endgroup\$
    – RubberDuck
    Commented Jun 30, 2014 at 19:01
  • \$\begingroup\$ What is Image.FromStream here, its not defined anywhere \$\endgroup\$
    – sairfan
    Commented Nov 14, 2020 at 18:30
  • \$\begingroup\$ Got it, its System.Drawing.Image.FromStream(stream) \$\endgroup\$
    – sairfan
    Commented Nov 14, 2020 at 18:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.