C# 缩小图片的方法

public Form1()
        {
            InitializeComponent();
            SmallPic("\test.jpg", 0.1f);   //缩小为原来的0.1倍
        }
        /// <param name="strOldPic">源图文件名(包括路径)</param>
        /// <param name="strNewPic">缩小后保存为文件名(包括路径)</param>   //Save方法出现问题,没用此变量
        /// <param name="intWidth">缩小至宽度</param>
        /// <param name="intHeight">缩小至高度</param>
        public void SmallPic(string strOldPic, float shrinkRatio)   //源路径名,缩小比例
        {
            Bitmap objPic, objNewPic;
            try
            {
                objPic = new Bitmap(strOldPic);     //从路径中读取图片
                objNewPic = new Bitmap((int)(objPic.Width * shrinkRatio), (int)(objPic.Height * shrinkRatio));
                int intWidth = (int)(shrinkRatio * objPic.Width);
                int intHeight = (int)(shrinkRatio * objPic.Height);
                for (int i = 0; i < intWidth; i++)
                {
                    for (int j = 0; j < intHeight; j++)
                    {
                        //获取此像素处颜色(每隔N倍采样一次,N为缩小倍数)

                        Color pixelColor = objPic.GetPixel(i*objPic.Width/intWidth, j*objPic.Height/intHeight);  

                        //设置此像素处(x=i,y=j处)颜色
                        objNewPic.SetPixel(i, j, pixelColor);
                    }
                }

                pictureBox1.Image = objNewPic;      //在PictureBox中显示缩小后的图片

             }

         }

今天找到了Bitmap.Save方法的正确用法:objNewPic.Save("\new.jpg", ImageFormat.Jpeg);

参考资料:http://www.study-code.com/dotnet/csharp/68393.htm

系统自带图片Blue Hill(800*600)缩小为 40*30 后生成的文件new.jpg 如下图:

image

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s