NEWS

[C#] Tạo hình ảnh thumbnail hàng loạt so sánh sử dụng bất đồng bộ và Parallel Async

[C#] Tạo hình ảnh thumbnail hàng loạt so sánh sử dụng bất đồng bộ và Parallel Async
Đăng bởi: Thảo Meo - Lượt xem: 3745 13:58:07, 08/01/2020DEVEXPRESS   In bài viết

Xin chào các bạn, bài viết hôm nay mình sẽ hướng dẫn các bạn các chuyển đổi hàng loạt hình ảnh gốc (original) sang hình ảnh thumbnail sử dụng Parallel C#.

Ở bài viết này, ngoài cách chuyển đổi hình ảnh thumnail hàng loạt.

image_thumbnail_csharp

Mình còn muốn hướng dẫn cho các bạn thấy cách sử dụng Parallel để vận dụng tối đa sức mạnh của phần cứng CPU.

Các bạn có thể xem video ở dưới đây, để có thể thấy được sự khác biệt khi sử dụng Parallel và khi không sử dụng Parallel.

Video demo ứng dụng:

Trong bài viết này, mình sử dụng bất động bộ và có trả về phần trăm kết quả thực thi, các file đang thực thi.

Các bạn có thể xem code ở bên dưới, hoặc download project về để tham khảo.

Source code Parallel convert image origin to thumbnail C#:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Thumbnails
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_input_Click(object sender, EventArgs e)
        {
            var dlg = new FolderBrowserDialog();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                txt_input.Text = dlg.SelectedPath;
            }
        }

        private void btn_output_Click(object sender, EventArgs e)
        {
            var dlg = new FolderBrowserDialog();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                txt_output.Text = dlg.SelectedPath;
            }
        }


        int count = 0;
        public void DoProcessing(IProgress<int> progress, bool isParallel)
        {

            var filters = new String[] { "jpg", "jpeg", "png" };
            var files = GetFilesFrom(txt_input.Text, filters, true);
            string[] array = files;


            if (isParallel)
            {
                Parallel.For(0, array.Length, i =>
                {
                    var url = array[i];
                    int width = int.Parse(txtWidth.Text);
                    int height = int.Parse(txtHeight.Text);


                    object b = new object();

                    lock (b)
                    {
                        Image image = Image.FromFile(url);

                        string outputUrl = url.Replace(txt_input.Text, txt_output.Text);
                        using (Image thumb = image.GetThumbnailImage(width, height, () => false, IntPtr.Zero))
                        {
                            System.IO.FileInfo file = new System.IO.FileInfo(outputUrl);
                            file.Directory.Create();
                            thumb.Save(outputUrl);
                            image.Dispose();
                        }

                        if (progress != null)
                        {
                            Interlocked.Increment(ref count);
                            var percent = (count * 1.0 / array.Length) * 100;                           
                            Thread.Sleep(5);
                            lbl_file_processing.BeginInvoke(new Action(() => {
                                lbl_file_processing.Text = $"({count} / {array.Length})" + Path.GetFileName(url);
                            }));
                            progress.Report((int)percent);

                        }
                    }

                });
            }
            else
            {

                for (int i = 0; i < array.Length; i++)
                {
                    var url = array[i];
                    int width = int.Parse(txtWidth.Text);
                    int height = int.Parse(txtHeight.Text);


                    object b = new object();

                    lock (b)
                    {
                        Image image = Image.FromFile(url);

                        string outputUrl = url.Replace(txt_input.Text, txt_output.Text);
                        using (Image thumb = image.GetThumbnailImage(width, height, () => false, IntPtr.Zero))
                        {
                            System.IO.FileInfo file = new System.IO.FileInfo(outputUrl);
                            file.Directory.Create();
                            thumb.Save(outputUrl);
                            image.Dispose();
                        }

                        if (progress != null)
                        {
                            Interlocked.Increment(ref count);
                            var percent = (count * 1.0 / array.Length) * 100;
                            Thread.Sleep(5);
                            lbl_file_processing.BeginInvoke(new Action(() => {
                                lbl_file_processing.Text = $"({count} / {array.Length})" + Path.GetFileName( url);
                            }));
                            progress.Report((int)percent);

                        }
                    }

                }
            }
        }

        
        private async void btn_process_Click(object sender, EventArgs e)
        {
            count = 0;
            var progress = new Progress<int>(percent =>
            {
                progressBar1.Value = percent;
                lbl_percent.Text = percent + "%";

            });


            await Task.Run(() => DoProcessing(progress, chkParallel.Checked));

            lbl_file_processing.Text = "Done!";

        }

        public String[] GetFilesFrom(String searchFolder, String[] filters, bool isRecursive)
        {
            List<String> filesFound = new List<String>();
            var searchOption = isRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
            foreach (var filter in filters)
            {
                filesFound.AddRange(Directory.GetFiles(searchFolder, String.Format("*.{0}", filter), searchOption));
            }
            return filesFound.ToArray();
        }
       
    }
}

Thanks for watching!

 

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Tạo hình ảnh thumbnail hàng loạt so sánh sử dụng bất đồng bộ và Parallel Async
Đăng bởi: Thảo Meo - Lượt xem: 3745 13:58:07, 08/01/2020DEVEXPRESS   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.