/// <summary> /// 문자열 이미지 uri를 받아서 이미지를 로컬에 저장하고 BitmapImage로 반환한다. /// </summary> /// <param name="imageUri"></param> /// <returns></returns> public async Task<BitmapImage> UriImageSaveLocalAsync(string imageUri, bool retry = true) { if (string.IsNullOrEmpty(imageUri) == true) return null; //폴더 초기화 될때까지 대기 while (files == null) { await TaskEx.Delay(500); } //Stream var iuri = new Uri(imageUri, UriKind.Absolute); string filename = System.IO.Path.GetFileName(iuri.LocalPath); //메모리 내용확인 var mbi = GetImage(filename); if (mbi != null) { return mbi; } Stream imageStream = null; //기본 스트림 //IRandomAccessStream InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream(); //create bitmap BitmapImage bi = new BitmapImage(); //폴더에 파일 존재 확인 if (files.Any(p => p.Name == filename)) { var localFile = files.First(p => p.Name == filename); bi.UriSource = new Uri(Path.Combine(ApplicationData.Current.TemporaryFolder.Path, localFile.Name)); AddImage(filename, bi); //try //{ // imageStream = await localFile.OpenStreamForReadAsync(); //} //catch (Exception) //{ // //파일 열때 에러가 발생하면, 파일이 존재하지 않기 때문일 수 있는.. // UpdateFolder(); // bi.UriSource = new Uri(imageUri); // if (imageStream != null) imageStream.Dispose(); // if (ras != null) ras.Dispose(); // return bi; //} //await imageStream.CopyToAsync(ras.AsStreamForWrite()); //if (ras.Size > 0) //{ // ras.Seek(0); // await bi.SetSourceAsync(ras); // //메모리에 저장 // AddImage(filename, bi); //} //else //{ // //파일 이상인듯 // await localFile.DeleteAsync(); // UpdateFolder(); // //재귀호출 // if (retry == false) // { // if (imageStream != null) imageStream.Dispose(); // if (ras != null) ras.Dispose(); // return await UriImageSaveLocalAsync(imageUri, true); // } // else // { // bi.UriSource = new Uri(imageUri); // if (imageStream != null) imageStream.Dispose(); // if (ras != null) ras.Dispose(); // return bi; // } //} } else { using (HttpClient hc = new HttpClient()) { try { imageStream = await hc.GetStreamAsync(imageUri); } catch (Exception) { //네트워크 상태가 끊어졌을 때 bi.UriSource = new Uri(imageUri); if (imageStream != null) imageStream.Dispose(); if (ras != null) ras.Dispose(); return bi; } //Stream -> IRandomAccessStream await imageStream.CopyToAsync(ras.AsStreamForWrite()); if (ras.Size > 0) { try { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(ras); BitmapFrame frame = await decoder.GetFrameAsync(0); //파일로 저장 var bitmap = new WriteableBitmap((int)frame.PixelWidth, (int)frame.PixelHeight); ras.Seek(0); await bitmap.SetSourceAsync(ras); var saveImage = await bitmap.SaveToFile(ApplicationData.Current.TemporaryFolder, filename, CreationCollisionOption.OpenIfExists); UpdateFolder(); //UriSource로 이미지 넣어주고 bi.UriSource = new Uri(Path.Combine(ApplicationData.Current.TemporaryFolder.Path, saveImage.Name)); //이미지로 변환 //ras.Seek(0); //await bi.SetSourceAsync(ras); //메모리에 저장 AddImage(filename, bi); } catch (Exception) { //이미지가 너무 커서 저장할 수 없을 경우 그냥 이미지 uri를 넣어서 던짐 bi.UriSource = new Uri(imageUri); if (imageStream != null) imageStream.Dispose(); if (ras != null) ras.Dispose(); return bi; } } else { //재귀호출 if (retry == false) { if (imageStream != null) imageStream.Dispose(); if (ras != null) ras.Dispose(); return await UriImageSaveLocalAsync(imageUri, true); } else { bi.UriSource = new Uri(imageUri); if (imageStream != null) imageStream.Dispose(); if (ras != null) ras.Dispose(); return bi; } } } } if(imageStream != null) imageStream.Dispose(); if(ras != null) ras.Dispose(); return bi; }
public async Task<BitmapSource> GetBitmapSource(object bitmapSource, string cacheName, int width, bool asThumbnail = false) { var height = width; WriteableBitmap writeableBitmap = null; ObservableCollection<Uri> uriSource = bitmapSource as ObservableCollection<Uri>; if (!string.IsNullOrEmpty(cacheName) && uriSource != null) { try { cacheName = asThumbnail ? cacheName + ThumbnailPart : cacheName; string cacheFileName = string.Format("{0}.{1}", cacheName, ImageExtension); var storageFolder = await LocalStorage.GetImageFolderAsync(); var storageFile = await storageFolder.TryGetItemAsync(cacheFileName) as StorageFile; if (storageFile != null) { writeableBitmap = await new WriteableBitmap(width, height).LoadAsync(storageFile); } var innerWidth = width / 2; var innerHeight = innerWidth; writeableBitmap = new WriteableBitmap(width, height); int index = 0; foreach (Uri uri in uriSource) { try { var randomAccessStreamReference = RandomAccessStreamReference.CreateFromUri(uri); using (IRandomAccessStream randomAccessStream = await randomAccessStreamReference.OpenReadAsync()) { if (randomAccessStream != null) { //We initialize the bitmap with height and width, but the actual size will be reset after the FromStream method! WriteableBitmap innerImage = new WriteableBitmap(innerWidth, innerHeight); innerImage = await innerImage.FromStream(randomAccessStream); int xPosition = 0; int yPosition = 0; if (index == 1 || index == 2) { xPosition = xPosition + innerWidth; } if (index == 1 || index == 3) { yPosition = yPosition + innerHeight; } writeableBitmap.Blit( new Rect() { Height = innerHeight, Width = innerWidth, X = xPosition, Y = yPosition }, innerImage, new Rect() { Height = innerImage.PixelHeight, Width = innerImage.PixelWidth, X = 0, Y = 0 }, WriteableBitmapExtensions.BlendMode.Additive); } index++; } } catch (Exception) { } } await writeableBitmap.SaveToFile(storageFolder, cacheFileName, CreationCollisionOption.ReplaceExisting); } catch (Exception) { } } return writeableBitmap; }
private async Task<BitmapSource> GetWriteableBitmap() { var width = (int)this.Width; var height = width; WriteableBitmap writeableBitmap = null; string cacheFileName = string.Format("{0}.{1}", this.CacheName, ImageExtension); var storageFile = await Windows.Storage.ApplicationData.Current.LocalFolder.TryGetItemAsync(cacheFileName) as StorageFile; if (storageFile != null) { writeableBitmap = await new WriteableBitmap(width, height).LoadAsync(storageFile); } else { try { var innerWidth = width / 2; var innerHeight = innerWidth; writeableBitmap = new WriteableBitmap(width, height); int index = 0; foreach (Uri uri in this.m_uriCollection) { try { var randomAccessStreamReference = RandomAccessStreamReference.CreateFromUri(uri); using (IRandomAccessStream randomAccessStream = await randomAccessStreamReference.OpenReadAsync()) { if (randomAccessStream != null) { //We initialize the bitmap with height and width, but the actual size will be reset after the FromStream method! WriteableBitmap innerImage = new WriteableBitmap(innerWidth, innerHeight); innerImage = await innerImage.FromStream(randomAccessStream); int xPosition = 0; int yPosition = 0; if (index == 1 || index == 2) { xPosition = xPosition + innerWidth; } if (index == 2 || index == 3) { yPosition = yPosition + innerHeight; } writeableBitmap.Blit( new Rect() { Height = innerHeight, Width = innerWidth, X = xPosition, Y = yPosition }, innerImage, new Rect() { Height = innerImage.PixelHeight, Width = innerImage.PixelWidth, X = 0, Y = 0 }, WriteableBitmapExtensions.BlendMode.Additive); } index++; } } catch(Exception) { } } await writeableBitmap.SaveToFile(Windows.Storage.ApplicationData.Current.LocalFolder, cacheFileName, CreationCollisionOption.ReplaceExisting); } catch (Exception) { } } return writeableBitmap; }
private async Task LoadFile(StorageFile file) { fileName = Path.GetFileNameWithoutExtension(file.Name); Debug.WriteLine("Picked video: " + fileName + " with full name: " + file.Name); if (handledExtensions.Contains(Path.GetExtension(file.Path))) { MediaClip newClip; if (imageExtensions.Contains(Path.GetExtension(file.Path))) { newClip = await MediaClip.CreateFromImageFileAsync(file, TimeSpan.FromSeconds(DEFAULT_DURATION)); } else // if (videoExtensions.Contains(Path.GetExtension(file.Path))) { newClip = await MediaClip.CreateFromFileAsync(file); } m_composition.Clips.Add(newClip); // Render a thumbnail from the center of the clip's duration ImageStream x = await m_composition.GetThumbnailAsync(TimeSpan.FromMilliseconds(newClip.StartTimeInComposition.TotalMilliseconds + newClip.TrimmedDuration.TotalMilliseconds / 2d), HEIGHT, 0, VideoFramePrecision.NearestKeyFrame); StorageFolder localFolder = ApplicationData.Current.LocalFolder; // Write data to a file StorageFile imageFile = await localFolder.CreateFileAsync(newClip.GetHashCode() + imageExtensions[0], CreationCollisionOption.ReplaceExisting); //BitmapImage bitmap = new BitmapImage(); //bitmap.SetSource(x); //wBitmap.SetSource(x); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(x); WriteableBitmap wBitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight); // Scale image to appropriate size BitmapTransform transform = new BitmapTransform() { ScaledWidth = Convert.ToUInt32(decoder.PixelWidth), ScaledHeight = Convert.ToUInt32(decoder.PixelHeight) }; PixelDataProvider pixelData = await decoder.GetPixelDataAsync( BitmapPixelFormat.Bgra8, // WriteableBitmap uses BGRA format BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation, // This sample ignores Exif orientation ColorManagementMode.DoNotColorManage ); // An array containing the decoded image data, which could be modified before being displayed byte[] sourcePixels = pixelData.DetachPixelData(); // Open a stream to copy the image contents to the WriteableBitmap's pixel buffer using (Stream stream = wBitmap.PixelBuffer.AsStream()) { await stream.WriteAsync(sourcePixels, 0, sourcePixels.Length); } await wBitmap.SaveToFile(imageFile, BitmapEncoder.JpegEncoderId); //var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite); //DataWriter writer = new DataWriter(fs.GetOutputStreamAt(0)); //writer.WriteBytes(await x.ReadAsync()); //await writer.StoreAsync(); //writer.DetachStream(); //await fs.FlushAsync(); //StorageFile imgFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(newClip.GetHashCode() + imageExtensions[0], CreationCollisionOption.ReplaceExisting); //byte[] pixels = new byte[4 * bitmap.PixelWidth * bitmap.PixelHeight]; //Stream pixelStream = wBitmap.PixelBuffer.AsStream(); //pixelStream.Seek(0, SeekOrigin.Begin); //pixelStream.Write(pixels, 0, pixels.Length); ////BitmapToWriteableBitmap(imgFile); //await Utilities.SaveToFile(wBitmap, imgFile, new Guid()); ////using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) ////{ //// var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); //// encoder.SetPixelData( //// BitmapPixelFormat.Bgra8, //// BitmapAlphaMode.Ignore, //// (uint)bitmap.PixelWidth, //// (uint)bitmap.PixelHeight, //// 96d, //// 96d, //// bitmap. //// ); ////// await encoder.FlushAsync(); //////} ////if (bitmap != null) ////{ //// IRandomAccessStream stream = await bitmap.OpenAsync(FileAccessMode.Read); //// bmp.SetSource(stream); //// imageGrid.Source = bmp; ////} newClip.UserData.Add("thumb", imageFile.Path); Clips.Add(newClip); RaisePropertyChanged(Utilities.GetMemberName(() => Clips)); MyUri = new Uri(imageFile.Path); } }