本人一般也很少上傳照片之類的女生喜歡玩的東西,但是偶爾還是要傳一傳的,為什么?因為現在與各種以前的朋友同學都很少聯系,但是只要一發有個人照片的微博或日志便引來各種鮮花雞蛋。
周末和幾個同學去了西涌露營,這么美麗的海灘不上傳照片分享著實可惜,可是現在的相機拍出來的照片很大,特別是單反,而咱們的網絡帶寬又何其可憐,所以先壓縮再上傳會是非常好的選擇,可是呢這么多張照片一張張壓縮太麻煩了(鄙人對作圖是小白,不懂得使用做圖工具),而咱是碼農,碼農就要用碼農的方式,于是乎就想做個程序了。
好了廢話了那么多開工了。
第一次迭代開始,先完成單張相片壓縮的Demo。我始終堅信好的代碼是重構出來的,因而在這里我將使用迭代開發的思想逐步完成這個程序。先看下第一次迭代的代碼
Image img = Image.FromFile(sourcePath + sourceName);
int width = img.Width / scale;
int height = img.Height / scale;
Image imgNew = new Bitmap(width, height);
Graphics g = Graphics.FromImage(imgNew);
g.DrawImage(img, new System.Drawing.Rectangle(0, 0, width, height),
new System.Drawing.Rectangle(0, 0, img.Width, img.Height),
System.Drawing.GraphicsUnit.Pixel);
imgNew.Save(savePath + "a.jpg", ImageFormat.Jpeg);
}
第二次迭代,對其進行重構。
經過分析,該功能的實現需要兩步,第一獲取要縮小的圖片集合,第二就是縮小圖片的邏輯,故而就有了以下重構后的代碼
List<string> imageNames = GetImageNames(sourcePath);
if (imageNames != null && imageNames.Count > 0)
{
foreach (var item in imageNames)
{
SaveSmallPhoto(sourcePath + item, scale, savePath + item);
}
}
}
/// <summary>
/// 獲取路徑下所有符合指定圖片后綴文件名
/// </summary>
/// <param name="path">路徑</param>
/// <returns></returns>
static List<string> GetImageNames(string path)
{
string[] fileNames = Directory.GetFiles(path);
if (fileNames == null || fileNames.Length == 0)
{
return null;
}
List<string> imageNames = new List<string>();
foreach (var item in fileNames)
{
if (ExistsInExtName(item, IMAGE_EXTNAME))
{
imageNames.Add(item.Substring(item.LastIndexOf('//') + 1));
}
}
return imageNames;
}
/// <summary>
/// 判斷文件名是否符合指定后綴名
/// </summary>
/// <param name="name">文件名</param>
/// <param name="extNames">符合要求的后綴名</param>
/// <returns></returns>
static bool ExistsInExtName(string name, string[] extNames)
{
if (string.IsNullOrEmpty(name) || extNames == null || extNames.Length == 0)
{
return false;
}
foreach (var item in extNames)
{
if (name.ToLower().EndsWith(item))
{
return true;
}
}
return false;
}
/// <summary>
/// 將圖片按比例縮小保存
/// </summary>
/// <param name="fromPath">原圖片路徑名</param>
/// <param name="scale">縮小比例</param>
/// <param name="toPath">縮小后保存的路徑名</param>
static void SaveSmallPhoto(string fromPath, int scale, string toPath)
{
int width, height;
using (Image img = Image.FromFile(fromPath))
{
width = img.Width / scale;
height = img.Height / scale;
using (Image imgNew = new Bitmap(width, height))
{
using (Graphics g = Graphics.FromImage(imgNew))
{
g.DrawImage(img, new Rectangle(0, 0, width, height),
new Rectangle(0, 0, img.Width, img.Height), System.Drawing.GraphicsUnit.Pixel);
}
imgNew.Save(toPath, ImageFormat.Jpeg);
}
}
}
}
完了之后,大家有更好的關于壓縮照片的辦法不妨拿出來分享下!
新聞熱點
疑難解答