- [TOOL] Chia sẻ phần mềm thay đổi thông tin cấu hình máy tính
- [C#] Hướng dẫn Export dữ liệu ra file Microsoft Word Template
- [C#] Chia sẻ source code tool kiểm tra domain website
- [C#] Hướng dẫn tạo file PDF sử dụng thư viện QuestPDF
- [C#] Hướng dẫn tạo ứng dụng dock windows giống Taskbar
- [C#] Chia sẻ source code sử dụng Object Listview trên Winform
- [VB.NET] Chia sẻ source code quản lý thu chi mô hình 3 lớp Winform
- [DATABASE] Xóa lịch sử danh sách đăng nhập tài khoản trên SMSS Sqlserver Management Studio
- [C#] Sử dụng FolderBrowserDialog Vista trên Winform
- [DEVEXPRESS] Chia sẻ tool Winform UI Templates Early Access Preview (EAP)
- [C#] Chia sẻ source code Spin Content (Trộn nội dung văn bản theo từ đồng nghĩa) trên Winform
- [VB.NET] Chia sẻ source code lịch âm dương và hẹn lịch nhắc việc
- [C#] Hướng dẫn đọc thông số thiết bị Thiết bị kiểm tra Pin (HIOKI BATTERY HiTESTER BT3562)
- [VB.NET] Hướng dẫn giải captcha sử dụng dịch vụ AZCaptcha API trên winform
- [C#] Hướng dẫn chứng thực đăng nhập ứng dụng bằng vân tay (Finger Print) trên máy tính
- [C#] Color Thief cách xuất màu sắc thiết kế từ hình ảnh
- [C#] Cách tạo bản quyền và cho phép dùng thử ứng dụng Winform
- [C#] Hướng dẫn sử dụng trình duyệt web Chrome convert HTML sang tập tin file PDF
- [C#] Kết nôi điện thoại Android, IOS với App Winform via Bluetooth
- [DATABASE] Cách query cộng trừ dồn dần trong Sqlserver
[C#] Tạo hình ảnh thumbnail hàng loạt so sánh sử dụng bất đồng bộ và Parallel Async
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.
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!