WPF Image Dynamically changing Image source during runtime - wpf

I have a window with a title on it. When the user selects a choice from a drop down list, the title image can change. The problem is when the image loads, it's a blurred, stretched, and pixelated. These are PNG files I'm working with and they look good prior to setting the source dynamically.
Here's the code I'm using to change the image's source.
string strUri2 = String.Format(#"pack://application:,,,/MyAssembly;component/resources/main titles/{0}", CurrenSelection.TitleImage);
Stream iconStream2 = App.GetResourceStream(new Uri(strUri2)).Stream;
imgTitle.Source = HelperFunctions.returnImage(iconStream2);
Here are the helper functions.
public static BitmapImage returnImage(Stream iconStream)
{
Bitmap brush = new Bitmap(iconStream);
System.Drawing.Image img = brush.GetThumbnailImage(brush.Height, brush.Width, null, System.IntPtr.Zero);
var imgbrush = new BitmapImage();
imgbrush.BeginInit();
imgbrush.StreamSource = ConvertImageToMemoryStream(img);
imgbrush.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
imgbrush.EndInit();
var ib = new ImageBrush(imgbrush);
return imgbrush;
}
public static MemoryStream ConvertImageToMemoryStream(System.Drawing.Image img)
{
var ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms;
}
And the XAML
<Image x:Name="imgTitle" HorizontalAlignment="Left" VerticalAlignment="Bottom" Grid.Column="1" Grid.Row="1" Stretch="None" d:IsLocked="False"/>
And for Ref:
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
Anyone have any ideas what's up?

I can think of two things:
First, try loading the image with:
string strUri2 = String.Format(#"pack://application:,,,/MyAseemby;component/resources/main titles/{0}", CurrenSelection.TitleImage);
imgTitle.Source = new BitmapImage(new Uri(strUri2));
Maybe the problem is with WinForm's image resizing, if the image is stretched set Stretch on the image control to "Uniform" or "UnfirofmToFill".
Second option is that maybe the image is not aligned to the pixel grid, you can read about it on my blog at http://www.nbdtech.com/blog/archive/2008/11/20/blurred-images-in-wpf.aspx

Hey, this one is kind of ugly but it's one line only:
imgTitle.Source = new BitmapImage(new Uri(#"pack://application:,,,/YourAssembly;component/your_image.png"));

Here is how it worked beautifully for me.
In the window resources add the image.
<Image x:Key="delImg" >
<Image.Source>
<BitmapImage UriSource="Images/delitem.gif"></BitmapImage>
</Image.Source>
</Image>
Then the code goes like this.
Image img = new Image()
img.Source = ((Image)this.Resources["delImg"]).Source;
"this" is referring to the Window object

Like for me -> working is:
string strUri2 = Directory.GetCurrentDirectory()+#"/Images/ok_progress.png";
image1.Source = new BitmapImage(new Uri(strUri2));

Me.imgAddNew.Source = New System.Windows.Media.Imaging.BitmapImage(New Uri("/SPMS;component/Images/Cancel__Red-64.png", UriKind.Relative))

Try Stretch="UniformToFill" on the Image

Related

Display Image in Modal Window

I am trying to display am image with two methods: First is when user has full absolute path and if they don't have it and if image is stored in sqlite database as blob object.
Here is my code:
var modal = new Modal();
modal.HorizontalAlignment = HorizontalAlignment.Center;
modal.VerticalAlignment = VerticalAlignment.Center;
modal.Title = "View Image";
modal.ResizeMode = ResizeMode.CanResizeWithGrip;
Grid grid = new Grid();
RowDefinition row1 = new RowDefinition() {Height = GridLength.Auto};
grid.RowDefinitions.Add(row1);
if (!string.IsNullOrEmpty(ImageFileLocation))
{
Image i = new Image();
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri(ImageFileLocation, UriKind.Absolute);
bi.EndInit();
i.Source = bi;
//i.Height = 400;
//i.Width = 400;
i.MinHeight = 400;
i.MinWidth = 400;
i.Stretch = Stretch.Fill;
i.HorizontalAlignment = HorizontalAlignment.Stretch;
i.VerticalAlignment = VerticalAlignment.Stretch;
grid.Children.Add(i);
modal.ModalContentControl.Content = grid;
}
else if (ImageStore.ImageStoreId != null)
{
//TODO: Create Image object to display
MessageBox.Show(ImageStore.ImageStoreId.ToString());
}
modal.ShowDialog();
Here is my Modal.. It is basically a window that I can re-use as a modal dialog box.
<Window x:Class="Screens.Modal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Screens"
mc:Ignorable="d"
Title="Modal" ResizeMode="NoResize"
SizeToContent="WidthAndHeight" x:Name="ModalWindow" WindowStartupLocation="CenterScreen">
<Grid>
<ContentControl x:Name="ModalContentControl" />
</Grid>
</Window>
Everything in code above works except one thing. when Modal is displayed with an image, modal comes out to be super huge and it fills almost my two monitors. I want to achieve two things with this:
I want modal to be resizable and so does the image inside it (responsive approach)
I want image to be proportionately growing since most of the image I use will be rectangle image and not square.
This might be easier and I probably can Google it and find out but since I am asking related question here.. How can I use the BLOB to create an Image object?
Please remove extra parameters I have with modal and/or image object if you think it is not needed to achieve what I want.
Avoid setting the SizeToContent property of the modal window to WidthAndHeight in your XAML markup. Keep its default value of Manual.

Load image from another assembly's resx file in XAML

I have two assemblies, say assembly1 and assembly2.
In assembly2 there is a XAML file. In this XAML file I want to create an image.
What I want to do is setting the source of this image to a bitmap that is in a resx file from assembly1.
<Image Name="image1" Stretch="Fill" Source="???" />
How do I correctly reference to that bitmap file in XAML? Is there an easy "XAML-only" solution?
Okay, so I assume there is no thing such as an "XAML-only" solution.
Instead, I do it like this after the WPF control's Loaded event is called:
Assembly coreAssembly = Assembly.GetAssembly(typeof (otherAssembly.Resources));
var resourceManager = new ResourceManager("otherAssembly.Resources", coreAssembly);
// get image from core resources
Bitmap completeImage = (Bitmap) resourceManager.GetObject("Complete");
// apply image to WPF image
var memoryStream = new MemoryStream();
completeImage.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = new MemoryStream(memoryStream.ToArray());
bitmapImage.EndInit();
this.myWpfImage.Source = bitmapImage;

XAML+TextBox: Referencing text from resource file included in assembly

I know how to use an image from my assembly resources in XAML for the Image element:
<Image Source="pack://application:,,,/MyImage.png" />
But, how can I do it for the Text attribute of a TextBox? Something similar to:
<TextBox Text="pack://application:,,,/MyTextFile.txt" />
Here is my current solution, but requires some code-behind:
Uri licenseUri = new Uri("pack://application:,,,/MyTextFile.txt", UriKind.Absolute);
StreamResourceInfo info = Application.GetResourceStream(licenseUri);
StreamReader reader = new StreamReader(info.Stream);
_textBox.Text = reader.ReadToEnd();

How to bind Image source?

From some examples, I think I'm doing this right, but it's not working so I wanted to check here to see. I'm binding my Image source, but the image is not there. If I take away my binding and just set the Image source to the path used in the method below it works fine.
public Image myImage = new Image();
public void someMethod() {
BitmapImage biSource = new BitmapImage();
biSource.BeginInit();
biSource.CacheOption = BitmapCacheOption.OnLoad;
biSource.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
biSource.UriSource = new Uri(#"C:\Images\testimage.jpg");
biSource.DecodePixelWidth = 150;
biSource.EndInit();
myImage.Source = biSource;
}
xaml code
<Image Source="{Binding Path=myImage}" Width="150" Height="150" />
You should bind the Source property to an ImageSource, not an Image. Expose biSource as a property and bind to it instead of myImage
You try to bind an Image to the source of an Image, not going to work. You need to bind the BitmapImage to the source of the Image.
Also the BitmapImage needs to be exposed as public property. If you are new to data binding read this overview on MSDN.
Further you should learn how to debug bindings.

Why isn't the image in my image control clear?

BitmapImage B = new BitmapImage();
B.BeginInit();
B.StreamSource = asm.GetManifestResourceStream("WpfApplication26.Back1.png");
B.EndInit();
image1.Source = B;
The size of the image (Back1.png) is 32*32, and I set the size of my image control to 32*32 and set the property "Scale" to "None".
Try
RenderOptions.BitmapScalingMode="NearestNeighbor"
on the image control in xaml or
RenderOptions.SetBitmapScalingMode(image1, BitmapScalingMode.NearestNeighbor)
in code.
Try SnapsToDevicePixels="True" on the image control.
If you still want to clear the image, meaning, turning it to blank, just set the source to "null"
image1.Source = null;
This does not require a BitmapImage.
Sorry for the late reply...

Resources