C# TiffBitmapEncoder:使位图编码异步
问题:如何相对于主线程异步保存/压缩位图图像(其中多个堆叠在C# TiffBitmapEncoder:使位图编码异步,c#,multithreading,backgroundworker,bitmapencoder,C#,Multithreading,Backgroundworker,Bitmapencoder,问题:如何相对于主线程异步保存/压缩位图图像(其中多个堆叠在tiff文件中) 我的设置:(同步和慢速工作解决方案:当执行压缩时,线程会停留几秒钟。我负担不起) 您必须将整个TIFF操作放入后台工作程序。然后将输入图像的副本作为参数传递给RunWorkerAsync。这里有一个链接,指向web上提供的许多解决方案中的一个,介绍了如何执行此操作:。将该代码放入助手方法中,并在将图像保存到磁盘之前使用它复制图像。我不是计算机科学家,但我发现,其中说明: WriteableBitmap继承Dispatc
tiff
文件中)
我的设置:(同步和慢速工作解决方案:当执行压缩时,线程会停留几秒钟。我负担不起)
您必须将整个TIFF操作放入后台工作程序。然后将输入图像的副本作为参数传递给
RunWorkerAsync
。这里有一个链接,指向web上提供的许多解决方案中的一个,介绍了如何执行此操作:。将该代码放入助手方法中,并在将图像保存到磁盘之前使用它复制图像。我不是计算机科学家,但我发现,其中说明:
WriteableBitmap继承DispatcherObject,并且只能在拥有它的dispatcher线程内访问它
而且,在我看来,您正在超出DispatcherObject的权限 关键是
TiffBitmapEncoder
/WriteableBitmap
需要在它将在其中使用的同一个线程中创建,并且可能需要冻结或复制colorBitmap
。@user7116我想我现在是这样实现的,但是现在我如何在线程之间深度复制colorBitmap
,我真的办不到。你能再详细一点吗?我调整了答案,加入了一个关于如何深度复制图片的链接。我也有同样的问题。
...in the body of a window class
private void afunction(){
//called with a given frequency and updating this.colorBitmap
...
this.colorBitmap = something;
savePictureStackTiff();
}
private int stack_pict_count = 0;
private int PICT_PER_FILE = 45;
private TiffBitmapEncoder encoder;
private string savePictureStackTiff()
{
initializeTiffEncoder();
//make a local copy of the image I want to put in the tiff binder
WriteableBitmap localCopy = new WriteableBitmap(this.colorBitmap);
encoder.Frames.Add(BitmapFrame.Create(localCopy));
stack_pict_count++;
if (stack_pict_count % PICT_PER_FILE == 0)
//Once I have enough files stacked I ask for compression
{
stack_pict_count = 0;
pict_metadata = "";
try
{
using (FileStream fs = new FileStream(path, FileMode.Create))
{
encoder.Save(fs); //<<<== LINE WHICH I'D LIKE TO BE RUN ASYNC
}
}
catch (IOException)
{}
}
}
private void initializeTiffEncoder()
{
if (stack_pict_count == 0)
{
encoder = new TiffBitmapEncoder();
encoder.Compression = TiffCompressOption.Zip;
}
}
tiffCompressorWorker = new BackgroundWorker();
tiffCompressorWorker.DoWork += (s, a) =>
{
initializeTiffEncoder();
WriteableBitmap localCopy = new WriteableBitmap((WriteableBitmap)a.Argument);
localCopy.Freeze();
encoder.Frames.Add(BitmapFrame.Create(localCopy));
stack_pict_count++;
if (stack_pict_count % PICT_PER_FILE == 0)
{
stack_pict_count = 0;
try
{
using (FileStream fs = new FileStream(path, FileMode.Create))
{
saving_encoder.Save(fs);
}
}
catch (IOException)
{
..
}
}
};