C#对图片进行缩放变换
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ScaleImage
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Image s = Image.FromFile("D:\\image\\22.jpg");
Image bgImage = ZoomPicture(s, 0.5f, 0.5f); //M,N大于1,为放大图片,小于1为缩小图片
panel1.Width = bgImage.Width; //设置画板宽度为图片宽度
panel1.Height = bgImage.Height; //设置画板高度为图片高度
panel1.BackgroundImage = bgImage;
BitMap bmap = new BitMap(bgImage);
bmap.Save("D:\\image\\23.jpg", ImageFormt.Jpeg);
bmap.Dispose();
}
// 按比例缩放图片
public Image ZoomPicture(Image SourceImage, float M, float N)
{
int IntWidth; //新的图片宽
int IntHeight; //新的图片高
int TargetWidth = (int)(M * SourceImage.Width); //取整,是因为下面的Bitmap的两个参数只能为整数
int TargetHeight = (int)(N * SourceImage.Height);
try
{
ImageFormat format = SourceImage.RawFormat;
Bitmap SaveImage = new Bitmap(TargetWidth, TargetHeight);
Graphics g = Graphics.FromImage(SaveImage);
g.Clear(Color.White);
//计算缩放图片的大小
IntHeight = TargetHeight;
IntWidth = TargetWidth;
g.DrawImage(SourceImage, 0, 0, IntWidth, IntHeight); //在指定坐标处画指定大小的图片
SourceImage.Dispose();
return SaveImage;
}
catch (Exception ex)
{
}
return null;
}
}
}
运行结果如下:
我胡真帅!!!!