How to compress jpg image?

前端 未结 2 1810
别跟我提以往
别跟我提以往 2021-01-06 06:14

I have jpg image format with size of 3300K.

I try to compress the image => so i changed the image size but still i have very big size of the file ( ~ 800K )

2条回答
  •  太阳男子
    2021-01-06 06:47

    mg = image

    newsize = height and width

    Call Resize function using following code

    Bitmap mg = new Bitmap(strUploadPath);
    Size newSize = new Size(Convert.ToInt32(DispMaxWidth), Convert.ToInt32(DispMaxHeight));
    Bitmap bp = ResizeImage(mg, newSize);
    if (bp != null)
    bp.Save(strUploadPath, System.Drawing.Imaging.ImageFormat.Jpeg);
    
    private Bitmap ResizeImage(Bitmap mg, Size newSize)
            {
                double ratio = 0d;
                double myThumbWidth = 0d;
                double myThumbHeight = 0d;
                int x = 0;
                int y = 0;
    
                Bitmap bp;
    
                if ((mg.Width / Convert.ToDouble(newSize.Width)) > (mg.Height /
                Convert.ToDouble(newSize.Height)))
                    ratio = Convert.ToDouble(mg.Width) / Convert.ToDouble(newSize.Width);
                else
                    ratio = Convert.ToDouble(mg.Height) / Convert.ToDouble(newSize.Height);
                myThumbHeight = Math.Ceiling(mg.Height / ratio);
                myThumbWidth = Math.Ceiling(mg.Width / ratio);
    
                //Size thumbSize = new Size((int)myThumbWidth, (int)myThumbHeight);
                Size thumbSize = new Size((int)newSize.Width, (int)newSize.Height);
                bp = new Bitmap(newSize.Width, newSize.Height);
                x = (newSize.Width - thumbSize.Width) / 2;
                y = (newSize.Height - thumbSize.Height);
                // Had to add System.Drawing class in front of Graphics ---
                System.Drawing.Graphics g = Graphics.FromImage(bp);
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                Rectangle rect = new Rectangle(x, y, thumbSize.Width, thumbSize.Height);
                g.DrawImage(mg, rect, 0, 0, mg.Width, mg.Height, GraphicsUnit.Pixel);
    
                return bp;
    
            }
    

提交回复
热议问题