c# - WPF: Memory implications of using ValueConverter to create BitmapImage for ImageSource -
i had issue using images , provide right-click context menu deleting image.
originally binding absolute file path:
<image source="{binding path=imagefilename} .../>
where imagefilename
c:\myapp\images\001.png
.
i getting error, the process cannot access file 'x' because being used process
. after lot of research, figured out necessary code change.
i used stackoverflow answer: delete file being used process , put code valueconverter
.
xaml:
<image source="{binding path=imagefilename, converter={staticresource pathtoimageconverter}}" ...>
value converter:
public class pathtoimageconverter : ivalueconverter { public object convert(object value, type targettype, object parameter, cultureinfo culture) { try { string filename = value string; if (filename != null) { bitmapimage image = new bitmapimage(); image.begininit(); image.cacheoption = bitmapcacheoption.onload; image.urisource = new uri(filename); image.endinit(); return image; } return new bitmapimage(); } catch { return new bitmapimage(); } } public object convertback(object value, type targettype, object parameter, cultureinfo culture) { throw new notimplementedexception(); } }
the concern have memory usage. when add images container, see memory increase. however, when delete images, , underlying file deleted, not see memory being freed up.
i've thought of bitmaps inefficient file format, since uncompressed, , tend huge compared jpeg or png file.
system.windows.media.imaging.bitmapsource
class creating uncompressed image out of png?
thanks in advance!
philip
wpf caches 300 imagesource
objects (using weak references) when load image uri. avoid this, set bitmapcreateoptions.ignoreimagecache
option or use filestream
load image instead.
note have adverse effect on app's performance, in situation you're scrolling , loading images in virtualized listbox
. if you're loading large images, might want avoid it.
use following code in converter (note added image.freeze
call, improves performance making object read-only , thread-agnostic):
using (var fs = new filestream(filename, filemode.open, fileaccess.read)) { bitmapimage image = new bitmapimage(); image.begininit(); image.cacheoption = bitmapcacheoption.onload; image.streamsource = fs; image.endinit(); image.freeze(); return image; }
another possible performance optimization set decodepixelwidth
downscale image.
regarding concern formats -- bitmap general name pixel-based images (in contrast vector-based images). file formats mentioned (png, jpeg) bitmaps well, they're encoded (possibly compression). bitmapimage
class uses wic decode them can rendered on screen.
Comments
Post a Comment