0

This is my add image code.

 protected void SubmitButton_Click(object sender, EventArgs e)
        {
            ProductImages productImage = new ProductImages();
            productImage.ProductID = Convert.ToInt32(ProductDropDownList.SelectedValue.ToString());

            if (!FileUpload1.HasFile)
            {
                MessageLabel1.Text = "Please Select Image File";    //checking if file uploader has no file selected
            }
            else
            {
                int length = FileUpload1.PostedFile.ContentLength;
                productImage.ProductImage = new byte[length];

                FileUpload1.PostedFile.InputStream.Read(productImage.ProductImage, 0, length);

                try
                {
                    ProductImageBL.AddProductImages(productImage);
                    MessageLabel1.Text = "Product Image has been successfully added!";
                }
                catch (Exception ex)
                {
                    MessageLabel1.Text = "Some error occured while processing the request. Error Description <br/>" + ex.Message;
                }
            }
        }
Nils
  • 9,682
  • 6
  • 46
  • 72
Jabeed Ahmed
  • 125
  • 1
  • 4
  • 13

2 Answers2

3

Image compression depends on image type and what is on image. Photos of real life objects are typically in .jpg and you can't compress them much without noticeable quality losing.

Probably what you really want to do - is resize image to smaller size like 500*500 if you know this will be enought for all your needs. Keep in mind to save image aspect ratio during resizing.

Related SO question: Resize an Image C#

Community
  • 1
  • 1
dlxeon
  • 1,932
  • 1
  • 11
  • 14
1

The SO link posted by dlxeon is excellent. I use the examples there myself. However all those examples resize the image, but you can also increase the compression in jpeg files and\or decrease the DPI.

Below a complete example of how to resize and compress a jpeg. It also checks if the image needs rotating in case the phone was held vertical for example. And you can add padding if you want to make the image square.

Note that if you use this example as is the transparency of .png and .gif files will be lost because they are converted to jpg.

    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile == true)
        {
            using (Bitmap postedImage = new Bitmap(FileUpload1.PostedFile.InputStream))
            {
                byte [] bin = Common.scaleImage(postedImage, 400, 400, false);
                Image1.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(bin);
            }
        }
    }


    public static byte[] scaleImage(Image image, int maxWidth, int maxHeight, bool padImage)
    {
        try
        {
            int newWidth;
            int newHeight;
            byte[] returnArray;

            //check if the image needs rotating (eg phone held vertical when taking a picture for example)
            foreach (var prop in image.PropertyItems)
            {
                if (prop.Id == 0x0112)
                {
                    int rotateValue = image.GetPropertyItem(prop.Id).Value[0];
                    RotateFlipType flipType = getRotateFlipType(rotateValue);
                    image.RotateFlip(flipType);
                    break;
                }
            }

            //apply padding if needed
            if (padImage == true)
            {
                image = applyPaddingToImage(image);
            }

            //check if the with or height of the image exceeds the maximum specified, if so calculate the new dimensions
            if (image.Width > maxWidth || image.Height > maxHeight)
            {
                var ratioX = (double)maxWidth / image.Width;
                var ratioY = (double)maxHeight / image.Height;
                var ratio = Math.Min(ratioX, ratioY);

                newWidth = (int)(image.Width * ratio);
                newHeight = (int)(image.Height * ratio);
            }
            else
            {
                newWidth = image.Width;
                newHeight = image.Height;
            }

            //start with a new image
            var newImage = new Bitmap(newWidth, newHeight);

            //set the new resolution, 72 is usually good enough for displaying images on monitors
            newImage.SetResolution(72, 72);
            //or use the original resolution
            //newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            //resize the image
            using (var graphics = Graphics.FromImage(newImage))
            {
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                graphics.DrawImage(image, 0, 0, newWidth, newHeight);
            }
            image = newImage;

            //save the image to a memorystream to apply the compression level, higher compression = better quality = bigger images
            using (MemoryStream ms = new MemoryStream())
            {
                EncoderParameters encoderParameters = new EncoderParameters(1);
                encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 80L);
                image.Save(ms, getEncoderInfo("image/jpeg"), encoderParameters);

                //save the stream as byte array
                returnArray = ms.ToArray();
            }

            //cleanup
            image.Dispose();
            newImage.Dispose();

            return returnArray;
        }
        catch (Exception ex)
        {
            //there was an error: ex.Message
            return null;
        }
    }


    private static ImageCodecInfo getEncoderInfo(string mimeType)
    {
        ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
        for (int j = 0; j < encoders.Length; ++j)
        {
            if (encoders[j].MimeType.ToLower() == mimeType.ToLower())
                return encoders[j];
        }
        return null;
    }


    private static Image applyPaddingToImage(Image image)
    {
        //get the maximum size of the image dimensions
        int maxSize = Math.Max(image.Height, image.Width);
        Size squareSize = new Size(maxSize, maxSize);

        //create a new square image
        Bitmap squareImage = new Bitmap(squareSize.Width, squareSize.Height);

        using (Graphics graphics = Graphics.FromImage(squareImage))
        {
            //fill the new square with a color
            graphics.FillRectangle(Brushes.Red, 0, 0, squareSize.Width, squareSize.Height);

            graphics.CompositingMode = CompositingMode.SourceCopy;
            graphics.CompositingQuality = CompositingQuality.HighQuality;
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

            //put the original image on top of the new square
            graphics.DrawImage(image, (squareSize.Width / 2) - (image.Width / 2), (squareSize.Height / 2) - (image.Height / 2), image.Width, image.Height);
        }

        return squareImage;
    }


    private static RotateFlipType getRotateFlipType(int rotateValue)
    {
        RotateFlipType flipType = RotateFlipType.RotateNoneFlipNone;

        switch (rotateValue)
        {
            case 1:
                flipType = RotateFlipType.RotateNoneFlipNone;
                break;
            case 2:
                flipType = RotateFlipType.RotateNoneFlipX;
                break;
            case 3:
                flipType = RotateFlipType.Rotate180FlipNone;
                break;
            case 4:
                flipType = RotateFlipType.Rotate180FlipX;
                break;
            case 5:
                flipType = RotateFlipType.Rotate90FlipX;
                break;
            case 6:
                flipType = RotateFlipType.Rotate90FlipNone;
                break;
            case 7:
                flipType = RotateFlipType.Rotate270FlipX;
                break;
            case 8:
                flipType = RotateFlipType.Rotate270FlipNone;
                break;
            default:
                flipType = RotateFlipType.RotateNoneFlipNone;
                break;
        }

        return flipType;
    }
Community
  • 1
  • 1
VDWWD
  • 35,079
  • 22
  • 62
  • 79