在開發中,涉及圖片的處理經常需要用到WritableBitmap對象,這個對象可以直接作為資料來源賦值給Image控制項,但若要儲存這個對象,我們只能將其序列化儲存為一個圖片檔案,自然需要用到圖片的編解碼庫:
將WritableBitmap儲存為圖片檔案
WriteableBitmap^ wb =“您的源”;IBuffer^ buffer = wb->PixelBuffer;DataReader^ dataReader = DataReader::FromBuffer(buffer);Array<unsigned char,1>^ fileContent =ref new Array<unsigned char,1>(buffer->Length);dataReader->ReadBytes(fileContent);task<StorageFile^>(ApplicationData::Current->LocalFolder->CreateFileAsync(pathName, CreationCollisionOption::ReplaceExisting)).then([this,fileContent,wb](StorageFile^ file){ task<IRandomAccessStream^>(file->OpenAsync(FileAccessMode::ReadWrite)).then([this,fileContent,wb](IRandomAccessStream^ _stream){
task<BitmapEncoder^>(BitmapEncoder::CreateAsync(BitmapEncoder::JpegEncoderId,_stream)).then([this,fileContent,wb](BitmapEncoder^ encoder){ encoder->SetPixelData(BitmapPixelFormat::Bgra8,BitmapAlphaMode::Straight,wb->PixelWidth ,wb->PixelHeight,96,96,fileContent); task<void>(encoder->FlushAsync()).then([=](void) { //Jpeg File Save Success! }); }); });});
將圖片檔案讀取到WritableBitmap對象
task<StorageFile^> ReadTask(ApplicationData::Current->LocalFolder->GetFileAsync(filename));ReadTask.then([=](StorageFile^ sampleFile){task<IRandomAccessStream^>(sampleFile->OpenAsync(FileAccessMode::Read)).then([=](IRandomAccessStream^ readStream){ int nWidth = 163; int nHeigh = 202; WriteableBitmap^ bitmapSnap = ref new WriteableBitmap(nWidth,nHeigh); readStream->Seek(0); bitmapSnap->SetSource(readStream);});});