private void Start_Click(object sender, RoutedEventArgs e)
{
if (listView.Items.Count > 0)
worker.RunWorkerAsync();
}
在DoWork中,我调整图像文件数量并将其保存到硬盘,并报告百分比和图像数量。在ProgressChanged事件中,我更新了progressBar和一些标签。
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < directories.Count; i++)
{
BitmapImage imagetosave = ResizeImage(directories[i]);
Save(imagetosave, saveDirectory);
int percents = ((i + 1) * 100) / directories.Count;
worker.ReportProgress(percents, i);
}
}
private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label.Content = e.ProgressPercentage.ToString() + "%";
label2.Content = e.UserState;
}
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
我想要做的是每次调整图像大小然后保存到硬盘时,将listView中的项目文本更改为&#34; Resized and saved&#34;甚至可以为项目着色,例如绿色。
这是我调整图像大小并保存它们的方法:
public void Save(BitmapImage image, string filePath)
{
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
{
encoder.Save(fileStream);
}
}
private BitmapImage ResizeImage(string file)
{
var bitmap = new BitmapImage();
var stream = File.OpenRead(file);
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.DecodePixelHeight = 100;
bitmap.DecodePixelWidth = 100;
bitmap.EndInit();
stream.Close();
stream.Dispose();
return bitmap;
}
答案 0 :(得分:0)
当你的后台工作人员完成后,你回到UI线程并运行它:
Dispatcher.Invoke(DispatcherPriority.Normal, new RefreshCallback(Refresh));
RefreshCallback
是Refresh
函数的简单代理,用于更新列表项。