在listview控件上动态创建固定大小的缩略图

如何动态创建固定大小的缩略图并在listview中调整图像大小最适合缩略图的大小。

private void Treeview1_AfterSelect(System.Object sender, System.Windows.Forms.TreeViewEventArgs e) { if (folder != null && System.IO.Directory.Exists(folder)) { try { DirectoryInfo dir = new DirectoryInfo(@folder); foreach (FileInfo file in dir.GetFiles()) { try { imageList.ImageSize = new Size(136, 136); imageList.ColorDepth = ColorDepth.Depth32Bit; Image img = new Bitmap(Image.FromFile(file.FullName)); Graphics g = Graphics.FromImage(img); g.DrawRectangle(Pens.Red, 0, 0, img.Width - 21, img.Height - 21); //g.DrawRectangle(Pens.Red, 0, 0, img.Width, img.Height); imageList.Images.Add(img); } catch { Console.WriteLine("This is not an image file"); } } for (int j = 0; j < imageList.Images.Count; j++) { this.ListView1.Items.Add("Item" + j); this.ListView1.Items[j].ImageIndex = j; } this.ListView1.View = View.LargeIcon; this.ListView1.LargeImageList = imageList; //this.ListView1.DrawItem += new DrawListViewItemEventHandler(ListView1_DrawItem); //import(folder); } catch (Exception ex) { } } 

我在这个答案中有代码专门用于调整图像大小和分辨率:

 public void GenerateThumbNail(HttpPostedFile fil, string sPhysicalPath, string sOrgFileName,string sThumbNailFileName, ImageFormat oFormat, int rez) { try { System.Drawing.Image oImg = System.Drawing.Image.FromStream(fil.InputStream); decimal pixtosubstract = 0; decimal percentage; //default Size ThumbNailSizeToUse = new Size(); if (ThumbNailSize.Width < oImg.Size.Width || ThumbNailSize.Height < oImg.Size.Height) { if (oImg.Size.Width > oImg.Size.Height) { percentage = (((decimal)oImg.Size.Width - (decimal)ThumbNailSize.Width) / (decimal)oImg.Size.Width); pixtosubstract = percentage * oImg.Size.Height; ThumbNailSizeToUse.Width = ThumbNailSize.Width; ThumbNailSizeToUse.Height = oImg.Size.Height - (int)pixtosubstract; } else { percentage = (((decimal)oImg.Size.Height - (decimal)ThumbNailSize.Height) / (decimal)oImg.Size.Height); pixtosubstract = percentage * (decimal)oImg.Size.Width; ThumbNailSizeToUse.Height = ThumbNailSize.Height; ThumbNailSizeToUse.Width = oImg.Size.Width - (int)pixtosubstract; } } else { ThumbNailSizeToUse.Width = oImg.Size.Width; ThumbNailSizeToUse.Height = oImg.Size.Height; } Bitmap bmp = new Bitmap(ThumbNailSizeToUse.Width, ThumbNailSizeToUse.Height); bmp.SetResolution(rez, rez); System.Drawing.Image oThumbNail = bmp; bmp = null; Graphics oGraphic = Graphics.FromImage(oThumbNail); oGraphic.CompositingQuality = CompositingQuality.HighQuality; oGraphic.SmoothingMode = SmoothingMode.HighQuality; oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic; Rectangle oRectangle = new Rectangle(0, 0, ThumbNailSizeToUse.Width, ThumbNailSizeToUse.Height); oGraphic.DrawImage(oImg, oRectangle); oThumbNail.Save(sPhysicalPath + sThumbNailFileName, oFormat); oImg.Dispose(); } catch (Exception ex) { Response.Write(ex.Message); } }