private void btnCompress_Click(object sender, EventArgs e) { try { ImageFile imageFile = new ImageFile(); string destFile = string.Empty; string[] fileList = { }; int counter = 0; long quality = GetCompressQuality(); int width, height; Int32.TryParse(txtWidth.Text, out width); Int32.TryParse(txtHeight.Text, out height); if (Directory.Exists(txtCompressSource.Text)) { fileList = Directory.GetFiles(txtCompressSource.Text); } for (int i = 0; i < fileList.Length; i++) { if (fileList[i].ToLower().Contains(".jpg") || fileList[i].ToLower().Contains(".png")) { destFile = fileList[i].Replace(txtCompressSource.Text, txtCompressDest.Text); imageFile.CompressImage(fileList[i], destFile, width, height, quality); counter++; } } MessageBox.Show(string.Format("处理成功,共{0}张!", counter), "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show("压缩失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); txtMessage.Text = ex.Message; } }
public void TestImage() { string strSrc = @"E:\Test\Files\1.JPG"; string strDest = @"E:\Test\Files\3.JPG"; ImageFile imgFile = new ImageFile(); imgFile.CompressImage(strSrc, strDest, 720, 480); }
/// <summary> /// 压缩图片,分辨率取用户选择的,质量为100L /// </summary> /// <param name="source"></param> /// <param name="dest"></param> private void CompressImage(string source, string dest) { int[] resolution = GetResolution(); long quality = 100L; //图片的质量 //必须每次都生成ImageFile对象,否则同一对象调用CompressImage次数太多会造成内存不足 ImageFile imgFile = new ImageFile(); imgFile.CompressImage(source, dest, resolution[0], resolution[1], quality); }