I try to write an application that create a watermarked image from the loaded jpeg in WPF. I want to load in WPF an jpeg image and draw it with a predifined png with a transparence region over. I've tried to create two images as the RenderTargetBitmap and then create a new RenderTargetBitmap like
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.Widt开发者_如何转开发h = 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;
}
but it doen't work.
Can anyone point me at the solution?
I have an easier solution:
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>
Code behind:
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();
}
}
精彩评论