1. Drag and drop upload Image 1.1, modify the form properties in the background code, add AllowDrop = True
1.2. Add a drag-and-drop event to the form to find a drag-and-drop on the event list:
Add the following code in the DragDrop generated method:
Private void Form1_dragdrop (object sender, DragEventArgs e) { if (E.data.getdatapresent ( DataFormats.FileDrop)) { = dragdropeffects.move; } Else { = dragdropeffects.none; } }
Add the following code in the DragEnter method:
Private voidForm1_dragenter (Objectsender, DragEventArgs e) { //Judging string[] files = e.Data.GetData (DataFormats.FileDrop) as string[]; stringFile = files[0]; if(!file. ToLower (). EndsWith (". PNG") &&!file. ToLower (). EndsWith (". jpg") {MessageBox.Show ("need picture File!"); return; } //PictureBox control Display Pictureimage.load (file); }
2. Click the button to upload the image 2.1, the Official document address: Https://msdn.microsoft.com/zh-cn/library/system.windows.controls.openfiledialog.filter (v= vs.95. aspx2.2, adding control OpenFileDialog to the form, provides the ability to prompt the user to open the file. button to add the following code:
Private void button1_click (object sender, EventArgs e) { if ( Openfiledialog.showdialog () = = DialogResult.OK ) {//PictureBox control display picture image.load (openfiledialog.filename); } }
2.3, upload pictures and save
Private voidButton1_Click (Objectsender, EventArgs e) { if(Openfiledialog.showdialog () = =DialogResult.OK) {//PictureBox control Display Pictureimage.load (openfiledialog.filename); //gets the suffix name of the user-selected file stringExtension =path.getextension (openfiledialog.filename); //declaring the allowed suffix names string[] str =New string[] {". gif",". Jpge",". jpg",". PNG" }; if(!Str. Contains (extension)) {MessageBox.Show ("only images in gif,jpge,jpg format can be uploaded! "); } Else { //gets the file selected by the user and determines that the file size cannot exceed 20k,fileinfo.length in bytes.FileInfo FileInfo =NewFileInfo (openfiledialog.filename); if(Fileinfo.length >20480) {MessageBox.Show ("the uploaded image cannot be larger than 20K"); } Else { //Absolute Path stringImage =Openfiledialog.filename; //it means xxx.jpg . stringPicpath =Openfiledialog.safefilename; File.Copy (Openfiledialog.filename, Application.startuppath+"\\Image\\"+Picpath); } } } }
"C #" WinForm Uploading pictures