CSharp examples for System.Drawing.Imaging:Bitmap
Compress Image
using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Drawing; using System.IO;/*from w w w .j ava 2s . c om*/ using System.Collections; using System; public class Main{ public static void Compress(string srcFile, string destFile, long level) { // Create a Bitmap object based on a BMP file. Bitmap bm = new Bitmap(srcFile); Compress(bm, destFile, level); bm.Dispose(); } public static void Compress(Image srcImg, string destFile, long level) { Bitmap bm = new Bitmap(srcImg); Compress(bm, destFile, level); bm.Dispose(); } public static void Compress(Stream srcStream, string destFile, long level) { Bitmap bm = new Bitmap(srcStream); Compress(bm, destFile, level); bm.Dispose(); } public static void Compress(Bitmap srcBitMap, string destFile, long level) { Stream s = new FileStream(destFile, FileMode.Create); Compress(srcBitMap, s, level); s.Close(); } public static void Compress(Bitmap srcBitmap, Stream destStream, long level) { ImageCodecInfo myImageCodecInfo; Encoder myEncoder; EncoderParameter myEncoderParameter; EncoderParameters myEncoderParameters; myImageCodecInfo = GetEncoderInfo("image/jpeg"); myEncoder = Encoder.Quality; myEncoderParameters = new EncoderParameters(1); myEncoderParameter = new EncoderParameter(myEncoder, level); myEncoderParameters.Param[0] = myEncoderParameter; srcBitmap.Save(destStream, myImageCodecInfo, myEncoderParameters); } public bool Compress(string oldfile, string newfile) { try { Image img = Image.FromFile(oldfile); ImageFormat thisFormat = img.RawFormat; Size newSize = new Size(100, 125); Bitmap outBmp = new Bitmap(newSize.Width, newSize.Height); Graphics g = Graphics.FromImage(outBmp); g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel); g.Dispose(); EncoderParameters encoderParams = new EncoderParameters(); long[] quality = new long[1]; quality[0] = 100; EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); encoderParams.Param[0] = encoderParam; ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICI = null; for (int x = 0; x < arrayICI.Length; x++) if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICI = arrayICI[x]; break; } img.Dispose(); if (jpegICI != null) outBmp.Save(newfile, System.Drawing.Imaging.ImageFormat.Jpeg); outBmp.Dispose(); return true; } catch { return false; } } }