C# 打開圖片


在c#中進行圖像處理,一般使用這三個類:Bitmap類,BitmapData類和Graphics類。

Bitmap類封裝了GDI+中的一個位圖,此位圖由圖形圖像機器屬性的像素數據組成。因此BItmap是用於處理由像素數據定義的圖像的對象。該類一般用到一下幾個方法和屬性:

GetPixel和SetPixel方法:獲取和設置一個圖像的指定像素的顏色。

PixelFormat屬性:返回圖像的像素格式。

Height屬性和Width屬性:返回圖像的高度和寬度。

LockBit方法和UnlockBits:分別鎖定和解鎖系統內存中的位圖像素。在基於像素帶你的圖像處理方法中使用LockBits和UnlockBits是一個很好的方式,這兩種方法可以使我們通過指定像素的范圍來控制位圖的任意一部分,從而消除了通過循環對位圖的像素逐個進行處理的需要。每次調用LockBits之后都應該調用一次UnlockBits。

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Diagnostics;

namespace WindowsFormsApplication14
{
    public partial class Form1 : Form
    {
        //文件名
        private string curFileName;
        //圖像對象
        private Bitmap curBitmap;
        private HiperfTimer myTimer;
        public Form1()
        {
            InitializeComponent();
            myTimer = new HiperfTimer();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog opndlg = new OpenFileDialog();
            opndlg.Filter = "所有圖像文件|*.bmp;*.pcx;*.png;*.jpg;*.gif";
            opndlg.Title = "打開圖像文件";
            if(opndlg .ShowDialog ()==DialogResult.OK )
            {
                curFileName = opndlg.FileName;
                try
                {
                    curBitmap = (Bitmap)Image.FromFile(curFileName);

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            Invalidate();
        }
}
}

先定義一個字符串和一個Bitmap類型的數據成員。

    private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            if(curBitmap !=null)
            {
                g.DrawImage(curBitmap, 160, 20, curBitmap.Width, curBitmap.Height);
            }
        }

當需要進行繪制時,必須通過Graphics對象來執行繪制操作。使用窗體的Paint事件,重載OnPaint方法,使用CreatGraphics方法創建Graphics對象。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM