转:http://www.cnblogs.com/lifeil/archive/2013/02/25/2931683.html
public static bool GetPicThumbnail(string sFile, string outPath, int flag) { System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile); ImageFormat tFormat = iSource.RawFormat; //以下代码为保存图片时,设置压缩质量 EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = flag;//设置压缩的比例1-100 EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); ep.Param[0] = eParam; try { ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICIinfo = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICIinfo = arrayICI[x]; break; } } if (jpegICIinfo != null) { iSource.Save(outPath, jpegICIinfo, ep);//dFile是压缩后的新路径 } else { iSource.Save(outPath, tFormat); } return true; } catch { return false; } finally { iSource.Dispose(); iSource.Dispose(); } }
下面是一个服务器上图片自动压缩工具。
private void button1_Click(object sender, EventArgs e) { if (isStart) { MessageBox.Show("已经开启!"); return; } isStart = true; Thread thread = new Thread(new ParameterizedThreadStart(jj)); thread.Start(cbDisk.Text); }
public void jj(object disk) { while (true) { Thread.Sleep(10000); //获取检测盘符 //获取当天的时间,做个延迟十分钟切换压缩目录 string date = string.Format("{0:yyyyMMdd}", DateTime.Now.AddMinutes(-10)); //当天的目录 string datePath = disk + @"\" + date; //获取目录下面的所有图片文件 string[] pictures = DirFile.GetFileNames(datePath, "*.JPG", true); foreach (var path in pictures) { FileInfo fileInfo = new FileInfo(path); long size = fileInfo.Length; if (size / 1024 > 400)//大于400K就进行压缩 { string fileName = fileInfo.Name; try { GetPicThumbnail(path, datePath + @"\" + fileName, 10); //删除原始图片 File.Delete(path); //移动 File.Move(datePath + @"\" + fileName, path); } catch { } } } } }
服务器图片