Generally, in web applications, the images submitted by the client must be compressed. Especially for larger pictures, if not compressed, the page will become large and the opening speed will be slower. Of course, if high-quality pictures are required, thumbnails must be produced.
Below is a picture compression algorithm I have thought about myself. First of all, this is a simple implementation without optimization:
The code is as follows:
public static GetImageThumb( sourceImg, int width, int height) { targetImg = new (width, height); using ( g = (targetImg)) { = .; = .; = .; = .; = .; (sourceImg, new (0, 0, width, height), new (0, 0, , ), ); (); } return targetImg; }
This method is relatively simple and uses high-quality compression. After this method, the 200K picture can only be compressed to about 160k. After rewriting the code, the following method is implemented:
The code is as follows:
public Bitmap GetImageThumb(Bitmap mg, Size newSize) { double ratio = 0d; double myThumbWidth = 0d; double myThumbHeight = 0d; int x = 0; int y = 0; Bitmap bp; if (( / ()) > ( / ())) ratio = () / (); else ratio = () / (); myThumbHeight = ( / ratio); myThumbWidth = ( / ratio); Size thumbSize = new Size((int), (int)); bp = new Bitmap(, ); x = ( - ) / 2; y = ( - ); g = (bp); = ; = ; = ; Rectangle rect = new Rectangle(x, y, , ); (mg, rect, 0, 0, , , ); return bp; }
The compression achieved in this way greatly increases the compression rate. In fact, the code has not changed much. The most important thing is that if you use jpg format when saving, if you do not specify the format, the default is to use png format.
The following is a method of compressing pictures based on setting the image quality value:
The code is as follows:
public static bool GetPicThumbnail(string sFile, string outPath, int flag) { iSource = (sFile); ImageFormat tFormat = ; //The following code sets the compression quality when saving the picture. EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = flag;//Set the compression ratio 1-100 EncoderParameter eParam = new EncoderParameter(, qy); [0] = eParam; try { ImageCodecInfo[] arrayICI = (); ImageCodecInfo jpegICIinfo = null; for (int x = 0; x < ; x++) { if (arrayICI[x].("JPEG")) { jpegICIinfo = arrayICI[x]; break; } } if (jpegICIinfo != null) { (outPath, jpegICIinfo, ep);//dFile is the new path after compression } else { (outPath, tFormat); } return true; } catch { return false; } finally { (); (); } }
The above is the detailed content of how to achieve image compression in C#. For more information about C# image compression, please pay attention to my other related articles!