Compress picture size to below specified KB

Source: Internet
Author: User

such as PS,QQ images have this feature, compress the image size below the specified KB.

I also come to the cottage, so far, to control the size of the picture, the usual solution through the resolution and quality control.

Assuming that the size of the last compression is 100kb, then the picture quality is as high as possible without a guarantee of greater than 100KB. the higher the image quality, the larger the image occupies . But the size and quality of the relationship, there is no fixed formula, such as Y= NX, and I have tried to win7 system picture collection of pictures, each saved 10 times, from the quality of 10, up to 100, found that only before the conclusion, the picture quality is high, occupies a large size.

In this case, you can only find the most suitable quality parameters that meet the 1OOKB size. The two-point method is used here to find.

        <summary>///compress pictures to less than n KB///</summary>//<param name= "img" > Picture </p aram>//<param name= "format" > Picture format </param>//<param name= "Targetlen" > Compressed size </param >//<param name= "Srclen" > Original size </param>//<returns> compressed picture memory stream </returns> p Ublic static MemoryStream Zip (Image img, imageformat format, long targetlen, long Srclen = 0) {//Set allowable size            Deviation amplitude Default 10kb const long Nearlylen = 10240;            Returns memory Stream read var ms = new MemoryStream () using a memory stream if the parameter is not passed in the chart size; if (0 = = Srclen) {img.                Save (MS, format); Srclen = Ms.            Length;            }//unit converted from KB to byte if the target size is higher than the original size, the conditional exit Targetlen *= 1024 is satisfied; if (Targetlen >= srclen) {Ms.                SetLength (0); Ms.                Position = 0; Img.                Save (MS, format); Return Ms            }//Gets the target size of the lowest value var exitlen = Targetlen-nearlylen;            Initialize mass compression parameters image Memory Stream var quality = (long) math.floor (100.00 * targetlen/srclen);            var parms = new EncoderParameters (1);            Gets the encoder information imagecodecinfo formatinfo = null;            var encoders = Imagecodecinfo.getimageencoders (); foreach (ImageCodecInfo ICF in encoders) {if (ICF. FormatID = = format.                    Guid) {formatinfo = ICF;                Break            }}//Use the binary method to find the nearest quality parameter long startquality = quality;            Long endquality = 100;            Quality = (startquality + endquality)/2; while (true) {//sets the quality parms.                Param[0] = new Encoderparameter (System.Drawing.Imaging.Encoder.Quality, quality); Empty the memory stream and save the picture Ms.                SetLength (0); Ms. Position = 0; Img.                Save (MS, FormatInfo, parms); If the size of the compression is lower than the target size, the conditional exit if (MS) is satisfied. Length >= Exitlen && Ms.                Length <= Targetlen) {break;                } else if (startquality >= endquality)//interval is equal without recalculation of {break; } else if (Ms.                Length < Exitlen)//compression too small, starting mass right shift {startquality = quality;                } else//compression too large terminating mass left {endquality = quality; }//Reset the quality parameter if the calculated quality has not changed, the lookup is terminated.                 This is to avoid duplication of calculations {start:16,end:18} and {start:16,endquality:17} var newquality = (startquality + endquality)/2;                if (newquality = = quality) {break;                } quality = newquality; Console.WriteLine ("Start:{0} End:{1} current:{2}", Startquality,endquality, quality);        } return MS;  }

During the testing process, it was found that the processing time of each figure was almost 1s. Complete the requirements, but there is no problem, but always feel that there should be a more appropriate solution, if there are friends who know, welcome to provide Cicada to discuss together!

Compress picture size to below specified KB

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.