在WPF中加载和合并两个图像

时间:2011-05-17 10:09:02

标签: wpf image merge bitmap drawing

我尝试编写一个应用程序,从WPF中加载的jpeg创建水印图像。 我想在WPF中加载一个jpeg图像,并用一个透明区域的预定义png绘制它。 我试图创建两个图像作为RenderTargetBitmap,然后创建一个新的RenderTargetBitmap,如

Image LoadSource(string file) {
  var image = new Image();
  var src = new BitmapImage(); 
  src.BeginInit(); 
  src.UriSource = new Uri(file, UriKind.Absolute);
  src.CacheOption = BitmapCacheOption.OnLoad;
  src.EndInit();
  image.Source = src;
  image.Stretch = Stretch.Uniform;
  image.Width = 1024;
  image.Height = 768;
  return image;
}

private void Window_Loaded(object sender, RoutedEventArgs e) {
  var imgA = LoadSource(@"D:\test\1.jpg");
  var imgB = LoadSource(@"D:\test\2.png");
  var bmp = new RenderTargetBitmap(1024, 768, 120, 96, PixelFormats.Pbgra32);
  bmp.Render(imgA);
  bmp.Render(imgB);
  ResultImage.Source = bmp;
}

但它不起作用。

有人能指出我的解决方案吗?

1 个答案:

答案 0 :(得分:2)

我有一个更简单的解决方案:

XAML:

<DockPanel>
    <Button DockPanel.Dock="Bottom" HorizontalAlignment="Right" 
            Margin="12" Click="ButtonSave_OnClick" Content="_Save" />
    <Grid Name="MergedImage" Width="1024" Height="768" 
            HorizontalAlignment="Center" VerticalAlignment="Center" 
            AllowDrop="True" DragOver="MergedImage_DragEnter" 
            Drop="MergedImage_Drop">
        <Image Name="SourcePicture"/>
        <Image Source="Watermark.png"/>
    </Grid>
</DockPanel>

代码背后:

void ButtonSave_OnClick(object sender, RoutedEventArgs e)
{
    var dialog = new Microsoft.Win32.SaveFileDialog 
    { 
        DefaultExt = ".jpg", 
        Filter = "Image (.jpg)|*.jpg" 
    };

    if (dialog.ShowDialog() == true)
    {
        // Save my merged image as jpeg.
        // SaveAsJpeg(MergedImage, dialog.FileName);
    }
}

private void MergedImage_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        var fileNames = (string[])e.Data.GetData(DataFormats.FileDrop, true);
        if (fileNames.Length == 1)
        {
            var file = new FileInfo(fileNames[0]);
            if (file.Extension.ToLower() == ".png" ||
                file.Extension.ToLower() == ".bmp" ||
                file.Extension.ToLower() == ".jpg" ||
                file.Extension.ToLower() == ".jpeg" ||
                file.Extension.ToLower() == ".gif")
            {
                e.Effects = DragDropEffects.Copy;
                e.Handled = true;
                return;
            }
        }
    }
    e.Effects = DragDropEffects.None;
    e.Handled = true;
}

private void MergedImage_Drop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        var fileNames = (string[])e.Data.GetData(DataFormats.FileDrop, true);
        SourcePicture.Source = new BitmapImage(new Uri(fileNames[0], 
            UriKind.Absolute));
        Application.Current.MainWindow.Activate();
    }
}