一、演示
二、功能
1、PictureBox控件显示拖拽到其中的图片;
2、显示图片的路径、大小等相关信息;
三、代码及说明
为实现拖拽,需将pictureBox1控件的AllowDrop属性设置为True,即:
this.pictureBox1.AllowDrop = true;
将该控件的图片布局属性设置为Zoom(按比例缩放):
为该控件添加DragEnter方法:
完整程序如下:
using System;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace FileDragDrop
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.pictureBox1.AllowDrop = true;//允许拖拽
}
//调用API中获取文件大小的方法
[DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern uint GetCompressedFileSize(string fileName, ref uint fileSizeHigh);
private void pictureBox1_DragEnter(object sender, DragEventArgs e)
{
String[] str_Drop = (String[])e.Data.GetData(DataFormats.FileDrop, true);//检查拖动目标类型,是文件时执行
Bitmap bgImage = new Bitmap(str_Drop[0]);//初始化该文件路径的图片
pictureBox1.BackgroundImage = bgImage;//显示图片
label1.Text = str_Drop[0].ToString();//路径
label2.Text = bgImage.Width.ToString() + " × " + bgImage.Height.ToString();//像素
var ext = Path.GetExtension(str_Drop[0]);
label4.Text = ext.ToString(); //格式
uint size = 0; //大小
uint lsize = GetCompressedFileSize(str_Drop[0], ref size);
ulong rsize = ((ulong)size << 32) + lsize;
switch (rsize)//判断图片大小范围
{
case ulong n when n < 1024:
label3.Text = n.ToString() + "字节";
break;
case ulong n when n >= 1024 && n < 1024 * 1024:
label3.Text = ((float)n / 1024).ToString("F1") + "KB";//保留1位小数
break;
case ulong n when n >= 1024 * 1024:
label3.Text = ((float)n / 1024 / 1024).ToString("F2") + "MB";//保留2位小数
break;
}
}
}
}