我想在.NET庫中使用ImageMagick COM對象(ImageMagickObject)。該庫旨在從IronRuby中調用,但這並不重要。我想採用這種方法,因爲它適合於我現有的調用,它將當前調用ImageMagick二進制文件作爲外部進程。 COM對象將採用與二進制文件相同的參數,但會保存進程創建,整體速度大約快5倍。重定向STDERR從.NET中的COM對象包裝器輸出
我唯一的障礙是COM對象的「比較」方法將其結果返回給STDERR。這對二進制文件來說也是一個問題,但很容易將它帶回到我期待的STDOUT中。使用COM對象,我得到了函數返回值的結果。
如何將「比較」結果重定向到字符串緩衝區或文件而不是STDERR?
我曾嘗試以下,這確實停止到達STDERR的輸出,但它不寫入預期文件:
using ImageMagickObject;
...
public class ImageMagickCOM
{
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern int SetStdHandle(int device, IntPtr handle);
private const int STDOUT_HANDLE = -11;
private const int STDERR_HANDLE = -12;
private ImageMagickObject.MagickImage magickImage = null;
private FileStream filestream = null;
private StreamWriter streamwriter = null;
public ImageMagickCOM()
{
IntPtr handle;
int status;
filestream = new FileStream("output.txt", FileMode.Create);
streamwriter = new StreamWriter(filestream);
streamwriter.AutoFlush = true;
//handle = filestream.Handle; // deprecated
handle = filestream.SafeFileHandle.DangerousGetHandle(); // replaces filestream.handle
status = SetStdHandle(STDOUT_HANDLE, handle);
status = SetStdHandle(STDERR_HANDLE, handle);
Console.SetOut(streamwriter);
Console.SetError(streamwriter);
magickImage = new ImageMagickObject.MagickImage();
}
public string Compare()
{
object[] args = new object[] { "-metric", "AE", "-fuzz", "10%", "imageA.jpg", "imageB.jpg", "diff.png" };
return (string)this.magickImage.Compare(ref args);
}
public void Close()
{
if (this.magickImage != null)
{
Marshal.ReleaseComObject(magickImage);
this.magickImage = null;
}
if (this.streamwriter != null)
{
this.streamwriter.Flush();
this.streamwriter.Close();
this.streamwriter = null;
this.filestream = null;
}
}
}
只有「比較」行爲似乎使用STDERR發送結果(它使用返回值作爲成功指示器)。所有其他方法(識別,轉換,Mogrify等)按照您的預期工作。
作爲參考,它被稱爲是這樣的(從IronRuby的):創建
require 'ImagingLib.dll'
im = ImagingLib::ImageMagickCOM.new
im.compare # returns nil
im.close
而且output.txt的,而空。沒有什麼打印到STDOUT或STDERR。
EDITS:爲了清晰有關Streamwriter刷新/關閉以及IronRuby如何使用示例。
我試過在調用Compose之前和之後顯式清空緩衝區,但沒有運氣。 – cgyDeveloper 2011-02-07 20:29:06