Trong bài viết này các bạn sẽ được học cách làm thế nào tạo một ứng dụng nhỏ có ích - một ứng dụng có thể lấy mọi ảnh JPEG trong một thư mục và thay đổi chất lượng ảnh theo tỷ lệ mong muốn, và đương nhiên giảm được cả kích thước của file JPEG. Vì vậy...
Trong bài viết này các bạn sẽ được học cách làm thế nào tạo một ứng dụng nhỏ có ích - một ứng dụng có thể lấy mọi ảnh JPEG trong một thư mục và thay đổi chất lượng ảnh theo tỷ lệ mong muốn, và đương nhiên giảm được cả kích thước của file JPEG. Vì vậy, ngoài việc sử dụng một trình giải mã để giảm chất lượng của hình ảnh, bạn cũng sẽ được học cách quét tất cả các ảnh trong một thư mục theo một định dạng nào đó, và đưa nó vào trong ListBox.
Thiết kế ứng dụng:
Khởi động Visual Studio 2005 và bắt đầu tạo ra một ứng dụng Window C#. Trên đó ta vẽ hai nút - btnOpen và btnReduce - chúng sẽ được sử dụng để chọn thư mục mà bạn muốn tìm các ảnh để chỉnh sửa, và một thư mục để các ảnh chỉnh sửa sẽ được lưu vào. Điều khiển lớn nhất trên form này là điều khiển ListBox có tên là lstPhotos, nó hiển thị danh sách nơi lưu trữ các file được giảm chất lượng sẽ được lưu. Tiếp đến có một điều khiển NumericUpDown tên numQual với giá trị nằm trong khoảng 1 - 100 - sẽ xác định chất lượng mà người dùng muốn giảm. Cuối cùng phần tử prgReduce - một ProgressBar sẽ hiển thị thông tin tiến trình thay đổi tất cả các file ở trên. Bạn sẽ thấy rằng thanh tiến trình này sẽ làm việc khác chính xác, mặc dầu chúng ta không dùng đến một thread tách biệt trong mã giảm chất lượng ảnh.
Ngoài ra, ở đây chúng ta còn cần đến 2 hộp thoại được phát sinh ra khi nhấn vào nút btnOpen và btnReduce. Chúng cho phép người dùng lựa chọn thư mục mà họ muốn các file được lấy ra và nơi những file mới được đưa vào. Hai hộp thoại của chúng ta là FolderBrowserDialog và được đặt tên như sau:
Viết mã ứng dụng:
Vì chúng ta làm việc với các file đồ họa và các thư mục, chúng ta sẽ sử dụng đến các câu lệnh using sau:
view plainprint?
1. using System.IO;
2. using System.Drawing.Imaging;
using System.IO; using System.Drawing.Imaging;
Mã nguồn của chúng ta được chia tành hai phần:
phần quét thư mục là nơi chúng ta định lấy ảnh ra, và phần xử lý giảm chất lượng ảnh rồi ghi lại.
Phần thứ nhất được nằm trong sự kiện click vào nút btnOpen:
view plainprint?
1. private void btnOpen_Click(object sender, EventArgs e)
2. {
3. if (fbdOpen.ShowDialog() == DialogResult.OK)
4. {
5. // Clear any previous items in the list
6. lstPhotos.Items.Clear();
7. // Run a loop through all the files in the directory at the selected path
8. foreach(string Filename in Directory.GetFiles(fbdOpen.SelectedPath))
9. {
10. // We'll create a new FileInfo object from the file path
11. FileInfo fiPicture = new FileInfo(Filename);
12. // If it's a JPEG file
13. if (fiPicture.Extension.ToLower() == ".jpeg" || fiPicture.Extension.ToLower() == ".jpg")
14. {
15. // Add it to the list of files
16. lstPhotos.Items.Add(Filename);
17. }
18. }
19. }
20. // We want the ProgressBar to have the same maximum value as the number of pictures to resize
21. prgReduce.Maximum = lstPhotos.Items.Count;
22. }
private void btnOpen_Click(object sender, EventArgs e) { if (fbdOpen.ShowDialog() == DialogResult.OK) { // Clear any previous items in the list lstPhotos.Items.Clear(); // Run a loop through all the files in the directory at the selected path foreach(string Filename in Directory.GetFiles(fbdOpen.SelectedPath)) { // We'll create a new FileInfo object from the file path FileInfo fiPicture = new FileInfo(Filename); // If it's a JPEG file if (fiPicture.Extension.ToLower() == ".jpeg" || fiPicture.Extension.ToLower() == ".jpg") { // Add it to the list of files lstPhotos.Items.Add(Filename); } } } // We want the ProgressBar to have the same maximum value as the number of pictures to resize prgReduce.Maximum = lstPhotos.Items.Count; }
Với việc chú giải, đoạn mã khá dễ dàng có thể hiểu được làm điều gì. Tất cả điều chúng ta làm là lặp qua các file trong thư mục, nếu như chúng có phần mở rộng là jpeg/jpg thì chúng ta sẽ đưa nó vào danh sách.
Hãy xem sự kiện click vào nút btnReduce, nơi có chứa phần mã thứ hai của chúng ta viết, và có một đoạn nhỏ rất thật thú vị là đoạn mã viết để làm giảm chất lượng ảnh:
view plainprint?
1. private void btnReduce_Click(object sender, EventArgs e)
2. {
3. // Reset the progress bar
4. prgReduce.Value = 0;
5. // Show the FolderBrowserDialog where the user selects where to save the files
6. if (fbdSave.ShowDialog() == DialogResult.OK)
7. {
8. // We will store the correct image codec in this object
9. ImageCodecInfo iciJpegCodec = null;
10. // This will specify the image quality to the encoder
11. EncoderParameter epQuality = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (int)numQual.Value);
12. // Get all image codecs that are available
13. ImageCodecInfo[] iciCodecs = ImageCodecInfo.GetImageEncoders();
14. // Store the quality parameter in the list of encoder parameters
15. EncoderParameters epParameters = new EncoderParameters(1);
16. epParameters.Param[0] = epQuality;
17. // Loop through all the image codecs
18. for (int i = 0; i < iciCodecs.Length; i++)
19. {
20. // Until the one that we are interested in is found, which is image/jpeg
21. if (iciCodecs<img src="http://hp-aptech.edu.vn/emoticons/emotion-55.gif" alt="Idea" />.MimeType == "image/jpeg")
22. {
23. iciJpegCodec = iciCodecs<img src="http://hp-aptech.edu.vn/emoticons/emotion-55.gif" alt="Idea" />;
24. break;
25. }
26. }
27. // Loop through the files in the list
28. foreach (string strFile in lstPhotos.Items)
29. {
30. // Take another step on the progress bar
31. prgReduce.PerformStep();
32. // Create a new Image object from the current file
33. Image newImage = Image.FromFile(strFile);
34. // Get the file information again, this time we want to find out the extension
35. FileInfo fiPicture = new FileInfo(strFile);
36. // Save the new file at the selected path with the specified encoder parameters, and reuse the same file name
37. newImage.Save(fbdSave.SelectedPath + "\\" + fiPicture.Name, iciJpegCodec, epParameters);
38. }
39. }
40. // Open the folder containing the new items
41. System.Diagnostics.Process.Start(fbdSave.SelectedPath.ToString());
42. }
private void btnReduce_Click(object sender, EventArgs e) { // Reset the progress bar prgReduce.Value = 0; // Show the FolderBrowserDialog where the user selects where to save the files if (fbdSave.ShowDialog() == DialogResult.OK) { // We will store the correct image codec in this object ImageCodecInfo iciJpegCodec = null; // This will specify the image quality to the encoder EncoderParameter epQuality = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (int)numQual.Value); // Get all image codecs that are available ImageCodecInfo[] iciCodecs = ImageCodecInfo.GetImageEncoders(); // Store the quality parameter in the list of encoder parameters EncoderParameters epParameters = new EncoderParameters(1); epParameters.Param[0] = epQuality; // Loop through all the image codecs for (int i = 0; i < iciCodecs.Length; i++) { // Until the one that we are interested in is found, which is image/jpeg if (iciCodecs<img src="http://hp-aptech.edu.vn/emoticons/emotion-55.gif" alt="Idea" />.MimeType == "image/jpeg") { iciJpegCodec = iciCodecs<img src="http://hp-aptech.edu.vn/emoticons/emotion-55.gif" alt="Idea" />; break; } } // Loop through the files in the list foreach (string strFile in lstPhotos.Items) { // Take another step on the progress bar prgReduce.PerformStep(); // Create a new Image object from the current file Image newImage = Image.FromFile(strFile); // Get the file information again, this time we want to find out the extension FileInfo fiPicture = new FileInfo(strFile); // Save the new file at the selected path with the specified encoder parameters, and reuse the same file name newImage.Save(fbdSave.SelectedPath + "\\" + fiPicture.Name, iciJpegCodec, epParameters); } } // Open the folder containing the new items System.Diagnostics.Process.Start(fbdSave.SelectedPath.ToString()); }
Những gì mà đoạn code này làm là lấy ra codec của các file JPEG; chúng ta sẽ cần đến nó để thay đổi chất lượng file ảnh. Mã nguồn có thể cải tiến đôi chút nếu để nó vào lớp tách biệt và thread khác. Điều đó sẽ giúp cho thanh progress làm việc trơ tru hơn.
Biên dịch ứng dụng và chạy nó. Bạn sẽ nhận được kết quả như sau.