I want to show Image in my WPF Window.
I have put this code to do so.
<Image x:Name="ImageControl" Stretch="Fill" Margin="2" Source="{Binding imgSource}"/>
and in code behind I have put,
public ImageSource imgSource
{
get
{
logo = new BitmapImage();
logo.BeginInit();
logo.UriSource = new Uri(#"C:\MyFolder\Icon.jpg");
logo.EndInit();
return logo;
}
}
This code shows image fine but I also should be able to change image runtime, That is, I want to replace Icon.jpg with another Image.
MyFolder is the folder path that will contain an Image "Icon.jpg" (Name would always be same).
So whenever I try to replace Icon.jpg with anyother Image, I get an error That Image file in Use
Can Anyone suggest how to overcome this issue. Please let me know if I need to clear my question.
Thanks in Anticipation.
Implement INotifyPropertyChanged in the class.
Change your property to a "get" "set"
And don't forget to set the DataContext.
Here is the code:
public class MyClass : INotifyPropertyChanged
{
private string imagePath;
public string ImagePath
{
get { return imagePath; }
set
{
if (imagePath != value)
{
imagePath = value;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.UriSource = new Uri(ImagePath);
bitmapImage.EndInit();
imgSource = bitmapImage;
}
}
}
public BitmapImage logo;
public ImageSource imgSource
{
get { return logo; }
set
{
if (logo != value)
{
logo = value;
OnPropertyChanged("imgSource");
}
}
}
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
UPDATE
BitmapImage is known to keep the file loaded when passing the path using string.
Load with a FileStream instead. BitmapImage as on demand loading capability set by default. To foce the bitmap to load the image on EndInit you have to change the ChacheOption:
using (FileStream stream = File.OpenRead(#"C:\MyFolder\Icon.jpg"))
{
logo = new BitmapImage();
logo.BeginInit();
logo.StreamSource = stream;
logo.CacheOption = BitmapCacheOption.OnLoad;
logo.EndInit();
}
Related
I have a view that contains an image control that is binded to this property:
private System.Drawing.Image _sigImage;
public System.Drawing.Image sigImage
{
get { return _sigImage; }
set { _sigImage = value; RaisePropertyChanged(); }
}
I am busy implementing a a signature pad using mvvm, and want the signature to display in the image control. However i cant get it to display.
The code for die signature pad is:
DynamicCapture dc = new DynamicCaptureClass();
DynamicCaptureResult res = dc.Capture(sigCtl, "Who", "Why", null, null);
if (res == DynamicCaptureResult.DynCaptOK)
{
sigObj = (SigObj)sigCtl.Signature;
sigObj.set_ExtraData("AdditionalData", "C# test: Additional data");
try
{
byte[] binaryData = sigObj.RenderBitmap("sign", 200, 150, "image/png", 0.5f, 0xff0000, 0xffffff, 10.0f, 10.0f, RBFlags.RenderOutputBinary | RBFlags.RenderColor32BPP) as byte[];
using (MemoryStream memStream = new MemoryStream(binaryData))
{
System.Drawing.Image newImage = System.Drawing.Image.FromStream(memStream);
sigImage = newImage;
// work with image here.
// You'll need to keep the MemoryStream open for
// as long as you want to work with your new image.
memStream.Dispose();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The image is stored as a bitmap in the variable newImage.
How can i bind that image to the image control of sigImage?
System.Drawing.Image is not an appropriate type for the Source property of an Image element. It is WinForms, not WPF.
Use System.Windows.Media.ImageSource instead
private ImageSource sigImage;
public ImageSource SigImage
{
get { return sigImage; }
set { sigImage = value; RaisePropertyChanged(); }
}
and assign a BitmapImage or BitmapFrame to the property, which is directly created from the MemoryStream. BitmapCacheOption.OnLoad has to be set in order to enable closing the stream immediately after decoding the bitmap.
var bitmapImage = new BitmapImage();
using (var memStream = new MemoryStream(binaryData))
{
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.StreamSource = memStream;
bitmapImage.EndInit();
}
bitmapImage.Freeze();
SigImage = bitmapImage;
The Binding would look like shown below, provided an instance of the class with the SigImage property is assigned to the DataContext of the view.
<Image Source="{Binding SigImage}"/>
Since WPF has built-in type conversion from string, Uri and byte[] to ImageSource, you may as well declare the source property as byte[]
private byte[] sigImage;
public byte[] SigImage
{
get { return sigImage; }
set { sigImage = value; RaisePropertyChanged(); }
}
and assign a value like
SigImage = binaryData;
without manually creating a BitmapImage or BitmapFrame, or changing the Binding.
I am just beginning to experiment with Ghostscript.Net. My goal is to adapt the GhostscriptViewer to my WPF MVVM Modular environment, but I am not able to display a page in a XAML Image control. I suspect that my problem lies either in my inadequate knowledge of Ghostscript.Net or in not understanding how to bind the image parameter to the image control.
In this app, I am using Prism with the UnityContainer. The PdfPageImage property in PdfViewModel is bound to the image control in the view XAML. The conversion, which takes place in the _viewer_displaypage method gives PdfPageImage an object of type System.Windows.Interop.InteropBitmap. I was thinking that the RaisePropertyChangedEvent method would cause the control to be updated with the ImageSource object.
<Image x:Name="PdfDocumentImage" Grid.Column="1" Grid.Row="0"
Source="{Binding PdfPageImage}"
Height="100"
Width="100">
</Image>
public class PdfViewModel : ViewModelBase, IPdfViewModel
{
private readonly IBitmapToImageSourceConverter _imageSourceConverter;
private readonly GhostscriptViewer _ghostscriptViewer;
private readonly GhostscriptVersionInfo _gsVersion =
GhostscriptVersionInfo.GetLastInstalledVersion(GhostscriptLicense.GPL |
GhostscriptLicense.AFPL, GhostscriptLicense.GPL);
private ImageSource _pdfPageImage;
public ImageSource PdfPageImage
{
get => _pdfPageImage;
set
{
if (value == _pdfPageImage) return;
_pdfPageImage = value;
RaisePropertyChangedEvent(nameof(PdfPageImage));
}
}
public PdfViewModel(IPdfView view,
IEventAggregator eventAggregator,
IBitmapToImageSourceConverter imageSourceConverter,
GhostscriptViewer ghostscriptViewer)
: base(view)
{
_ghostscriptViewer = ghostscriptViewer;
_imageSourceConverter = imageSourceConverter;
_ghostscriptViewer.DisplayPage += _viewer_DisplayPage;
eventAggregator.GetEvent<PdfDocumentOpenedEvent>().Subscribe(OpenPdfDocument, ThreadOption.UIThread);
}
private void _viewer_DisplayPage(object sender, GhostscriptViewerViewEventArgs e)
{
PdfPageImage = _imageSourceConverter.ImageSourceForBitmap(e.Image);
}
private void OpenPdfDocument(string path)
{
_ghostscriptViewer.Open(path, _gsVersion, false);
}
}
public class BitmapToImageSourceConverter : IBitmapToImageSourceConverter
{
[DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DeleteObject(IntPtr hObject);
public ImageSource ImageSourceForBitmap(Bitmap bmp)
{
var handle = bmp.GetHbitmap();
try
{
return Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
}
finally { DeleteObject(handle); }
}
}
Okay. So I figured it out. My solution isn't perfect; while paging through a pdf document, the page orientation isn't correct, but other than that, it works.
The key was to use a memorystream in creating a BitmapImage:
public static BitmapImage ConvertBitmapToImage(System.Drawing.Image image)
{
using (MemoryStream memoryStream = new MemoryStream())
{
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
memoryStream.Position = 0;
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
memoryStream.Seek(0, SeekOrigin.Begin);
bitmapImage.StreamSource = memoryStream;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
return bitmapImage;
}
}
Many other modifications were made to make the Ghostscrip.NET viewer work in my WPF MVVM app. If anybody is interested in more details, I will post more.
My application loads a lot of images in a BackgroundWorker to stay usable. My Image control is bound to a property named "ImageSource". If this is null it's loaded in the background and raised again.
public ImageSource ImageSource
{
get
{
if (imageSource != null)
{
return imageSource;
}
if (!backgroundImageLoadWorker.IsBusy)
{
backgroundImageLoadWorker.DoWork += new DoWorkEventHandler(bw_DoWork);
backgroundImageLoadWorker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
backgroundImageLoadWorker.RunWorkerAsync();
}
return imageSource;
}
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
bitmap = new BitmapImage();
bitmap.BeginInit();
try
{
bitmap.CreateOptions = BitmapCreateOptions.DelayCreation;
bitmap.DecodePixelWidth = 300;
MemoryStream memoryStream = new MemoryStream();
byte[] fileContent = File.ReadAllBytes(imagePath);
memoryStream.Write(fileContent, 0, fileContent.Length);
memoryStream.Position = 0;
bitmap.StreamSource = memoryStream;
}
finally
{
bitmap.EndInit();
}
bitmap.Freeze();
e.Result = bitmap;
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
BitmapSource bitmap = e.Result as BitmapSource;
if (bitmap != null)
{
Dispatcher.CurrentDispatcher.BeginInvoke(
(ThreadStart)delegate()
{
imageSource = bitmap;
RaisePropertyChanged("ImageSource");
}, DispatcherPriority.Normal);
}
}
This is all well so far but my users can change the images in question. They choose a new image in an OpenDialog, the old image file is overwritten with the new and ImageSource is raised again which loads the new image with the same filename again:
public string ImagePath
{
get { return imagePath; }
set
{
imagePath= value;
imageSource = null;
RaisePropertyChanged("ImageSource");
}
}
On some systems the overwriting of the old file results in an exception:
"a generic error occured in GDI+" and "The process cannot access the file..."
I tried a lot of things like loading with BitmapCreateOptions.IgnoreImageCache and BitmapCacheOption.OnLoad. This raised Exceptions when loading them:
Key cannot be null.
Parameter name: key
If I try this without the BackgroundWorker on the UI thread it works fine. Am I doing something wrong? Isn't it possible to load the images in the background while keeping the files unlocked?
Well, it seems all of the above works. I simplified the example for the question and somehow on the way lost the problem.
The only difference I could see in my code is that the loading of the image itself was delegated to a specific image loader class which somehow created the problem. When I removed this dependency the errors disappeared.
I have problem with converter from Uri to BitmapImage. Uri is url of image on web. I use this converter on item in listbox.
I download image from webpage and create from this stream BitampImage
Problem is if listbox consist about 100 - 250 items, app freeze, I try call WebRequestMethod in another thread but it don’t work.
Here is root part of code:
private static BitmapImage GetImgFromAzet(int sex, Uri imgUri)
{
try
{
if (imgUri == null)
{
if (sex == (int)Sex.Man)
{
return new BitmapImage(new Uri(#"pack://application:,,,/Spirit;Component/images/DefaultAvatars/man.jpg",
UriKind.RelativeOrAbsolute));
}
else
{
return new BitmapImage(new Uri(#"pack://application:,,,/Spirit;Component/images/DefaultAvatars/woman.jpg",
UriKind.RelativeOrAbsolute));
}
}
else
{
BitmapImage image = null;
Task.Factory.StartNew(() =>
{
WebRequest webRequest = WebRequest.CreateDefault(imgUri);
webRequest.ContentType = "image/jpeg";
WebResponse webResponse = webRequest.GetResponse();
image = new BitmapImage();
image.CreateOptions = BitmapCreateOptions.None;
image.CacheOption = BitmapCacheOption.OnLoad;
image.BeginInit();
image.StreamSource = webResponse.GetResponseStream();
image.EndInit();
return image;
//((System.Action)(() =>
//{
// //webResponse.Close();
//})).OnUIThread();
});
return image;
}
}
catch (Exception)
{
//default
return
new BitmapImage(new Uri(PokecUrl.Avatar,UriKind.RelativeOrAbsolute));
}
}
My aim is download image from web, create BitamImage object from him and return as Source of Image control, but I need avoid app freezing. Also problem is if I close webResponse it broke all code.
EDITED:
I try this:
BitmapImage image;
WebRequest req = WebRequest.CreateDefault(imgUri);
req.ContentType = "image/jpeg";
using (var res = req.GetResponse())
{
image = new BitmapImage();
image.CreateOptions = BitmapCreateOptions.None;
image.CacheOption = BitmapCacheOption.OnLoad;
image.BeginInit();
image.UriSource = imgUri;
image.StreamSource = res.GetResponseStream();
image.EndInit();
}
but somewhere must be bug, code is broken.
Any advice?
Binding converter is always executed on UI thread. So you could start other thread in Convert method but eventually (as you need feedback from this thread) you have to wait until it completes, thereby you're blocking your app.
In order to solve this problem, for example, you could use Binding.IsAsync property:
public class ListItemViewData
{
private readonly Uri _uri;
private readonly Sex _sex;
ListItemViewData(Uri uri, Sex sex)
{
this._uri = uri;
this._sex = sex;
}
public BitmapSource Image
{
get
{
// Do synchronous WebRequest
}
}
}
Usage in xaml (inside DataTemplate of listbox item):
<Image Source="{Binding Path=Image, IsAsync=True}"/>
EDITED
I've dived into BitmapImage class and have found out that it has pretty ctor with Uri parameter, that works asynchronously.
So you shouldn't execute WebRequest by yourself. Do just like this:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var uri = (Uri)value;
return new BitmapImage(uri) { CacheOption = BitmapCacheOption.None };
}
EDITED 2
Your view data class.
public class ListItemViewData : INotifyPropertyChanged
{
public ListItemViewData(Uri uri)
{
this._uri = uri;
}
private readonly Uri _uri;
public Uri Uri
{
get
{
return this._uri;
}
}
private BitmapSource _source = null;
public BitmapSource Image
{
get
{
return this._source;
}
set
{
this._source = value;
this.OnPropertyChanged("Image");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string p)
{
var pc = this.PropertyChanged;
if (pc!=null)
{
pc(this, new PropertyChangedEventArgs(p));
}
}
}
Helper, that executes images downloading:
public static class WebHelper
{
public static Stream DownloadImage(Uri uri, string savePath)
{
var request = WebRequest.Create(uri);
var response = request.GetResponse();
using (var stream = response.GetResponseStream())
{
Byte[] buffer = new Byte[response.ContentLength];
int offset = 0, actuallyRead = 0;
do
{
actuallyRead = stream.Read(buffer, offset, buffer.Length - offset);
offset += actuallyRead;
}
while (actuallyRead > 0);
File.WriteAllBytes(savePath, buffer);
return new MemoryStream(buffer);
}
}
}
When you are filling model - you should start separate thread, which will download files and set up images source.
this._listItems.Add(new ListItemViewData(new Uri(#"http://lifeboat.com/images/blue.ocean.jpg")));
//...
var sc = SynchronizationContext.Current;
new Thread(() =>
{
foreach (var item in this._listItems)
{
var path = "c:\\folder\\"+item.Uri.Segments.Last();
var stream = WebHelper.DownloadImage(item.Uri, path);
sc.Send(p =>
{
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = (Stream)p;
bi.EndInit();
item.Image = bi;
}, stream);
}
}).Start();
In an app I need to serialize an image through a binarywriter, and to get it in an other app to display it.
Here is a part of my "serialization" code :
FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write);
BinaryWriter bin = new BinaryWriter(fs);
bin.Write((short)this.Animations.Count);
for (int i = 0; i < this.Animations.Count; i++)
{
MemoryStream stream = new MemoryStream();
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(Animations[i].Image));
encoder.Save(stream);
stream.Seek(0, SeekOrigin.Begin);
bin.Write((int)stream.GetBuffer().Length);
bin.Write(stream.GetBuffer());
stream.Close();
}
bin.Close();
And here is the part of my deserialization that load the image :
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader bin = new BinaryReader(fs);
int animCount = bin.ReadInt16();
int imageBytesLenght;
byte[] imageBytes;
BitmapSource img;
for (int i = 0; i < animCount; i++)
{
imageBytesLenght = bin.ReadInt32();
imageBytes = bin.ReadBytes(imageBytesLenght);
img = new BitmapImage();
MemoryStream stream = new MemoryStream(imageBytes);
BitmapDecoder dec = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
img = dec.Frames[0];
stream.Close();
}
bin.Close();
When I use this method, I load the image (it seems to be stored in the "img" object) but it can't be displayed.
Has somedy an idea?
Thanks
KiTe
UPD :
I already do this : updating my binding, or even trying to affect it directly through the window code behing. None of these approaches work :s
However, when I add this :
private void CreateFile(byte[] bytes)
{
FileStream fs = new FileStream(Environment.CurrentDirectory + "/" + "testeuh.png", FileMode.Create, FileAccess.Write);
fs.Write(bytes, 0, bytes.Length);
fs.Close();
}
at the end of you function, it perfectly create the file, which can be read without any problems ... So I don't know where the problem can be.
UPD 2 :
A weird things happens.
Here is the binding I use :
<Image x:Name="imgSelectedAnim" Width="150" Height="150" Source="{Binding ElementName=lstAnims, Path=SelectedItem.Image}" Stretch="Uniform" />
(the list is itself binded on an observableCollection).
When I create manually the animation through the app, it works (the image is displayed).
But when I load it, it is not displayed (I look at my code, there are not any "new" which could break up my binding, since there are others properties binded the same way and they does not fail).
Moreover, I've put a breakpoint on the getter/setter of the properties Image of my animation.
When it is created, no problems, it has the good informations.
But when it is retreived through the getter, it return a good image the first time, and then and image with pixelWidth, pixelHeight, width, height of only 1 but without going through the setter anymore !
Any idea?
UPD3
tried what you said like this :
Added a property TEST in my viewModel :
private BitmapSource test;
public BitmapSource TEST { get { return test; } set { test = value; RaisePropertyChanged("TEST"); } }
then did it :
img = getBmpSrcFromBytes(bin.ReadBytes(imageBytesLenght));
TEST = img;
(in the code showed and modified before)
and my binding :
<Image x:Name="imgSelectedAnim" Width="150" Height="150" Source="{Binding Path=TEST}" Stretch="Uniform" />
(datacontext is set to my ViewModel)
And it still doesn't work and does the weird image modification (pixW, pixH, W and H set to 1)
FINAL UPD:
It seems I finally solved the problem. Here is simply what I did :
byte[] bytes = bin.ReadBytes(imageBytesLenght);
MemoryStream mem = new MemoryStream(bytes);
img = new BitmapImage();
img.BeginInit();
img.StreamSource = mem;
img.EndInit();
the strange thing is that it didn't work the first time, maybe it is due to an architectural modification within my spriteanimation class, but I don't think it is.
Well, thank you a lot to Eugene Cheverda for his help
At the first, I think you should store your images in a list of BitmapSource and provide reverse encoding of image for using stream as BitmapImage.StreamSource:
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader bin = new BinaryReader(fs);
int animCount = bin.ReadInt16();
int imageBytesLenght;
byte[] imageBytes;
List<BitmapSource> bitmaps = new List<BitmapSource>();
for (int i = 0; i < animCount; i++)
{
imageBytesLenght = bin.ReadInt32();
imageBytes = bin.ReadBytes(imageBytesLenght);
bitmaps.Add(getBmpSrcFromBytes(imageBytes));
}
bin.Close();
UPD
In code above use func written below:
private BitmapSource getBmpSrcFromBytes(byte[] bytes)
{
using (var srcStream = new MemoryStream(bytes))
{
var dec = new PngBitmapDecoder(srcStream, BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.Default);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(dec.Frames[0]);
BitmapImage bitmapImage = null;
bool isCreated;
try
{
using (var ms = new MemoryStream())
{
encoder.Save(ms);
bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = ms;
bitmapImage.EndInit();
isCreated = true;
}
}
catch
{
isCreated = false;
}
return isCreated ? bitmapImage : null;
}
}
Hope this helps.
UPD #2
Your binding is incorrect. You may be should bind selected item to for example CurrentImageSource. And then this CurrentImageSource bind to Image control.
Code:
public class MyViewModel : INotifyPropertyChanged
{
public ObservableCollection<BitmapSource> ImagesCollection { get; set; }
private BitmapSource _currentImage;
public BitmapSource CurrentImage
{
get { return _currentImage; }
set
{
_currentImage = value;
raiseOnPropertyChanged("CurrentImage");
}
}
private void raiseOnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
Then:
<ListBox ItemsSource="{Binding ImagesCollection}" SelectedItem="{Binding CurrentImage}"/>
<Image Source="{Binding CurrentImage}"/>
ADDED
Here is the sample project in which implemented technique as I described above.
It creates animations collection and represent them in listbox, selected animation is displayed in Image control using its Image property.
What I want to say is that if you cannot obtain image as it should be, you need to search problems in serialization/deserialization.