private static IntPtr GetHBitmap ( string fileName, int width, int height, ThumbnailOptions options) { IShellItem nativeShellItem; var shellItem2Guid = new Guid(ShellItem2Guid); int retCode = SHCreateItemFromParsingName ( fileName, IntPtr.Zero, ref shellItem2Guid, out nativeShellItem); if (retCode != 0) { throw Marshal.GetExceptionForHR(retCode); } var nativeSize = new NativeSize(); nativeSize.Width = width; nativeSize.Height = height; IntPtr hBitmap; HResult hr = ((IShellItemImageFactory)nativeShellItem).GetImage ( nativeSize, options, out hBitmap); Marshal.ReleaseComObject(nativeShellItem); if (hr == HResult.Ok) { return(hBitmap); } throw Marshal.GetExceptionForHR((int)hr); }
public static Bitmap GetThumbnail(string fileName, int width, int height, ThumbnailOptions options) { if (!File.Exists(fileName) && !Directory.Exists(fileName)) { throw new FileNotFoundException(); } Bitmap clonedBitmap = null; IntPtr hBitmap = new IntPtr(); try { hBitmap = GetHBitmap(Path.GetFullPath(fileName), width, height, options); // Original code returned the bitmap directly: // return GetBitmapFromHBitmap( hBitmap ); // I'm making a clone first, so I can dispose of the original bitmap. // The returned clone should be managed and not need disposing of. (I think...) Bitmap thumbnail = GetBitmapFromHBitmap(hBitmap); clonedBitmap = thumbnail.Clone() as Bitmap; thumbnail.Dispose(); } catch (System.Runtime.InteropServices.COMException ex) { if (ex.ErrorCode == -2147175936 && options.HasFlag(ThumbnailOptions.ThumbnailOnly)) // -2147175936 == 0x8004B200 { clonedBitmap = null; } else { throw; } } finally { // delete HBitmap to avoid memory leaks DeleteObject(hBitmap); } return(clonedBitmap); }
private async Task ShowThumbnail(StorageFolder storageFolder) { // 如果要获取文件夹的缩略图,就指定为 ThumbnailMode.SingleItem 即可 // 空文件夹会返回空文件夹缩略图,包含文件的文件夹会返回那种内含文件缩略图的文件夹缩略图 ThumbnailMode thumbnailMode = ThumbnailMode.SingleItem; uint requestedSize = 200; ThumbnailOptions thumbnailOptions = ThumbnailOptions.UseCurrentScale; using (StorageItemThumbnail thumbnail = await storageFolder.GetThumbnailAsync(thumbnailMode, requestedSize, thumbnailOptions)) { if (thumbnail != null) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(thumbnail); imageThumbnail.Source = bitmapImage; lblMsg.Text = $"thumbnail1 requestedSize:{requestedSize}, returnedSize:{thumbnail.OriginalWidth}x{thumbnail.OriginalHeight}, size:{thumbnail.Size}"; } } }
public static Bitmap GetThumbnail(string fileName, int width, int height, ThumbnailOptions options) { var hBitmap = GetHBitmap(Path.GetFullPath(fileName), width, height, options); if (hBitmap == IntPtr.Zero) { return(null); } try { // return a System.Drawing.Bitmap from the hBitmap return(GetBitmapFromHBitmap(hBitmap)); } finally { // delete HBitmap to avoid memory leaks DeleteObject(hBitmap); } }
private static IntPtr GetHBitmap(string fileName, int width, int height, ThumbnailOptions options) { IShellItem nativeShellItem; Guid shellItem2Guid = new Guid(IShellItem2Guid); int retCode; if (fileName != null && fileName.Length > 2 && fileName[0] == ':') { // handle PIDL of syntax :123456789 IntPtr pidl = (IntPtr)int.Parse(fileName.Substring(1)); retCode = SHCreateItemFromIDList(pidl, ref shellItem2Guid, out nativeShellItem); } else { // Normal file/directory path retCode = SHCreateItemFromParsingName(Path.GetFullPath(fileName), IntPtr.Zero, ref shellItem2Guid, out nativeShellItem); } if (retCode != 0) { throw Marshal.GetExceptionForHR(retCode); } NativeSize nativeSize = new NativeSize(); nativeSize.Width = width; nativeSize.Height = height; IntPtr hBitmap; HResult hr = ((IShellItemImageFactory)nativeShellItem).GetImage(nativeSize, options, out hBitmap); Marshal.ReleaseComObject(nativeShellItem); if (hr == HResult.Ok) { return(hBitmap); } throw Marshal.GetExceptionForHR((int)hr); }
public static BitmapSource GetIcon(string fileName, int width, int height, ThumbnailOptions options) { // SHFILEINFO _SHFILEINFO = new SHFILEINFO(); // IntPtr _IconIntPtr = SHGetFileInfo(fileName, 0, ref _SHFILEINFO, (uint)Marshal.SizeOf(_SHFILEINFO), (uint)(SHGFI.SHGFI_ICON | SHGFI.SHGFI_LARGEICON | SHGFI.SHGFI_USEFILEATTRIBUTES)); // if (_IconIntPtr.Equals(IntPtr.Zero)) return null; var _Icon = Icon.ExtractAssociatedIcon(fileName); var hBitmap = _Icon.ToBitmap().GetHbitmap(); try { return(Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())); } finally { // delete HBitmap to avoid memory leaks DeleteObject(hBitmap); } }
private static IntPtr GetHBitmap(string fileName, int width, int height, ThumbnailOptions options) { var shellItem2Guid = new Guid(IShellItem2Guid); var retCode = SHCreateItemFromParsingName(fileName, IntPtr.Zero, ref shellItem2Guid, out var nativeShellItem); if (retCode != 0) { throw Marshal.GetExceptionForHR(retCode); } var nativeSize = new NativeSize { Width = width, Height = height }; var hr = ((IShellItemImageFactory)nativeShellItem).GetImage(nativeSize, options, out var hBitmap); Marshal.ReleaseComObject(nativeShellItem); return(hr == HResult.Ok ? hBitmap : IntPtr.Zero); }
private static IntPtr GetHBitmap(string fileName, int width, int height, ThumbnailOptions options) { IShellItem nativeShellItem; var shellItem2Guid = new Guid(IShellItem2Guid); var retCode = SHCreateItemFromParsingName(fileName, IntPtr.Zero, ref shellItem2Guid, out nativeShellItem); if (retCode != 0) { throw Marshal.GetExceptionForHR(retCode); } var nativeSize = new NativeSize { Width = width, Height = height }; IntPtr hBitmap; var hr = ((IShellItemImageFactory)nativeShellItem).GetImage(nativeSize, options, out hBitmap); // if extracting image thumbnail and failed, extract shell icon if (options == ThumbnailOptions.ThumbnailOnly && hr == HResult.ExtractionFailed) { hr = ((IShellItemImageFactory)nativeShellItem).GetImage(nativeSize, ThumbnailOptions.None, out hBitmap); } Marshal.ReleaseComObject(nativeShellItem); if (hr == HResult.Ok) { return(hBitmap); } throw new COMException($"Error while extracting thumbnail for {fileName}", Marshal.GetExceptionForHR((int)hr)); }
public BitmapSource GetThumbnail(string fileName) { var thumbSizePixels = GetThumbSizePixels(); var bitmapHandle = IntPtr.Zero; Bitmap bmpThumbnail = null; const ThumbnailOptions options = ThumbnailOptions.BiggerSizeOk | ThumbnailOptions.ResizeToFit; try { bitmapHandle = GetBitmapHandle(Path.GetFullPath(fileName), thumbSizePixels, options); bmpThumbnail = GetBitmapFromHandle(bitmapHandle); } catch (Exception e) { Log.Instance.Error("Cannot retrieve thumbnail " + e.Message); } finally { // Delete HBitmap to avoid memory leaks. WinApiFunctions.DeleteObject(bitmapHandle); } return(bmpThumbnail == null ? null : bmpThumbnail.ToBitmapSource()); }
public static string GetThumbnail(ThumbnailOptions options) { return(options.Serialize()); }
public static BitmapSource GetThumbnail(string fileName, int width, int height, ThumbnailOptions options) { IntPtr hBitmap = GetHBitmap(Path.GetFullPath(fileName), width, height, options); try { return(Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())); } finally { // delete HBitmap to avoid memory leaks DeleteObject(hBitmap); } }
public static IntPtr GetThumbnail(IShellItem nativeShellItem, int width, int height, ThumbnailOptions options) { IntPtr hBitmap = GetHBitmap(nativeShellItem, width, height, options); return(hBitmap); }
//to get a collection of music files public async Task <IList <Album> > EnumerateAndGetAlbumsAsync() { string[] fileType = { ".mp3", ".mp4", ".wma" }; QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderByTitle, fileType); queryOptions.FolderDepth = FolderDepth.Deep; var files = await KnownFolders.MusicLibrary.CreateFileQueryWithOptions(queryOptions).GetFilesAsync(); //get thumbnail const uint requestThumbNailSize = 190; const ThumbnailMode thumbnailMode = ThumbnailMode.MusicView; const ThumbnailOptions thumbnailOptions = ThumbnailOptions.UseCurrentScale; foreach (var file in files) { MusicProperties musicProperties = await file.Properties.GetMusicPropertiesAsync(); BasicProperties basicProperties = await file.GetBasicPropertiesAsync(); var thumbnail = await file.GetThumbnailAsync(thumbnailMode, requestThumbNailSize, thumbnailOptions); //Get ThumbNail // Create a new Song object, add it to the album object created above. Song song = new Song() { Title = musicProperties.Title, Artist = musicProperties.Artist, Size = basicProperties.Size, FilePath = file.Path, AlbumName = musicProperties.Album, Duration = musicProperties.Duration, //ImagePath = musicProperties. }; //Album does not exist in the colleciotn if (!albumCollection.ContainsKey(musicProperties.Album.ToLower())) { // Create a new Alubum - new Album() Album album = new Album() { Name = musicProperties.Album, ArtistName = musicProperties.AlbumArtist, //FolderPath = }; //Add song object to Album album.AddSong(song); //Add song to the songs collection if (!songsCollection.ContainsKey(song.FilePath)) { songsCollection.Add(song.FilePath, song); } // Then, add album to the colleciton albumCollection.Add(album.Name.ToLower(), album); } else // Album exists in the collection { // Get a alumbum object from the collection using album name as key var album = albumCollection[musicProperties.Album.ToLower()]; // Create a new Song object, add it to the alubum object obtained above. album.AddSong(song); //Add song to the songs collection if (!songsCollection.ContainsKey(song.FilePath)) { songsCollection.Add(song.FilePath, song); } } } IsMusicScanned = true; return(albumCollection.Values.ToList <Album>()); }
public abstract IAsyncOperation <StorageItemThumbnail> GetThumbnailAsync(ThumbnailMode mode, uint requestedSize, ThumbnailOptions options);
public static BitmapSource GetThumbnailSource(string fileName, int width, int height, ThumbnailOptions options, CancellationToken?token = null) { if (token != null && token.Value.IsCancellationRequested) { return(null); } var bitmap = GetThumbnail(fileName, width, height, options); var bitmapSource = Convert(bitmap); bitmapSource.Freeze(); return(bitmapSource); }
/// <summary> /// Retrieves an adjusted thumbnail image for the file, determined by the /// purpose of the thumbnail, the requested size, and the specified /// options. /// </summary> /// <param name="mode">The enum value that describes the purpose of the thumbnail and determines how the thumbnail image is adjusted.</param> /// <param name="requestedSize">The requested size, in pixels, of the longest edge of the thumbnail. Windows uses the requestedSize as a guide and tries to scale the thumbnail image without reducing the quality of the image.</param> /// <param name="options">The enum value that describes the desired behavior to use to retrieve the thumbnail image. The specified behavior might affect the size and/or quality of the image and how quickly the thumbnail image is retrieved.</param> /// <returns>When this method completes successfully, it returns a StorageItemThumbnail that represents the thumbnail image or null if there is no thumbnail image associated with the file.</returns> public IAsyncOperation<StorageItemThumbnail> GetThumbnailAsync(ThumbnailMode mode, uint requestedSize, ThumbnailOptions options) { throw new NotImplementedException(); }
/// <summary> /// /// </summary> /// <param name="key">whatever system you want... just used for caching</param> /// <param name="document"></param> /// <param name="backgroundColorOfResult">use Color.Transparent if you'll be composing in onto something else</param> /// <param name="drawBorderDashed"></param> /// <returns></returns> public void GetThumbnailAsync(string folderForThumbNailCache, string key, HtmlDom document, ThumbnailOptions options, Action<Image> callback, Action<Exception> errorCallback) { GetThumbnail(folderForThumbNailCache, key, document, options, callback, errorCallback, true); }
/// <summary> /// /// </summary> /// <param name="folderForThumbNailCache"></param> /// <param name="key">whatever system you want... just used for caching</param> /// <param name="document"></param> /// <param name="options"></param> /// <param name="callback"></param> /// <param name="errorCallback"></param> /// <returns></returns> public void GetThumbnailAsync(string folderForThumbNailCache, string key, HtmlDom document, ThumbnailOptions options, Action <Image> callback, Action <Exception> errorCallback) { GetThumbnail(folderForThumbNailCache, key, document, options, callback, errorCallback, true); }
public override IAsyncOperation <StorageItemThumbnail> GetThumbnailAsync(ThumbnailMode mode, uint requestedSize, ThumbnailOptions options) => throw new NotSupportedException();
private Image MakeThumbNail(Image bmp, ThumbnailOptions options) { if (bmp == null) return null; int contentWidth; int contentHeight; #if !__MonoCS__ int horizontalOffset = 0; int verticalOffset = 0; int thumbnailWidth = options.Width; int thumbnailHeight = options.Height; #endif //unfortunately as long as we're using the winform listview, we seem to need to make the icons //the same size regardless of the book's shape, otherwise the title-captions don't line up. if (options.CenterImageUsingTransparentPadding) { if (bmp.Width > bmp.Height)//landscape { contentWidth = options.Width; contentHeight = (int)(Math.Ceiling(((float)bmp.Height / (float)bmp.Width) * (float)contentWidth)); } else if (bmp.Width < bmp.Height) //portrait { contentHeight = options.Height; contentWidth = (int) (Math.Ceiling(((float) bmp.Width/(float) bmp.Height)*(float) contentHeight)); } else //square page { contentWidth = options.Width; contentHeight = options.Height; } #if !__MonoCS__ horizontalOffset = (options.Width / 2) - (contentWidth / 2); verticalOffset = (options.Height / 2) - (contentHeight / 2); #endif } else { contentHeight = options.Height; contentWidth = (int)Math.Floor((float)options.Height * (float)bmp.Width / (float)bmp.Height); #if !__MonoCS__ thumbnailHeight = contentHeight; thumbnailWidth = contentWidth; #endif } #if !__MonoCS__ var thumbnail = new Bitmap(thumbnailWidth, thumbnailHeight, PixelFormat.Format64bppPArgb); using (var graphics = Graphics.FromImage(thumbnail)) { graphics.PixelOffsetMode = PixelOffsetMode.None; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; var destRect = new Rectangle(horizontalOffset, verticalOffset, contentWidth,contentHeight); graphics.DrawImage(bmp, destRect, 0,0, bmp.Width, bmp.Height, //source GraphicsUnit.Pixel, WhiteToBackground); if (options.BorderStyle != ThumbnailOptions.BorderStyles.None) { using (var pn = new Pen(Color.Black, 1)) { if (options.BorderStyle == ThumbnailOptions.BorderStyles.Dashed) { pn.DashStyle = DashStyle.Dash; pn.Width = 2; } destRect.Height--; //hack, we were losing the bottom destRect.Width--; graphics.DrawRectangle(pn, destRect); } } } return thumbnail; #else int skipMarginH = 30; int skipMarginV = 30; Bitmap croppedImage = (bmp as Bitmap).Clone(new Rectangle(new Point(skipMarginH, skipMarginV), new Size(bmp.Width - 2 * skipMarginH, bmp.Height - 2 * skipMarginV)), bmp.PixelFormat); return croppedImage.GetThumbnailImage(contentWidth, contentHeight, null, IntPtr.Zero); #endif }
public static async Task <Stream> GetPhotoThumbnailAsync(StorageFile file, ThumbnailMode mode, uint requestedSize, ThumbnailOptions options) { if (file == null) { return(null); } try { var thumbnail = await file.GetThumbnailAsync(mode, requestedSize, options); if (thumbnail != null) { return(thumbnail.AsStream()); } } catch (Exception ex) { Log.Write(ex.ToString()); } try { var stream = await file.OpenReadAsync(); var photo = await ResizeJpeg(stream, 99 * 2, null, null); if (photo != null && photo.Bytes != null) { return(new MemoryStream(photo.Bytes)); } } catch (Exception ex) { Log.Write(ex.ToString()); } return(null); }
public async static Task <StorageItemThumbnail> ConvertToThumbnailAsync(this StorageFile file, uint requestedSize = 300, ThumbnailMode mode = ThumbnailMode.SingleItem, ThumbnailOptions thumbnailOptions = ThumbnailOptions.UseCurrentScale) { return(await file.GetThumbnailAsync(mode, requestedSize, thumbnailOptions).AsTask().ConfigureAwait(false)); }
public static ImageSource SaveThumbnail(ThumbnailOptions options) { // Make sure this method runs in the UI thread. if (!Deployment.Current.Dispatcher.CheckAccess()) { return Deployment.Current.Dispatcher.Invoke<ImageSource>(() => { return SaveThumbnail(options); }); } // Gets the images. WriteableBitmap preferedImage = GetBitmapSource(options.PreferedMedia); WriteableBitmap fallbackImage = GetBitmapSource(options.FallbackMedia); // Determines which image needs to be saved. WriteableBitmap targetImage = preferedImage; if (preferedImage == null) { // Use the fallback image if the prefered image does not exist. targetImage = fallbackImage; } else if (fallbackImage != null && options.MinWidth > -1 && preferedImage.PixelWidth < options.MinWidth && preferedImage.PixelWidth < fallbackImage.PixelWidth) { // Use the fallback image if its width is bigger than the prefered image's width, the latter being // smaller than the min width. targetImage = fallbackImage; } // No image? Return. if (targetImage == null) { return null; } // Gets the dimensions of the target image. int targetWidth = (int) Math.Max(options.MinWidth, targetImage.PixelWidth); double sourcePixelRatio = targetImage.PixelWidth / (double) targetImage.PixelHeight; int targetHeight = (int) Math.Floor(targetWidth / sourcePixelRatio); // Blurs the image if needed. ExtendedImage targetExtendedImage = null; if (options.Blur) { // Converts the image to an ImageTools image. targetExtendedImage = targetImage.ToImage(); // Resizes the image if it can help decreasing the time needed to blur it. // The image is only resized if the target size is less than the original size. // Otherwise it means that the original image is smaller than the target size, in which case we blur it // as it is and let WP scale up the blurred image later. if (targetExtendedImage.PixelHeight * targetExtendedImage.PixelWidth > targetWidth * targetHeight) { targetExtendedImage = ExtendedImage.Resize(targetExtendedImage, targetWidth, targetHeight, new ImageTools.Filtering.NearestNeighborResizer()); } // Inits the blur filter if needed and runs it. if (_gaussianBlurFilter == null) { _gaussianBlurFilter = new ImageTools.Filtering.GaussianBlur() { Variance = 2d }; } targetExtendedImage = ExtendedImage.ApplyFilters(targetExtendedImage, _gaussianBlurFilter); } // Crops the image if needed. if (options.CropRectangle.HasValue) { if (targetExtendedImage == null) { // Converts the image to an ImageTools image. targetExtendedImage = targetImage.ToImage(); } // Computes the downscaled crop rectangle. // We're downscaling the crop rectangle instead of upscaling the image and then cropping it, // in order to save some time. // WP will upscale the cropped image later on. int conformedCropWidth = Math.Min(options.CropRectangle.Value.Width, targetWidth); int conformedCropHeight = Math.Min(options.CropRectangle.Value.Height, targetHeight); double scaleFactor = (double)targetExtendedImage.PixelWidth / (double)targetWidth; Rectangle crop = options.CropRectangle.Value; crop.Width = (int)(conformedCropWidth * scaleFactor); crop.Height = (int)(conformedCropHeight * scaleFactor); crop.X = (int)((double)crop.X * scaleFactor); crop.Y = (int)((double)crop.Y * scaleFactor); // Crops the image. if (crop.Width > 0 && crop.Height > 0) { targetExtendedImage = ExtendedImage.Crop(targetExtendedImage, crop); } // Stores the final dimensions of the image for later scaling. targetWidth = conformedCropWidth; targetHeight = conformedCropHeight; } if (targetExtendedImage != null) { targetImage = targetExtendedImage.ToBitmap(); } // Saves the image. try { if (targetWidth > 0 && targetHeight > 0) { using (IsolatedStorageFileStream stream = options.IsoStoreFile.OpenFile(options.Filename, FileMode.Create, FileAccess.ReadWrite)) { targetImage.SaveJpeg(stream, targetWidth, targetHeight, 0, 100); } } } catch (IsolatedStorageException ex) { // Nothing to do, let's just dump this for further analysis. DebugUtils.DumpException(ex, string.Format("OpenFile(f:{0})", options.Filename), true); } catch (ArgumentException ex) { // Nothing to do, let's just dump this for further analysis. DebugUtils.DumpException(ex, string.Format("SaveJpeg(w:{0},h:{1})", targetWidth, targetHeight), true); } // Returns the image. return targetImage; }
public static Bitmap GetThumbnail(this FileInfo file, Size size, ThumbnailOptions options = ThumbnailOptions.ThumbnailOnly) { return(WindowsThumbnailProvider.GetThumbnail(file.FullName, size.Width, size.Height, options)); }
static Rect PDF_PORTION_RECT = new Rect(100, 100, 300, 400); //portion of a page public static async Task <Images> GetFileListWithBitmapImages(List <string> fileTypes, bool loadFilesFromLocalFolder = false, List <string> fileListToLoad = null) { Images imagecollection = new Images(); //ObservableCollection<List<ImageSource>> ListImageDisplay = new ObservableCollection<List<ImageSource>>(); IReadOnlyList <StorageFile> files = null; if (!loadFilesFromLocalFolder) //Open file picker. { FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode = PickerViewMode.List; openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; foreach (string fileType in fileTypes) { openPicker.FileTypeFilter.Add(fileType); } files = await openPicker.PickMultipleFilesAsync(); } else //Load files from local folder { if (fileListToLoad != null) { foreach (string filePath in fileListToLoad) { var uri = new System.Uri(filePath);// ("ms-appx:///images/logo.png"); var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri); List <StorageFile> filesLocal = new List <StorageFile>(); filesLocal.Add(file); files = filesLocal; } } } if (files != null && files.Count > 0) { StringBuilder output = new StringBuilder("Picked files:\n"); // Application now has read/write access to the picked file(s) foreach (StorageFile file in files) { output.Append(file.Name + "\n"); bool fastThumbnail = false; ThumbnailOptions thumbnailOptions = ThumbnailOptions.ResizeThumbnail; if (fastThumbnail) { thumbnailOptions |= ThumbnailOptions.ReturnOnlyIfCached; } const uint size = 500; using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(ThumbnailMode.SingleItem, size)) { if (thumbnail != null) { List <ImageSource> bitmapImageList = null; ImageProperties imgProp = await file.Properties.GetImagePropertiesAsync(); if (file.FileType.ToLower() == ".pdf") { DocumentProperties docProp = await file.Properties.GetDocumentPropertiesAsync(); Images image = await LoadPDFBitmapImage(file, RENDEROPTIONS.NORMAL); imagecollection.ListImageDisplay.Add(image.ListImageDisplay[0]); imagecollection.ListWriteImages.Add(image.ListWriteImages[0]); //image.ListWriteImages.Add() } else { bitmapImageList = new List <ImageSource>(); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(thumbnail); bitmapImageList.Add(bitmapImage); using (var imgStream = await file.OpenAsync(FileAccessMode.Read)) { List <WriteableBitmap> lstwriteable = new List <WriteableBitmap>(); WriteableBitmap bitmap = new WriteableBitmap((int)imgProp.Width, (int)imgProp.Height); bitmap.SetSource(imgStream); lstwriteable.Add(bitmap); imagecollection.ListWriteImages.Add(lstwriteable); } imagecollection.ListImageDisplay.Add(bitmapImageList); } //ListImageDisplay.Add(bitmapImageList); } } } } else { } return(imagecollection); }
private Image MakeThumbNail(Image bmp, ThumbnailOptions options) { if (bmp == null) { return(null); } int contentWidth; int contentHeight; #if !__MonoCS__ int horizontalOffset = 0; int verticalOffset = 0; int thumbnailWidth = options.Width; int thumbnailHeight = options.Height; #endif //unfortunately as long as we're using the winform listview, we seem to need to make the icons //the same size regardless of the book's shape, otherwise the title-captions don't line up. if (options.CenterImageUsingTransparentPadding) { if (bmp.Width > bmp.Height) //landscape { contentWidth = options.Width; contentHeight = (int)(Math.Ceiling(((float)bmp.Height / (float)bmp.Width) * (float)contentWidth)); } else if (bmp.Width < bmp.Height) //portrait { contentHeight = options.Height; contentWidth = (int)(Math.Ceiling(((float)bmp.Width / (float)bmp.Height) * (float)contentHeight)); } else //square page { contentWidth = options.Width; contentHeight = options.Height; } #if !__MonoCS__ horizontalOffset = (options.Width / 2) - (contentWidth / 2); verticalOffset = (options.Height / 2) - (contentHeight / 2); #endif } else { contentHeight = options.Height; contentWidth = (int)Math.Floor((float)options.Height * (float)bmp.Width / (float)bmp.Height); #if !__MonoCS__ thumbnailHeight = contentHeight; thumbnailWidth = contentWidth; #endif } #if !__MonoCS__ var thumbnail = new Bitmap(thumbnailWidth, thumbnailHeight, PixelFormat.Format64bppPArgb); using (var graphics = Graphics.FromImage(thumbnail)) { graphics.PixelOffsetMode = PixelOffsetMode.None; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; var destRect = new Rectangle(horizontalOffset, verticalOffset, contentWidth, contentHeight); graphics.DrawImage(bmp, destRect, 0, 0, bmp.Width, bmp.Height, //source GraphicsUnit.Pixel, WhiteToBackground); using (var pn = new Pen(Color.Black, 1)) { if (options.DrawBorderDashed) { pn.DashStyle = DashStyle.Dash; pn.Width = 2; } destRect.Height--; //hack, we were losing the bottom destRect.Width--; graphics.DrawRectangle(pn, destRect); } } return(thumbnail); #else int skipMarginH = 30; int skipMarginV = 30; Bitmap croppedImage = (bmp as Bitmap).Clone(new Rectangle(new Point(skipMarginH, skipMarginV), new Size(bmp.Width - 2 * skipMarginH, bmp.Height - 2 * skipMarginV)), bmp.PixelFormat); return(croppedImage.GetThumbnailImage(contentWidth, contentHeight, null, IntPtr.Zero)); #endif }
public override IAsyncOperation <StorageItemThumbnail> GetThumbnailAsync(ThumbnailMode mode, uint requestedSize, ThumbnailOptions options) { return(File.GetThumbnailAsync(mode, requestedSize, options)); }
/// <summary> /// /// </summary> /// <param name="key">whatever system you want... just used for caching</param> /// <param name="document"></param> /// <param name="backgroundColorOfResult">use Color.Transparent if you'll be composing in onto something else</param> /// <param name="drawBorderDashed"></param> /// <returns></returns> public void GetThumbnail(string folderForThumbNailCache, string key, HtmlDom document, ThumbnailOptions options, Action<Image> callback, Action<Exception> errorCallback, bool async) { //review: old code had it using "key" in one place(checking for existing), thumbNailFilePath in another (adding new) string thumbNailFilePath = null; if (!string.IsNullOrEmpty(folderForThumbNailCache)) thumbNailFilePath = Path.Combine(folderForThumbNailCache, options.FileName); //In our cache? Image image; if (!String.IsNullOrWhiteSpace(key) && _images.TryGetValue(key, out image)) { callback(image); return; } //Sitting on disk? if (!string.IsNullOrEmpty(folderForThumbNailCache)) { if (RobustFile.Exists(thumbNailFilePath)) { var thumbnail = ImageUtils.GetImageFromFile(thumbNailFilePath); thumbnail.Tag = thumbNailFilePath; if (!String.IsNullOrWhiteSpace(key)) _images.Add(key, thumbnail); callback(thumbnail); return; } } var order = new ThumbnailOrder() { ThumbNailFilePath = thumbNailFilePath, Options = options, Callback = callback, ErrorCallback = errorCallback, Document = document, FolderForThumbNailCache = folderForThumbNailCache, Key = key }; if (async) QueueOrder(order); else { ProcessOrder(order); } }
public async void MemoryFriendlyGetItemsAsync(string path, Page passedPage) { TextState.isVisible = Visibility.Collapsed; tokenSource = new CancellationTokenSource(); CancellationToken token = App.ViewModel.tokenSource.Token; pageName = passedPage.Name; Universal.path = path; // Personalize retrieved items for view they are displayed in switch (pageName) { case "GenericItemView": isPhotoAlbumMode = false; break; case "PhotoAlbumViewer": isPhotoAlbumMode = true; break; case "ClassicModePage": isPhotoAlbumMode = false; break; } if (pageName != "ClassicModePage") { FilesAndFolders.Clear(); } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Universal.path = path; // Set visible path to reflect new navigation try { PVIS.isVisible = Visibility.Visible; TextState.isVisible = Visibility.Collapsed; switch (Universal.path) { case "Desktop": Universal.path = MainPage.DesktopPath; break; case "Downloads": Universal.path = MainPage.DownloadsPath; break; case "Documents": Universal.path = MainPage.DocumentsPath; break; case "Pictures": Universal.path = MainPage.PicturesPath; break; case "Music": Universal.path = MainPage.MusicPath; break; case "Videos": Universal.path = MainPage.VideosPath; break; case "OneDrive": Universal.path = MainPage.OneDrivePath; break; } folder = await StorageFolder.GetFolderFromPathAsync(Universal.path); History.AddToHistory(Universal.path); if (History.HistoryList.Count == 1) { BS.isEnabled = false; } else if (History.HistoryList.Count > 1) { BS.isEnabled = true; } QueryOptions options = new QueryOptions() { FolderDepth = FolderDepth.Shallow, IndexerOption = IndexerOption.UseIndexerWhenAvailable }; string sort = "By_Name"; if (sort == "By_Name") { SortEntry entry = new SortEntry() { AscendingOrder = true, PropertyName = "System.FileName" }; options.SortOrder.Add(entry); } uint index = 0; const uint step = 250; if (!folder.AreQueryOptionsSupported(options)) { options.SortOrder.Clear(); } folderQueryResult = folder.CreateFolderQueryWithOptions(options); IReadOnlyList <StorageFolder> folders = await folderQueryResult.GetFoldersAsync(index, step); int foldersCountSnapshot = folders.Count; while (folders.Count != 0) { foreach (StorageFolder folder in folders) { if (token.IsCancellationRequested) { return; } gotFolName = folder.Name.ToString(); gotFolDate = folder.DateCreated.ToString(); gotFolPath = folder.Path.ToString(); gotFolType = "Folder"; gotFolImg = Visibility.Visible; gotFileImgVis = Visibility.Collapsed; gotEmptyImgVis = Visibility.Collapsed; if (pageName == "ClassicModePage") { ClassicFolderList.Add(new Classic_ListedFolderItem() { FileName = gotFolName, FileDate = gotFolDate, FileExtension = gotFolType, FilePath = gotFolPath }); } else { FilesAndFolders.Add(new ListedItem() { EmptyImgVis = gotEmptyImgVis, ItemIndex = FilesAndFolders.Count, FileImg = null, FileIconVis = gotFileImgVis, FolderImg = gotFolImg, FileName = gotFolName, FileDate = gotFolDate, FileExtension = gotFolType, FilePath = gotFolPath }); } } index += step; folders = await folderQueryResult.GetFoldersAsync(index, step); } index = 0; fileQueryResult = folder.CreateFileQueryWithOptions(options); IReadOnlyList <StorageFile> files = await fileQueryResult.GetFilesAsync(index, step); int filesCountSnapshot = files.Count; while (files.Count != 0) { foreach (StorageFile file in files) { if (token.IsCancellationRequested) { return; } gotName = file.DisplayName.ToString(); gotDate = file.DateCreated.ToString(); // In the future, parse date to human readable format if (file.FileType.ToString() == ".exe") { gotType = "Executable"; } else { gotType = file.DisplayType; } gotPath = file.Path.ToString(); gotFolImg = Visibility.Collapsed; gotDotFileExtension = file.FileType; if (isPhotoAlbumMode == false) { const uint requestedSize = 20; const ThumbnailMode thumbnailMode = ThumbnailMode.ListView; const ThumbnailOptions thumbnailOptions = ThumbnailOptions.UseCurrentScale; try { gotFileImg = await file.GetThumbnailAsync(thumbnailMode, requestedSize, thumbnailOptions); BitmapImage icon = new BitmapImage(); if (gotFileImg != null) { gotEmptyImgVis = Visibility.Collapsed; icon.SetSource(gotFileImg.CloneStream()); } else { gotEmptyImgVis = Visibility.Visible; } gotFileImgVis = Visibility.Visible; if (pageName == "ClassicModePage") { ClassicFileList.Add(new ListedItem() { FileImg = icon, FileIconVis = gotFileImgVis, FolderImg = gotFolImg, FileName = gotName, FileDate = gotDate, FileExtension = gotType, FilePath = gotPath }); } else { FilesAndFolders.Add(new ListedItem() { DotFileExtension = gotDotFileExtension, EmptyImgVis = gotEmptyImgVis, FileImg = icon, FileIconVis = gotFileImgVis, FolderImg = gotFolImg, FileName = gotName, FileDate = gotDate, FileExtension = gotType, FilePath = gotPath }); } } catch { // Silent catch here to avoid crash // TODO maybe some logging could be added in the future... } } else { const uint requestedSize = 275; const ThumbnailMode thumbnailMode = ThumbnailMode.PicturesView; const ThumbnailOptions thumbnailOptions = ThumbnailOptions.ResizeThumbnail; try { gotFileImg = await file.GetThumbnailAsync(thumbnailMode, requestedSize, thumbnailOptions); BitmapImage icon = new BitmapImage(); if (gotFileImg != null) { gotEmptyImgVis = Visibility.Collapsed; icon.SetSource(gotFileImg.CloneStream()); } else { gotEmptyImgVis = Visibility.Visible; } gotFileImgVis = Visibility.Visible; if (pageName == "ClassicModePage") { ClassicFileList.Add(new ListedItem() { FileImg = icon, FileIconVis = gotFileImgVis, FolderImg = gotFolImg, FileName = gotName, FileDate = gotDate, FileExtension = gotType, FilePath = gotPath }); } else { FilesAndFolders.Add(new ListedItem() { DotFileExtension = gotDotFileExtension, EmptyImgVis = gotEmptyImgVis, FileImg = icon, FileIconVis = gotFileImgVis, FolderImg = gotFolImg, FileName = gotName, FileDate = gotDate, FileExtension = gotType, FilePath = gotPath }); } } catch { // Silent catch here to avoid crash // TODO maybe some logging could be added in the future... } } } index += step; files = await fileQueryResult.GetFilesAsync(index, step); } if (foldersCountSnapshot + filesCountSnapshot == 0) { TextState.isVisible = Visibility.Visible; } if (pageName != "ClassicModePage") { PVIS.isVisible = Visibility.Collapsed; } PVIS.isVisible = Visibility.Collapsed; stopwatch.Stop(); Debug.WriteLine("Loading of: " + path + " completed in " + stopwatch.ElapsedMilliseconds + " Milliseconds."); } catch (UnauthorizedAccessException e) { if (path.Contains(@"C:\")) { DisplayConsentDialog(); } else { MessageDialog unsupportedDevice = new MessageDialog("This device may be unsupported. Please file an issue report in Settings - About containing what device we couldn't access. Technical information: " + e, "Unsupported Device"); await unsupportedDevice.ShowAsync(); } stopwatch.Stop(); Debug.WriteLine("Loading of: " + Universal.path + " failed in " + stopwatch.ElapsedMilliseconds + " Milliseconds."); } catch (COMException e) { stopwatch.Stop(); Debug.WriteLine("Loading of: " + Universal.path + " failed in " + stopwatch.ElapsedMilliseconds + " Milliseconds."); Frame rootFrame = Window.Current.Content as Frame; MessageDialog driveGone = new MessageDialog(e.Message, "Drive Unplugged"); await driveGone.ShowAsync(); rootFrame.Navigate(typeof(MainPage), new SuppressNavigationTransitionInfo()); } tokenSource = null; }
/// <summary> /// A synchronous version of getting thumbnails, currently used by the image server /// to get thumbnails that are used in the add page dialog. /// </summary> /// <param name="key">Used to retrieve the thumbnail from a dictionary if we are asked for /// the same one repeatedly</param> /// <param name="document">Whose rendering will produce the thumbnail content.</param> /// <param name="options"></param> /// <returns></returns> public Image GetThumbnail(string key, HtmlDom document, ThumbnailOptions options) { Image image; Image thumbnail = null; lock (this) { //In our cache? if (!String.IsNullOrWhiteSpace(key) && _images.TryGetValue(key, out image)) { Debug.WriteLine("Thumbnail Cache HIT: "+ key + " thread=" + Thread.CurrentThread.ManagedThreadId); return image; } Debug.WriteLine("Thumbnail Cache MISS: " + key + " thread=" + Thread.CurrentThread.ManagedThreadId); _backgroundColorOfResult = options.BackgroundColor; XmlHtmlConverter.MakeXmlishTagsSafeForInterpretationAsHtml(document.RawDom); var browser = GetBrowserForPaperSize(document.RawDom); if (browser == null) return Resources.PagePlaceHolder; var order = new ThumbnailOrder() { Options = options, Document = document }; for (int i = 0; i < 4; i++) { if (CreateThumbNail(order, browser, out thumbnail)) break; // For some reason...possibly another navigation was in progress...we can't do this just now. // Try a few times. } if (thumbnail == null) // just can't get it. { return Resources.PagePlaceHolder; // but don't save it...try again if we get another request. } if (!String.IsNullOrWhiteSpace(key)) _images[key] = thumbnail; } return thumbnail; }
/* * [StructLayout(LayoutKind.Sequential)] * public struct RGBQUAD { * public byte rgbBlue; * public byte rgbGreen; * public byte rgbRed; * public byte rgbReserved; * } */ /* * public static Bitmap GetThumbnail(string fileName, int width, int height, ThumbnailOptions options) { * IntPtr hBitmap = GetHBitmap(Path.GetFullPath(fileName), width, height, options); * * try { * // return a System.Drawing.Bitmap from the hBitmap * return GetBitmapFromHBitmap(hBitmap); * } finally { * // delete HBitmap to avoid memory leaks * DeleteObject(hBitmap); * } * } */ public static IntPtr GetThumbnail(IntPtr pidl, int width, int height, ThumbnailOptions options) { IntPtr hBitmap = GetHBitmap(pidl, width, height, options); return(hBitmap); }
private static IntPtr GetHBitmap(string fileName, int width, int height, ThumbnailOptions options) { IShellItem nativeShellItem; Guid shellItem2Guid = new Guid(IShellItem2Guid); int retCode = SHCreateItemFromParsingName(fileName, IntPtr.Zero, ref shellItem2Guid, out nativeShellItem); if (retCode != 0) throw Marshal.GetExceptionForHR(retCode); NativeSize nativeSize = new NativeSize(); nativeSize.Width = width; nativeSize.Height = height; IntPtr hBitmap; HResult hr = ((IShellItemImageFactory)nativeShellItem).GetImage(nativeSize, options, out hBitmap); Marshal.ReleaseComObject(nativeShellItem); if (hr == HResult.Ok) return hBitmap; throw Marshal.GetExceptionForHR((int)hr); }
private static IntPtr GetHBitmap(IShellItem nativeShellItem, int width, int height, ThumbnailOptions options) { NativeSize nativeSize = new NativeSize(); nativeSize.Width = width; nativeSize.Height = height; IntPtr hBitmap; HResult hr = ((IShellItemImageFactory)nativeShellItem).GetImage(nativeSize, options, out hBitmap); Marshal.ReleaseComObject(nativeShellItem); if (hr == HResult.Ok) { return(hBitmap); } return(IntPtr.Zero); }
public async void GetItemsAsync(string path) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); IsTerminated = false; PUIP.Path = path; try { folder = await StorageFolder.GetFolderFromPathAsync(path); // Set location to the current directory specified in path folderList = await folder.GetFoldersAsync(); // Create a read-only list of all folders in location fileList = await folder.GetFilesAsync(); // Create a read-only list of all files in location NumOfFolders = folderList.Count; // How many folders are in the list NumOfFiles = fileList.Count; // How many files are in the list NumOfItems = NumOfFiles + NumOfFolders; NumItemsRead = 0; if (NumOfItems == 0) { TextState.isVisible = Visibility.Visible; } PUIH.Header = "Loading " + NumOfItems + " items"; ButtonText.buttonText = "Hide"; if (NumOfItems >= 250) { PVIS.isVisible = Visibility.Visible; } if (NumOfFolders > 0) { foreach (StorageFolder fol in folderList) { if (IsStopRequested) { IsStopRequested = false; IsTerminated = true; return; } int ProgressReported = (NumItemsRead * 100 / NumOfItems); UpdateProgUI(ProgressReported); gotFolName = fol.Name.ToString(); gotFolDate = fol.DateCreated.ToString(); gotFolPath = fol.Path.ToString(); gotFolType = "Folder"; gotFolImg = Visibility.Visible; gotFileImgVis = Visibility.Collapsed; if (pageName == "ClassicModePage") { ClassicFolderList.Add(new Classic_ListedFolderItem() { FileName = gotFolName, FileDate = gotFolDate, FileExtension = gotFolType, FilePath = gotFolPath }); } else { FilesAndFolders.Add(new ListedItem() { ItemIndex = FilesAndFolders.Count, FileImg = null, FileIconVis = gotFileImgVis, FolderImg = gotFolImg, FileName = gotFolName, FileDate = gotFolDate, FileExtension = gotFolType, FilePath = gotFolPath }); } NumItemsRead++; } } if (NumOfFiles > 0) { foreach (StorageFile f in fileList) { if (IsStopRequested) { IsStopRequested = false; IsTerminated = true; return; } int ProgressReported = (NumItemsRead * 100 / NumOfItems); UpdateProgUI(ProgressReported); gotName = f.Name.ToString(); gotDate = f.DateCreated.ToString(); // In the future, parse date to human readable format if (f.FileType.ToString() == ".exe") { gotType = "Executable"; } else { gotType = f.DisplayType; } gotPath = f.Path.ToString(); gotFolImg = Visibility.Collapsed; if (isPhotoAlbumMode == false) { const uint requestedSize = 20; const ThumbnailMode thumbnailMode = ThumbnailMode.ListView; const ThumbnailOptions thumbnailOptions = ThumbnailOptions.UseCurrentScale; gotFileImg = await f.GetThumbnailAsync(thumbnailMode, requestedSize, thumbnailOptions); } else { const uint requestedSize = 275; const ThumbnailMode thumbnailMode = ThumbnailMode.PicturesView; const ThumbnailOptions thumbnailOptions = ThumbnailOptions.ResizeThumbnail; gotFileImg = await f.GetThumbnailAsync(thumbnailMode, requestedSize, thumbnailOptions); } BitmapImage icon = new BitmapImage(); if (gotFileImg != null) { icon.SetSource(gotFileImg.CloneStream()); } gotFileImgVis = Visibility.Visible; if (pageName == "ClassicModePage") { ClassicFileList.Add(new ListedItem() { FileImg = icon, FileIconVis = gotFileImgVis, FolderImg = gotFolImg, FileName = gotName, FileDate = gotDate, FileExtension = gotType, FilePath = gotPath }); } else { FilesAndFolders.Add(new ListedItem() { FileImg = icon, FileIconVis = gotFileImgVis, FolderImg = gotFolImg, FileName = gotName, FileDate = gotDate, FileExtension = gotType, FilePath = gotPath }); } NumItemsRead++; } } if (pageName != "ClassicModePage") { PVIS.isVisible = Visibility.Collapsed; } IsTerminated = true; } catch (UnauthorizedAccessException) { DisplayConsentDialog(); } stopwatch.Stop(); Debug.WriteLine("Loading of: " + path + " completed in " + stopwatch.ElapsedMilliseconds + " Milliseconds."); }
public static System.Windows.Media.ImageSource GetFileThumbnail(string fileName, int width = 60, int height = 60, ThumbnailOptions options = ThumbnailOptions.IconOnly) { try { Bitmap bitmap = GetThumbnail(fileName, width, height, options); var source = ImageDeal.BitmapToBitmapSource(bitmap); //_hisOld.Add(value, source); return(source); } catch { try { return(new System.Windows.Media.Imaging.BitmapImage(new Uri(fileName, UriKind.RelativeOrAbsolute))); } catch { return(IMAssets.ImageDeal.DefaultImage); } } //if (File.Exists(fileName)) //{ // using (FileStream file = new FileStream(fileName, FileMode.Open)) // { // var md5 = System.Security.Cryptography.MD5.Create().ComputeHash(file); // string value= BitConverter.ToString(md5); // if (_hisOld.ContainsKey(value)) // { // return _hisOld[value]; // } // else // { // Bitmap bitmap = GetThumbnail(fileName, width, height, options); // var source = ImageDeal.BitmapToBitmapSource(bitmap); // _hisOld.Add(value, source); // return source; // } // } //} //else //{ // return null; //} }
public override IAsyncOperation <StorageItemThumbnail> GetThumbnailAsync(ThumbnailMode mode, uint requestedSize, ThumbnailOptions options) { return(AsyncInfo.Run(async(cancellationToken) => { if (ShellStorageFolder.IsShellPath(Path)) { return null; } var zipFile = await StorageFile.GetFileFromPathAsync(Path); return await zipFile.GetThumbnailAsync(mode, requestedSize, options); })); }
public override IAsyncOperation <StorageItemThumbnail> GetThumbnailAsync(ThumbnailMode mode, uint requestedSize, ThumbnailOptions options) { return(Task.FromResult <StorageItemThumbnail>(null).AsAsyncOperation()); }
public static Bitmap GetThumbnail(string fileName, int width, int height, ThumbnailOptions options) { IntPtr hBitmap = GetHBitmap(Path.GetFullPath(fileName), width, height, options); try { // return a System.Drawing.Bitmap from the hBitmap return GetBitmapFromHBitmap(hBitmap); } finally { // delete HBitmap to avoid memory leaks DeleteObject(hBitmap); } }