using System;using System.Drawing;using System.Windows.Forms;namespace WindowsFormsapplication2{ public partial class selectimg : Form { public selectimg() { InitializeComponent(); this.pictureBox1.BorderStyle = BorderStyle.FixedSingle; this.openFileDialog1.Filter = "圖片|*.jpg;*.png"; } PRivate void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { Image fromImage = Image.FromFile(this.openFileDialog1.FileName); fromImage = fromImage.AdjImageToFitSize(pictureBox1.Width, pictureBox1.Height); //350 this.pictureBox1.Image = fromImage; } } //... } internal static class ImgHelp { /// <summary> /// 獲取等比例縮放的圖片(高寬不一致時獲取最中間部分的圖片) /// </summary> public static Image AdjImageToFitSize(this Image fromImage, int width, int height) { Bitmap bitmap = new Bitmap(width, height); Graphics graphics = Graphics.FromImage(bitmap); Point[] destPoints = new Point[] { new Point(0, 0), new Point(width, 0), new Point(0, height) }; Rectangle rect = GetImageRectangle(fromImage.Width, fromImage.Height); graphics.DrawImage(fromImage, destPoints, rect, GraphicsUnit.Pixel); Image image = Image.FromHbitmap(bitmap.GetHbitmap()); bitmap.Dispose(); graphics.Dispose(); return image; } /// <summary> /// 居中位置獲取 /// </summary> private static Rectangle GetImageRectangle(int w, int h) { int x = 0; int y = 0; if (h > w) { h = w; y = (h - w) / 2; } else { w = h; x = (w - h) / 2; } return new Rectangle(x, y, w, h); } }}
新聞熱點
疑難解答