1. Open the picture file and convert it to the BitmapImage class
The first thing to do is to open a picture file, you can use the Fileopenpicker to manually select the picture, in short, can get a storagefile is OK.
// Open the picture selector, select the picture you want to send var openpicker = fileopenpicker{ ViewMode = Pickerviewmode.thumbnail, suggestedstartlocation = Pickerlocationid.pictureslibrary};openpicker.filetypefilter.add ( " .jpg " " Span style= "color: #800000;" >.jpeg ); var file = await Openpicker.picksinglefileasync ();
You can also use Storagefile.getfilefromapplicationuriasync to get the file that the following code obtains is the 1.jpg file in the Application standalone storage folder Localstate.
var " ms-appdata:///local/1.jpg " ; var await Storagefile.getfilefromapplicationuriasync (Thenew Uri (path));
The file is then opened and the file stream is written to BitmapImage.
// read the picture file as BitmapImage var await file. OpenReadAsync (); var New BitmapImage (); await bitmap. Setsourceasync (FileStream);
2. Convert picture byte[] information to bitmap
First, the byte[] is converted to Irandomaccessstream and then the Bitmapimage.setsourceasync method is used to write the stream to the bitmap, and the simple MemoryStream is not directly written to the bitmap.
Public Async StaticTask<bitmapimage> Convertbytestobitmapimage (byte[] bytes) { Try { if(bytes = =NULL|| bytes. Length = =0)return NULL; varstream =NewMemoryStream (bytes); varRandomaccessstream =NewInmemoryrandomaccessstream (); using(varOutputStream = Randomaccessstream.getoutputstreamat (0)) { varDW =NewDataWriter (OutputStream); varTask =NewTask (() =DW. Writebytes (stream. ToArray ())); Task. Start (); awaittask; awaitDW. Storeasync (); awaitOutputstream.flushasync (); varBitmapImage =NewBitmapImage (); awaitBitmapimage.setsourceasync (Irandomaccessstream); returnBitmapImage; } } Catch(Exception Exception) {Debug.WriteLine ("[Error] Convert bytes to BitmapImage failed,exception: {0}", exception); return NULL; }}
Universal app picture file and picture byte[] information converted to bitmap