您现在的位置是:首页 >技术教程 >c# 无损压缩照片大小,并且设计了界面,添加了外部Ookii.Dialogs.dll,不一样的选择文件夹界面,并且可以把外部dll打包进exe中网站首页技术教程
c# 无损压缩照片大小,并且设计了界面,添加了外部Ookii.Dialogs.dll,不一样的选择文件夹界面,并且可以把外部dll打包进exe中
c# 无损压缩照片大小,并且设计了界面,添加了外部Ookii.Dialogs.dll,不一样的选择文件夹界面,并且可以把外部dll打包进exe中
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.WebRequestMethods;
using static System.Windows.Forms.AxHost;
namespace _23_无损压缩照片大小
{
public partial class Form1 : Form
{
public Form1()
{
DllClass.LoadResourceDll();//将dll加到exe需要加入这行代码
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path = textBox1.Text;
string path_bc = textBox2.Text;
ArrayList list_jpg = select_jpg(path);
//设置进度条的最小及最大值
progressBar1.Maximum = list_jpg.Count;
progressBar1.Minimum = 0;
int i = 0;
setPos(i);
foreach (string item in list_jpg)
{
string pPath = System.IO.Path.GetDirectoryName(item); //获取文件路径
string pName = System.IO.Path.GetFileName(item); //获取文件名
string path_jpg_bc = path_bc + “压缩后-” + pName;
//执行照片压缩
CompressImage(item, path_jpg_bc);
setPos(i);
i++;
}
setPos(i);
}
///
/// 根据文本框内容获取照片路径集合
///
/// 文本框路径
/// 照片集合
private static ArrayList select_jpg(string path)
{
ArrayList list_jpg = new ArrayList();
//判断是否是文件夹
if (Directory.Exists(path))
{
DirectoryInfo folder = new DirectoryInfo(path);
FileSystemInfo fileinfo1 = folder as FileSystemInfo;
list_jpg = selecte_jpg(fileinfo1);//获取文件夹下面所有的照片
}
else
{
//根据符号拆分照片路径
string[] result = path.Split(‘|’);
foreach (string item in result)
{
list_jpg.Add(item);//将路径添加到集合中
}
}
return list_jpg;
}
///
/// 提取文件夹下面所有的png
///
/// 文件夹路径
/// 所有png照片路径
private static ArrayList selecte_jpg(FileSystemInfo info)
{
DirectoryInfo dir = info as DirectoryInfo;
ArrayList listPics = new ArrayList();
FileSystemInfo[] files = dir.GetFileSystemInfos();
for (int i = 0; i < files.Length; i++)
{
FileInfo file = files[i] as FileInfo;
//是文件
if (file != null)
{
string extension = Path.GetExtension(file.Name);
if (extension.ToUpper() == “.PNG”)
{
listPics.Add(file.FullName);
}
else if (extension.ToUpper() == “.JPG”)
{
listPics.Add(file.FullName);
}
else if (extension.ToUpper() == “.ICO”)
{
listPics.Add(file.FullName);
}
}
else//对于子目录,进行递归调用
selecte_jpg(files[i]);
}
return listPics;
}
///
/// 无损压缩图片
///
/// 原图片地址
/// 压缩后保存图片地址
/// 压缩质量(数字越小压缩率越高)1-100
/// 压缩后图片的最大大小
/// 是否是第一次调用
///
public static bool CompressImage(string sFile, string dFile, int flag = 100, int size = 1000, bool sfsc = true)
{
Image iSource = Image.FromFile(sFile);
ImageFormat tFormat = iSource.RawFormat;
//如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
FileInfo firstFileInfo = new FileInfo(sFile);
if (sfsc == true && firstFileInfo.Length < size * 1024)
{
try { firstFileInfo.CopyTo(dFile); }
catch
{
System.IO.File.Delete(dFile);
firstFileInfo.CopyTo(dFile);
}
return true;
}
int dHeight = iSource.Height / 2;
int dWidth = iSource.Width / 2;
int sW = 0, sH = 0;
//按比例缩放
Size tem_size = new Size(iSource.Width, iSource.Height);
if (tem_size.Width > dHeight || tem_size.Width > dWidth)
{
if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
{
sW = dWidth;
sH = (dWidth * tem_size.Height) / tem_size.Width;
}
else
{
sH = dHeight;
sW = (tem_size.Width * dHeight) / tem_size.Height;
}
}
else
{
sW = tem_size.Width;
sH = tem_size.Height;
}
Bitmap ob = new Bitmap(dWidth, dHeight);
Graphics g = Graphics.FromImage(ob);
g.Clear(Color.WhiteSmoke);
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
g.Dispose();
//以下代码为保存图片时,设置压缩质量
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)
{
ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
FileInfo fi = new FileInfo(dFile);
if (fi.Length > 1024 * size)
{
flag = flag - 10;
CompressImage(sFile, dFile, flag, size, false);
}
}
else
{
ob.Save(dFile, tFormat);
}
return true;
}
catch
{
return false;
}
finally
{
iSource.Dispose();
ob.Dispose();
}
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = true;//该值确定是否可以选择多个文件
dialog.Title = "请选择电子文档excel";
dialog.Filter = "图片文件(*.jpg,*.png,*.ico)|*.jpg;*.png;*.ico";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
List<string> list = new List<string>();
//循环将多个文件添加到集合中
foreach (string file in dialog.FileNames)
{
list.Add(file);
}
string result = String.Join("|", list);
textBox1.Text = result.TrimEnd('|');
}
}
else
{
Ookii.Dialogs.VistaFolderBrowserDialog folderBrowser = new Ookii.Dialogs.VistaFolderBrowserDialog();
//folderBrowser.SelectedPath = @"D:";
//folderBrowser.Description = "请选择网页所在的目录";
folderBrowser.ShowNewFolderButton = true;
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
textBox1.Text = folderBrowser.SelectedPath;
}
}
}
private void button3_Click(object sender, EventArgs e)
{
Ookii.Dialogs.VistaFolderBrowserDialog folderBrowser = new Ookii.Dialogs.VistaFolderBrowserDialog();
//folderBrowser.SelectedPath = @"D:";
//folderBrowser.Description = "请选择网页所在的目录";
folderBrowser.ShowNewFolderButton = true;
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
textBox2.Text = folderBrowser.SelectedPath;
}
}
/// <summary>
/// 设置进度条
/// </summary>
/// <param name="value"></param>
private void setPos(int value) //设置进度条当前进度值
{
if (value < progressBar1.Maximum + 1) //如果值有效
{
progressBar1.Value = value; //设置进度值
}
Application.DoEvents();//重点,必须加上,否则父子窗体都假死
}
/// <summary>
/// 应用外部dll需要加上这个模块
/// </summary>
class DllClass
{
public static void LoadResourceDll()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
private static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string dllName = args.Name.Contains(",") ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll", "");
dllName = dllName.Replace(".", "_");
if (dllName.EndsWith("_resources")) return null;
string Namespace = Assembly.GetEntryAssembly().GetTypes()[0].Namespace;
System.Resources.ResourceManager rm = new System.Resources.ResourceManager(Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());
byte[] bytes = (byte[])rm.GetObject(dllName);
return System.Reflection.Assembly.Load(bytes);
}
}
}
}