C # L The application of this system Istview a simple image browser

Source: Internet
Author: User
Tags bmp image define function

Recently a classmate asked me how to use the ListView load image list, in ... The previous "application in C # system" Displays the disk folder in the Treeview+listview+contextmenustrip Control implementation tree view. and displays specific information about the file in the ListView. Here's a brief introduction to the students how to use the Listview+imagelist control to implement a simple picture browser knowledge.
The first step is to design the interface framework, for example, to add the ImageList control (not visible) at the same time as seen.

Note: The Anchor property of the ListView control is set to Top,bottom,right, and the anchor property of the set PictureBox is up or down.
second step using the OpenFileDialog control to open the display picture

//Open Picture Private    void Button1_Click (object sender, EventArgs e) {//Set Open file control OpenFileDialog OpenFile = new OpenFileDialog (); OpenFile. Filter = "JPG (*. jpg;*. JPEG); GIF file (*. GIF); BMP File (*. BMP); PNG file (*.    PNG) |*.jpg;*.jpeg;*.gif;*.bmp;*.png "; OpenFile.  FilterIndex = 1; The currently selected index OpenFile.    Restoredirectory = true; OpenFile.    FileName = ""; The dialog box selects the OK button if (openfile. ShowDialog () = = DialogResult.OK) {//fromfile creates an Image pictureBox1.Image = Image.FromFile (openfile) from the specified file.        FileName);                   The picture is stretched or shrunk to fit picturebox size Picturebox1.sizemode = Pictureboxsizemode.stretchimage; }}

         Picture display effect For example to see, need to note that in the use of FromFile display pictures, the picture may appear in full screen when only a partial picture phenomenon, I set the picture can be stretched or shrunk stretchimage mode.

         step three   display a list of pictures to the ListView control
        

Join namespaces using system.io;                   //directory folder using system.diagnostics;                                     //stopwatch Display time//define variable private string Folderdirpath;                        Picture folder address private string picdirpath = null; Picture path private list<string> imagepathlist = new list<string> ();                                       Gets the list picture path private int index; Get selected list picture ordinal//listview and ImageList display picture List private void button2_click (object sender, EventArgs e) {try {//Open Select Folder        dialog box FolderBrowserDialog FolderBrowserDialog = new FolderBrowserDialog ();        DialogResult result = Folderbrowserdialog.showdialog (); if (result = = DialogResult.OK) {//Get user-selected folder path This.folderdirpath = Folderbrowserdialog.sele            Ctedpath;        Call your own definition function to display a list of pictures to the ListView control Showpicture (); } ElSe if (result = = DialogResult.Cancel) {MessageBox.Show ("suppress Picture List");    }} catch (Exception msg) {//Error prompt does not set object reference to an instance of object throw msg; }}//displays a list of pictures to the ListView control private void Showpicture () {//provides a way to start calculation of test Execution time//reference information: Http://www.cnblogs.com/newstart/arc    hive/2012/09/21/2696884.html Stopwatch sw = new Stopwatch (); Sw.    Start ();    Get folders and subfolders DirectoryInfo dir = new DirectoryInfo (Folderdirpath); Gets the current folder jpg file list GetFiles Gets the name of the file in the specified folder (including its path) fileinfo[] FileInfo = dir.    GetFiles ("*.jpg"); Prevent image Distortion//reference information: http://blog.csdn.net/cdefg198/article/details/7821891 (quoted in the blog) this.imageList1.ColorDepth = COLORDEP Th.    Depth32bit; for (int i = 0; i < fileinfo.length; i++) {//Get file full folder Picdirpath = Fileinfo[i].        FullName;        Record picture source path double-click to display the picture using Imagepathlist.add (Picdirpath);    Images are loaded into the ImageList control and ImageList Picture List This.imageList1.Images.Add (Image.FromFile (Picdirpath)); }//Show file list This.liStView1.Items.Clear ();    This.listView1.LargeImageList = This.imagelist1;        This.listView1.View = View.LargeIcon;   Large icon Display//imagelist1.imagesize = new Size (40, 40);    Cannot set ImageList image Size property at change//start binding this.listView1.BeginUpdate (); Add a picture to the ListView control for (int i = 0; i < ImageList1.Images.Count; i++) {ListViewItem LVI = new ListViewItem        (); Lvi.        ImageIndex = i; Lvi.        Text = "pic" + i;    THIS.LISTVIEW1.ITEMS.ADD (LVI);    } this.listView1.EndUpdate (); Displays the time required to open the Picture list SW.    Stop (); Long secords = SW. Elapsedmilliseconds; Millisecond Unit Label1. Text + = ' \ n ' + (convert.todouble (secords)/1000).  ToString ();   Convert to Seconds}

        The results are shown for example as seen in:

It is important to note that:
1. Several steps to load information using the ListView: Get Folder path, DirectoryInfo get folder--GetFiles Get file--add picture to ImageList--add picture to ListView.
2. When setting the size of the picture in the ListView, the assignment with imagelist1.imagesize = new Size (40, 40) failed, and I implemented it by altering the ImageSize property of the ImageList1 (64,64).
3. Display the picture in the ListView, the general distortion of the situation, the main reason for the blog: ListView shows distorted picture.
The main summary is ImageList inside the picture color distortion and image size distortion, the picture color distortion reason is design-time in the vs.net to add the picture when the user specified colordepth (such as Depth32bit), The default value of Imagelist.colordepth (Depth8bit) is used. Therefore, you need to set the color depth of the picture before adding the image to the ImageList, and the image size is equal to imagelist.imagesize.
Fourth Step by double-clicking the Listview1_doubleclick function to open the picture
in form1.cs[design], the ListView property page adds a DoubleClick double-click event to it and displays the picture through Image.FromFile.

Add double-click the ListView event to display the picture to Pictureboxprivate void Listview1_doubleclick (object sender, EventArgs e) {    if ( This.listView1.SelectedItems.Count = = 0)        return;    Indexed way Imagepathlist record the real path of the picture    index = this.listview1.selecteditems[0]. Index;    Show Picture    this.pictureBox1.Image = Image.FromFile (Imagepathlist[index]);    The picture is stretched or shrunk to fit picturebox size    Picturebox1.sizemode = pictureboxsizemode.stretchimage;}

Double-click the display of different pictures in the list, such as what you see:


It is important to note that I display the picture in the list renamed "pic+ number", the same time to define the variable record directory in the picture real path with its one by one corresponding. Private list<string> imagepathlist = new list< String> (). Here you can use the index to display the corresponding picture, the same as the previous \ Next sheet.
The fifth step shows the previous sheet \ Next

Show previous picture private void Button3_Click (object sender, EventArgs e) {if (picturebox1.image! = null) {if (Index & Gt            0) {index--;            Show Picture This.pictureBox1.Image = Image.FromFile (Imagepathlist[index]);                          Picturebox1.sizemode = Pictureboxsizemode.stretchimage;            } else if (index = = 0) {index = Imagepathlist.count;            index--;            Show Picture This.pictureBox1.Image = Image.FromFile (Imagepathlist[index]);                          Picturebox1.sizemode = Pictureboxsizemode.stretchimage; }}}//shows the next picture private void Button4_Click (object sender, EventArgs e) {if (picturebox1.image! = null) {if (            index = = imagepathlist.count-1)//Last picture {index = 0;            Show Picture This.pictureBox1.Image = Image.FromFile (Imagepathlist[index]);                     Picturebox1.sizemode = Pictureboxsizemode.stretchimage;    } else {index++;            Show Picture This.pictureBox1.Image = Image.FromFile (Imagepathlist[index]);                          Picturebox1.sizemode = Pictureboxsizemode.stretchimage;    }    }}

        article written here basic content is complete, the content is relatively simple, But it also makes up a complete picture browser. At the same time, very often, we need to upload thumbnails to call the following functions (online note):

Join namespaces using system.drawing.drawing2d;   //compositingquality.highqualityusing system.drawing.imaging;     //encoderparameter///<summary>///Picture Lossless zoom own define function generate thumbnails/ </summary>///<param name= "sourcefile" > Picture source path </param>///<param name= "destfile" > Zoom picture Output path </param>///<param name= "destheight" > Zoom picture height </param>///<param name= "destwidth" > Zoom picture width </param>///<returns></returns>public static bool GetThumbnail (string sourcefile, String destFile,    int destheight, int destwidth) {System.Drawing.Image Imgsource = System.Drawing.Image.FromFile (sourcefile);    System.Drawing.Imaging.ImageFormat Thisformat = Imgsource.rawformat;    int SW = 0, SH = 0;    proportionally scales int swidth = imgsource.width;    int sheight = Imgsource.height;        if (Sheight > Destheight | | swidth > Destwidth) {if ((Swidth * destheight) > (sheight * destwidth))   {SW = Destwidth;         SH = (Destwidth * sheight)/swidth;            } else {SH = Destheight;        SW = (Swidth * destheight)/sheight;        }} else {SW = Swidth;    SH = Sheight;    }//Create a new BMP image Bitmap Outbmp = new Bitmap (destwidth, destheight);    Create a new artboard Graphics g = graphics.fromimage (outbmp);    Empty the canvas and fill the color.black black filled g.clear (System.Drawing.Color.Transparent) with a transparent background color;    Set the drawing quality of the canvas g.compositingquality = compositingquality.highquality;    Set high quality, low speed rendering smoothness G.smoothingmode = smoothingmode.highquality;    Set high-quality interpolation method g.interpolationmode = Interpolationmode.highqualitybicubic; Draws the specified portion of the original picture at the specified position and at the specified size g.drawimage (imgsource, New Rectangle ((DESTWIDTH-SW)/2, (DESTHEIGHT-SH)/2, SW, SH), 0,    0, Imgsource.width, Imgsource.height, GraphicsUnit.Pixel);    G.dispose ();    The following code sets the compression quality encoderparameters Encoderparams = new EncoderParameters () when saving the picture;    long[] quality = new LONG[1];    QUALITY[0] = 100; EncodErparameter Encoderparam = new Encoderparameter (System.Drawing.Imaging.Encoder.Quality, quality);    Encoderparams.param[0] = Encoderparam; try {//Get ImageCodecInfo object that includes information about the built-in image codec imagecodecinfo[] Arrayici = Imagecodecinfo.getimageencoders ()        ;        ImageCodecInfo jpegici = null; for (int x = 0, x < arrayici.length, x + +) {if (arrayici[x].            Formatdescription.equals ("JPEG")) {Jpegici = arrayici[x];//set JPEG encoding break; }}//save to JPG format picture if (Jpegici! = null) {Outbmp.save (DestFile, Jpegici, Enco        Derparams);        } else {Outbmp.save (destfile, Thisformat);    } return true;    } catch (Exception e) {throw e;        } finally {imgsource.dispose ();    Outbmp.dispose (); }}

Summary: This article is mainly based on the students to explain the ListView control display picture written an article, the same time there is a disadvantage of the picture may be pulled deformation, and the code to open the ListView picture when there is a "open time", mainly through the Stopwatch record batch Open the picture time, Assuming that you open a lot of pictures, I want to use a parallel approach to the implementation of the time comparison. At the same time, it is assumed that students who are interested in image processing (c + + opens the transform via bitmap) can study it themselves. I want the display to look like Google Picasa in a high-speed batch display (study ing).
:http://download.csdn.net/detail/eastmount/8021077
Finally hope that the article is helpful to everyone, if there are errors or shortcomings, please Haihan ~
(By:eastmount 2014-10-10 Noon 13 o'clock original CSDN http://blog.csdn.net/eastmount/)

Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

C # L The application of this system Istview a simple image browser

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.