zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C# 图像处理

2023-09-11 14:16:46 时间

一 GDI+中的图像处理

1 GDI+中对图像处理提供了以下支持:

① 支持BMP、GIF、JPEG、PNG、TIFF、ICON等等广泛格式的图像文件;
② 提供了用于多种光栅图像格式进行编码和解码的公共接口;
③ 支持为图像格式添加动态格式;
④ 支持对图像的像素进行多种处理,包括亮度,对比度,颜色平滑、模糊;
⑤ 支持对图像进行选择、剪切等操作;

2 主要公共Image实现

二 Bitmap类

1 Image是抽象类,Bitmap从Image派生

2 可以出来BMP、Jpeg、GIF、PNG等格式

3 构建

① Bitmap bt1=new Bitmap(“c:\1.bmp”);
② Bitmap bt2=new Bitmap(bt1,200,300);
③ Bitmap bt3;
bt3.FromFile(“文件名称”);

三 图像的绘制

整个图像的绘制
DrawImage;

四 图像处理

1 图像文件bmp格式;

2 使用bitmap.GetPixel(x,y);得到像素点;

2 使用指针

bitmapData=bitmap.LockBits(bounds,ImageLockMode.ReadWrite,PixelForm.Format24bppRgb);
pBase=(Byte*)bitmapData.Scan0.ToPointer();
(PixelData*)(pBase+y*stride+x*sizeof(PixelData));

3 因为使用unsafe,所以编译的时候需要设置“允许不安全的代码”.

五 图像过滤

图像过滤
针对像素的运算

更全面的图像过滤器.rar: https://url09.ctfile.com/f/22158009-749685290-1cc953?p=5939 (访问密码: 5939)

生产缩略图

using System;

using System.Drawing;

using System.Drawing.Drawing2D;

 

class ThumbnailTest

{

    static void Main()

    {

        string file = @"c:\1.jpg";

        Bitmap bitmap = new Bitmap( file );

        Bitmap thum = CreateThumbnail( bitmap, 100, 80 );

        thum.Save( @"c:\1_small.jpg");

    }

 

 

    public static Bitmap CreateThumbnail(Bitmap originalBmp, int desiredWidth, int desiredHeight)

    {

        // If the image is smaller than a thumbnail just return it

        if (originalBmp.Width <= desiredWidth && originalBmp.Height <= desiredHeight)

        {

            return originalBmp;

        }

 

        int newWidth, newHeight;

 

        // scale down the smaller dimension

        if (desiredWidth * originalBmp.Height < desiredHeight * originalBmp.Width)

        {

            newWidth = desiredWidth;

            newHeight = (int)Math.Round((decimal)originalBmp.Height * desiredWidth / originalBmp.Width);

        }

        else

        {

            newHeight = desiredHeight;

            newWidth = (int)Math.Round((decimal)originalBmp.Width * desiredHeight / originalBmp.Height);

        }

 

        // This code creates cleaner (though bigger) thumbnails and properly

        // and handles GIF files better by generating a white background for

        // transparent images (as opposed to black)

        // This is preferred to calling Bitmap.GetThumbnailImage()

 

        Bitmap bmpOut = new Bitmap(newWidth, newHeight);

         

        using (Graphics graphics = Graphics.FromImage(bmpOut))

        {

            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

            graphics.FillRectangle(Brushes.White, 0, 0, newWidth, newHeight);

            graphics.DrawImage(originalBmp, 0, 0, newWidth, newHeight);

        }

 

        return bmpOut;

    }

}