c# - Save BitmapImage to File -
i working on program downloads images url bitmapimageand displays it. next try save bitmapimage harddrive using jpegbitmapencoder. file created actual jpeg image empty or 1 black pixel.
public guid savephoto(string istrimagepath) { imagepath = istrimagepath; bitmapimage objimage = new bitmapimage( new uri(istrimagepath, urikind.relativeorabsolute)); picturedisplayed.source = objimage; savedcreationobject = objimage; guid photoid = system.guid.newguid(); string photolocation = photoid.tostring() + ".jpg"; //file name filestream filestream = new filestream(photolocation, filemode.create); jpegbitmapencoder encoder = new jpegbitmapencoder(); encoder.frames.add(bitmapframe.create(objimage)); encoder.save(filestream); return photoid; }
this function saves , displays photo. photo displayed correctly again when saved empty jpeg or 1 black pixel.
when create bitmapimage uri, time required download image.
if check following property, value true
objimage.isdownloading
as such, attach listener downloadcompleted event handler , move processing eventhandler.
objimage.downloadcompleted += objimage_downloadcompleted;
where handler like:
private void objimage_downloadcompleted(object sender, eventargs e) { jpegbitmapencoder encoder = new jpegbitmapencoder(); guid photoid = system.guid.newguid(); string photolocation = photoid.tostring() + ".jpg"; //file name encoder.frames.add(bitmapframe.create((bitmapimage)sender)); using (var filestream = new filestream(photolocation, filemode.create)) encoder.save(filestream); }
you want add eventhandler downloadfailed in order gracefully handle error cases.
edit
added full sample class based on ben's comment:
public partial class mainwindow : window { public mainwindow() { initializecomponent(); savephoto("http://www.google.ca/intl/en_com/images/srpr/logo1w.png"); } public void savephoto(string istrimagepath) { bitmapimage objimage = new bitmapimage(new uri(istrimagepath, urikind.relativeorabsolute)); objimage.downloadcompleted += objimage_downloadcompleted; } private void objimage_downloadcompleted(object sender, eventargs e) { jpegbitmapencoder encoder = new jpegbitmapencoder(); guid photoid = system.guid.newguid(); string photolocation = photoid.tostring() + ".jpg"; //file name encoder.frames.add(bitmapframe.create((bitmapimage)sender)); using (var filestream = new filestream(photolocation, filemode.create)) encoder.save(filestream); } }
Comments
Post a Comment