2014-02-21 86 views
0

我从本地图像文件创建一个位图图像覆盖另一个位图,但是当指定文件URI时,我得到一个System.UriFormatException,我不能理解,因为该图像存储在项目中名为图像的文件夹中似乎是正确的。这是我如何指定URI new Uri("Images/boxbag.png")。有人可以解释为什么我得到这种格式异常,是文件路径问题还是我设置URI的方式。如何将URI路径添加到位图图像?

这是下面这应该澄清事情的完整方法更多:

void myKinect_ColorFrameReady(object sender, ColorImageFrameReadyEventArgs e) { 
    using (ColorImageFrame colorFrame = e.OpenColorImageFrame()) { 
     if (colorFrame == null) return; 
     byte[] colorData = new byte[colorFrame.PixelDataLength]; 
     colorFrame.CopyPixelDataTo(colorData); 

     KinectVideo.Source = BitmapSource.Create(colorFrame.Width, colorFrame.Height, 96, 96, 
      PixelFormats.Bgr32, null, colorData, colorFrame.Width * colorFrame.BytesPerPixel); 

     //drawing image overlay to video feed 
     var drawingVisual = new DrawingVisual(); 
     var drawingContext = drawingVisual.RenderOpen(); 
     drawingContext.DrawImage(BitmapSource.Create(colorFrame.Width, colorFrame.Height, 96, 96, PixelFormats.Bgr32, null, colorData, colorFrame.Width * colorFrame.BytesPerPixel), 
      new Rect(new Size(colorFrame.Width, colorFrame.Height))); 
     var overlayImage = new BitmapImage(new Uri("Images/boxbag.png")); 
     drawingContext.DrawImage(overlayImage, new Rect(12, 12, overlayImage.Width, overlayImage.Height)); 
     drawingContext.Close(); 
     var mergedImage = new RenderTargetBitmap(colorFrame.Width, colorFrame.Height, 96, 96, PixelFormats.Pbgra32); 
     mergedImage.Render(drawingVisual); 

     KinectVideo.Source = mergedImage; 
    } 
} 

回答

1

根据http://msdn.microsoft.com/en-us/library/z6c2z492%28v=vs.110%29.aspx

此构造假定字符串参数引用了 绝对URI,相当于调用Uri构造函数与 UriKind设置为Absolute。如果传递给构造函数 的字符串参数是相对URI,则此构造函数将抛出一个 UriFormatException。

首先,尝试使用绝对路径来查看是否一切正常工作。

如果有效,您可以尝试查找应用程序路径,例如在System.AppDomain.CurrentDomain.BaseDirectory的帮助下,使用应用程序路径和从应用程序路径到图像的相对路径构建图像的绝对路径。

类似以下内容:

string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; 
string imageRelativePath = "..."; 
string imagePath = Path.Combine(baseDirectory, imageRelativePath); 
+0

你能举一个这样的代码示例吗? –

+0

@BrianJ我又添了一句话。这个版本的构造函数假定绝对URI。 – AlexD

+0

好吧我现在明白了,默认的URI是绝对的,这就是为什么它将一个相对URI作为参数抛出一个错误。 –

1
new Uri("Images/boxbag.png", UriKind.Relative) 

否则URI视为绝对的,并且必须包括计划。

+0

正确,但可能会导致另一个问题。也许路径将相对于可执行文件的目录而不是项目目录。从问题中:“*图像存储在项目*中名为Images的文件夹中”。 – AlexD

相关问题