工具类代码:
代码如下
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Drawing;
usingSystem.Drawing.Drawing2D;
usingSystem.Drawing.Imaging;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceZoomImage.Utils
{
///
/// 图片缩放
///
publicclassZoomImageUtil
{
///
/// 图片缩放
///
/// 图片
/// 目标宽度,若为0,表示宽度按比例缩放
/// 目标长度,若为0,表示长度按比例缩放
publicstaticBitmap GetThumbnail(Bitmap bmp,intwidth,intheight)
{
if(width == 0)
{
width = height * bmp.Width / bmp.Height;
}
if(height == 0)
{
height = width * bmp.Height / bmp.Width;
}
Image imgSource = bmp;
Bitmap outBmp =newBitmap(width, height);
Graphics g = Graphics.FromImage(outBmp);
g.Clear(Color.Transparent);
// 设置画布的描绘质量
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(imgSource,newRectangle(0, 0, width, height + 1), 0, 0, imgSource.Width, imgSource.Height, GraphicsUnit.Pixel);
g.Dispose();
imgSource.Dispose();
bmp.Dispose();
returnoutBmp;
}
}
}
使用示例:
代码如下
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.IO;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading;
usingSystem.Threading.Tasks;
usingSystem.Windows.Forms;
usingZoomImage.Utils;
namespaceZoomImage
{
publicpartialclassForm1 : Form
{
publicForm1()
{
InitializeComponent();
}
privatevoidForm1_Load(objectsender, EventArgs e)
{
openFileDialog1.Multiselect =true;
}
privatevoidtxtWidth_KeyPress(objectsender, KeyPressEventArgs e)
{
if(e.KeyChar != 8 && !Char.IsDigit(e.KeyChar))
{
e.Handled =true;
}
}
privatevoidtxtHeight_KeyPress(objectsender, KeyPressEventArgs e)
{
if(e.KeyChar != 8 && !Char.IsDigit(e.KeyChar))
{
e.Handled =true;
}
}
privatevoidbtnSelectImage_Click(objectsender, EventArgs e)
{
try
{
if(txtWidth.Text ==""&& txtHeight.Text =="")
{
return;
}
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
Task.Factory.StartNew(() =>
{
stringpath = Path.GetDirectoryName(openFileDialog1.FileNames[0]) +"\\NewImage\\";
inti = 0;
foreach(stringfileNameinopenFileDialog1.FileNames)
{
Bitmap bmp = ZoomImageUtil.GetThumbnail(newBitmap(fileName), Convert.ToInt32(txtWidth.Text ==""?"0": txtWidth.Text), Convert.ToInt32(txtHeight.Text ==""?"0": txtHeight.Text));
if(!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
File.Delete(path + Path.GetFileName(fileName));
bmp.Save(path + Path.GetFileName(fileName));
this.Invoke(newInvokeDelegate(() =>
{
lblProgress.Text =string.Format("进度:{1}/{0}", openFileDialog1.FileNames.Length, ++i);
}));
Thread.Sleep(1);
}
MessageBox.Show("成功!");
});
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
///
/// 跨线程访问控件的委托
///
publicdelegatevoidInvokeDelegate();
}
http://m.bbyears.com/jiaocheng/130675.html
推荐访问:藏宝阁 菜鸟教程 创客贴 草料二维码 cctv5 csdn cnki colg