C# 圖片(圖像/影像) 基礎(基本) 運算/處理

C# 圖片(圖像/影像) 基礎(基本) 運算/處理

C# 圖片(圖像/影像) 基礎(基本) 運算/處理


資料來源:

https://blog.csdn.net/qq_42170268/article/details/82259029
https://dotblogs.com.tw/ricochen/2009/12/07/12324


code:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lib
{
    //https://blog.csdn.net/qq_42170268/article/details/82259029
    //https://dotblogs.com.tw/ricochen/2009/12/07/12324

    public class ImageCalc
    {
        public static Image MarkImage(Image img1, Image img2)//圖片浮水印
        {
            Image MergedImage = default(Image);
            //設定背景圖片
            Graphics gr = System.Drawing.Graphics.FromImage(img1);
            //新建logo浮水印圖片
            Bitmap Logo = new Bitmap(img2.Width, img2.Height);
            Graphics tgr = Graphics.FromImage(Logo);
            ColorMatrix cmatrix = new ColorMatrix();
            //設定圖片色彩(透明度)
            cmatrix.Matrix33 = 0.5F;
            ImageAttributes imgattributes = new ImageAttributes();
            imgattributes.SetColorMatrix(cmatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            tgr.DrawImage(img2, new Rectangle(0, 0, Logo.Width, Logo.Height), 0, 0, Logo.Width, Logo.Height, GraphicsUnit.Pixel, imgattributes);
            tgr.Dispose();
            //logo圖片位置
            gr.DrawImage(Logo, img1.Width / 3, 10);
            gr.Dispose();
            MergedImage = img1;
            return MergedImage;
        }

        public static Image VerticalMergeImages(Image img1, Image img2)//垂直合併
        {
            Image MergedImage = default(Image);
            Int32 Wide = 0;
            Int32 High = 0;
            High = img1.Height + img2.Height;//設定高度          
            if (img1.Width >= img2.Width)
            {
                Wide = img1.Width;
            }
            else
            {
                Wide = img2.Width;
            }
            Bitmap mybmp = new Bitmap(Wide, High);
            Graphics gr = Graphics.FromImage(mybmp);
            //處理第一張圖片
            gr.DrawImage(img1, 0, 0);
            //處理第二張圖片
            gr.DrawImage(img2, 0, img1.Height);
            MergedImage = mybmp;
            gr.Dispose();
            return MergedImage;
        }

        public static Image HorizontalMergeImages(Image img1, Image img2)//水平合併
        {
            Image MergedImage = default(Image);
            Int32 Wide = 0;
            Int32 High = 0;
            Wide = img1.Width + img2.Width;//設定寬度           
            if (img1.Height >= img2.Height)
            {
                High = img1.Height;
            }
            else
            {
                High = img2.Height;
            }
            Bitmap mybmp = new Bitmap(Wide, High);
            Graphics gr = Graphics.FromImage(mybmp);
            //處理第一張圖片
            gr.DrawImage(img1, 0, 0);
            //處理第二張圖片
            gr.DrawImage(img2, img1.Width, 0);
            MergedImage = mybmp;
            gr.Dispose();
            return MergedImage;
        }

        /// <summary>
        /// 背景透明化
        /// </summary>
        /// <param name="img">原圖</param>
        /// <param name="w">圖片寬度</param>
        /// <param name="h">圖片高度</param>
        /// <returns></returns>
        public static Bitmap Conver_1(Bitmap img, int w, int h)
        {
            Bitmap bg = new Bitmap(w, h);
            int alpha = 0;
            Color demo;
            Color pixel;
            for (int x = 0; x < w; x++)
            {
                for (int y = 0; y < h; y++)
                {
                    demo = img.GetPixel(1, 1);
                    pixel = img.GetPixel(x, y);
                    int R = demo.R;
                    int G = demo.G;
                    int B = demo.B;
                    int r1 = pixel.R;
                    int g1 = pixel.G;
                    int b1 = pixel.B;
                    int a = 40;  //RGB誤差範圍
                    if (Math.Abs(R - r1) < a && Math.Abs(G - g1) < a && Math.Abs(B - b1) < a)
                    {
                        alpha = 0;  //RGB在色差範圍內,透明度為0
                    }
                    else
                    {
                        alpha = 255;
                    }
                    bg.SetPixel(x, y, Color.FromArgb(alpha, r1, g1, b1));
                }
            }
            return bg;
        }

        /// <summary>
        /// 指定顏色透明化
        /// </summary>
        /// <param name="img">原圖</param>
        /// <param name="w">原圖寬度</param>
        /// <param name="h">原圖高度</param>
        /// <param name="R">指定顏色RGB的R值</param>
        /// <param name="G">指定顏色RGB的G值</param>
        /// <param name="B">指定顏色RGB的B值</param>
        /// <returns></returns>
        public static Bitmap Conver_2(Bitmap img, int w, int h, int R, int G, int B)
        {
            Bitmap bg = new Bitmap(w, h);
            int alpha = 0;
            Color pixel;
            for (int x = 0; x < w; x++)
            {
                for (int y = 0; y < h; y++)
                {
                    pixel = img.GetPixel(x, y);
                    int r1 = pixel.R;
                    int g1 = pixel.G;
                    int b1 = pixel.B;
                    int a = 40;  //色差範圍值
                    if (Math.Abs(R - r1) < a && Math.Abs(G - g1) < a && Math.Abs(B - b1) < a)
                    {
                        alpha = 0;    //若兩種顏色比較接近,透明度設為0
                    }
                    else
                    {
                        alpha = 255;
                    }
                    bg.SetPixel(x, y, Color.FromArgb(alpha, r1, g1, b1));
                }
            }
            return bg;
        }

        /// <summary>
        /// 指定顏色替換成另一種顏色
        /// </summary>
        /// <param name="img">原圖</param>
        /// <param name="w">圖寬</param>
        /// <param name="h">圖高</param>
        /// <param name="R">要被替換顏色的RGB的R</param>
        /// <param name="G">要被替換顏色的RGB的G</param>
        /// <param name="B">要被替換顏色的RGB的B</param>
        /// <param name="r">替換色的RGB的R</param>
        /// <param name="g">替換色的RGB的G</param>
        /// <param name="b">替換色的RGB的B</param>
        /// <returns></returns>
        public static Bitmap Conver_3(Bitmap img, int w, int h, int R, int G, int B, int r, int g, int b)
        {
            Bitmap bg = new Bitmap(w, h);
            Color pixel;
            for (int x = 0; x < w; x++)
            {
                for (int y = 0; y < h; y++)
                {
                    pixel = img.GetPixel(x, y);
                    int r1 = pixel.R;
                    int g1 = pixel.G;
                    int b1 = pixel.B;
                    int a = 40;
                    if (Math.Abs(R - r1) < a && Math.Abs(G - g1) < a && Math.Abs(B - b1) < a)
                    {
                        bg.SetPixel(x, y, Color.FromArgb(r, g, b));
                    }
                    else
                    {
                        bg.SetPixel(x, y, Color.FromArgb(r1, g1, b1));
                    }

                }
            }
            return bg;
        }

        /// <summary>
        /// 圖片按比例縮放
        /// </summary>
        /// <param name="SourceImage">靶心圖表片</param>
        /// <param name="a">縮放的比例</param>
        /// <returns></returns>
        public static Image PictureHandle1(Image SourceImage, float a)
        {
            int W;  //縮放後圖片的寬
            int H;  //縮放後圖片的高
            W = (int)(a * SourceImage.Width);
            H = (int)(a * SourceImage.Height);
            try
            {
                ImageFormat format = SourceImage.RawFormat;
                Bitmap SaveImage = new Bitmap(W, H);
                Graphics g = Graphics.FromImage(SaveImage);
                g.Clear(Color.White);
                g.DrawImage(SourceImage, 0, 0, W, H);
                SourceImage.Dispose();
                return SaveImage;
            }
            catch (Exception e)
            {

            }
            return null;
        }

        /// <summary>
        /// 圖片旋轉
        /// </summary>
        /// <param name="b">原圖</param>
        /// <param name="savePath">旋轉後保存路徑</param>
        /// <param name="angle">旋轉角度</param>
        public static bool RotateImage(Image b, string savePath, float angle)
        {
            angle = angle % 360;            //弧度轉換
            double radian = angle * Math.PI / 180.0;
            double cos = Math.Cos(radian);
            double sin = Math.Sin(radian);
            //原圖的寬和高
            int w = b.Width;
            int h = b.Height;
            int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));
            int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));
            //目標點陣圖
            Image dsImage = new Bitmap(W, H);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(dsImage);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //計算偏移量
            Point Offset = new Point((W - w) / 2, (H - h) / 2);
            //構造圖像顯示區域:讓圖像的中心與視窗的中心點一致
            Rectangle rect = new Rectangle(Offset.X, Offset.Y, w, h);
            Point center = new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
            g.TranslateTransform(center.X, center.Y);
            g.RotateTransform(360 - angle);
            //恢復圖像在水準和垂直方向的平移
            g.TranslateTransform(-center.X, -center.Y);
            g.DrawImage(b, rect);
            //重至繪圖的所有變換
            g.ResetTransform();
            g.Save();
            g.Dispose();
            string extension = Path.GetExtension(savePath);
            if (extension == ".jpg")
            {
                return false;//MessageBox.Show("圖片保存不是png格式,旋轉效果有誤!請重新選擇保存格式!");
            }
            else
            {
                dsImage.Save(savePath, ImageFormat.Png);
                return true;//MessageBox.Show("圖片旋轉成功!");
            }
        }

        /// <summary>
        /// 圖片更改透明度
        /// </summary>
        /// <param name="waterPic">浮水印圖</param>
        /// <param name="alpha">透明度值 0—255</param>
        /// <returns></returns>
        public static Image ChangeAlpha(Image waterPic, int alpha)
        {
            Bitmap img = new Bitmap(waterPic);
            using (Bitmap bmp = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
            {
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    g.DrawImage(img, 0, 0);
                    for (int h = 0; h < img.Height; h++)
                    {
                        for (int w = 0; w < img.Width; w++)
                        {
                            Color color = img.GetPixel(w, h);
                            bmp.SetPixel(w, h, Color.FromArgb(alpha, color.R, color.G, color.B));
                        }
                    }
                    return (Image)bmp.Clone();
                }
            }
        }

        /// <summary>
        /// 圖片添加文字
        /// </summary>
        /// <param name="template">範本路徑</param>
        /// <param name="savePath">保存路徑</param>
        /// <param name="text">文字內容</param>
        /// <param name="font">字體</param>
        /// <param name="color">字體顏色</param>
        /// <param name="x">文字添加位置的起始座標X</param>
        /// <param name="y">文字添加位置的起始座標Y</param>
        public static void templateAddText(string template, string savePath, string text, Font font, Color color, int x, int y)
        {
            Image image = Image.FromFile(template);
            Bitmap bt = new Bitmap(image, image.Width, image.Height);
            Graphics g = Graphics.FromImage(bt);
            Font f = font;
            Brush b = new SolidBrush(color);
            g.DrawString(text, f, b, x, y);
            string extension = Path.GetExtension(savePath);
            if (extension == ".jpg")
            {
                bt.Save(savePath, ImageFormat.Jpeg);
            }
            else
            {
                bt.Save(savePath, ImageFormat.Png);
            }
        }

        /// <summary>
        /// 圖片添加小圖
        /// </summary>
        /// <param name="template">範本圖路徑</param>
        /// <param name="pic">小圖路徑</param>
        /// <param name="savePath">保存路徑</param>
        /// <param name="x">小圖添加位置起始座標X</param>
        /// <param name="y">小圖添加位置起始座標Y</param>
        public static void TemplateAddPicture(string template, string pic, string savePath, int x, int y)
        {
            Image image = Image.FromFile(template);
            Bitmap bt = new Bitmap(image, image.Width, image.Height);
            Image picture = Image.FromFile(pic);
            Bitmap small = new Bitmap(picture, picture.Width, picture.Height);
            Graphics g = Graphics.FromImage(bt);
            g.DrawImage(small, x, y, picture.Width, picture.Height);
            string extension = Path.GetExtension(savePath);
            if (extension == ".jpg")
            {
                bt.Save(savePath, ImageFormat.Jpeg);
            }
            else
            {
                bt.Save(savePath, ImageFormat.Png);
            }

        }

        /// <summary>
        /// 橫向合併兩張圖片
        /// </summary>
        /// <param name="pic1">左圖檔的路徑</param>
        /// <param name="pic2">右圖的檔路徑</param>
        /// <param name="savePath">合成圖片保存路徑</param>
        public static bool H_merge(string pic1, string pic2, string savePath)
        {
            Image img1 = Image.FromFile(pic1);
            Image img2 = Image.FromFile(pic2);
            Bitmap L = new Bitmap(img1, img1.Width, img1.Height);
            Bitmap R = new Bitmap(img2, img2.Width, img2.Height);
            if (img2.Height == img1.Height)
            {
                Bitmap bg = new Bitmap(img1.Width + img2.Width, img1.Height);
                Graphics g = Graphics.FromImage(bg);
                g.DrawImage(L, 0, 0, img1.Width, img1.Height);
                g.DrawImage(R, img1.Width, 0, img2.Width, img2.Height);
                g.Dispose();
                string extension = Path.GetExtension(savePath);
                if (extension == ".jpg")
                {
                    bg.Save(savePath, ImageFormat.Jpeg);
                }
                else
                {
                    bg.Save(savePath, ImageFormat.Png);
                }
                return true;//MessageBox.Show("圖片合成成功!");
            }
            else
            {
                return false;//MessageBox.Show("兩張圖片的高度不一致,請重新選擇!");
            }
        }

        /// <summary>
        /// 縱向合併兩張圖片
        /// </summary>
        /// <param name="pic1">上圖檔的路徑</param>
        /// <param name="pic2">下圖的檔路徑</param>
        /// <param name="savePath">合成圖片保存路徑</param>
        public static bool Z_merge(string pic1, string pic2, string savePath)
        {
            Image img1 = Image.FromFile(pic1);
            Image img2 = Image.FromFile(pic2);
            Bitmap L = new Bitmap(img1, img1.Width, img1.Height);
            Bitmap R = new Bitmap(img2, img2.Width, img2.Height);
            if (img2.Width == img1.Width)
            {
                Bitmap bg = new Bitmap(img1.Width, img1.Height + img2.Height);
                Graphics g = Graphics.FromImage(bg);
                g.DrawImage(L, 0, 0, img1.Width, img1.Height);
                g.DrawImage(R, 0, img1.Height, img2.Width, img2.Height);
                g.Dispose();
                string extension = Path.GetExtension(savePath);
                if (extension == ".jpg")
                {
                    bg.Save(savePath, ImageFormat.Jpeg);
                }
                else
                {
                    bg.Save(savePath, ImageFormat.Png);
                }
                return true;//MessageBox.Show("圖片合成成功!");
            }
            else
            {
                return false;//MessageBox.Show("兩張圖片的寬度不一致,請重新選擇!");
            }
        }

        /// <summary>
        /// 圖片切割
        /// </summary>
        /// <param name="template">原圖路徑</param>
        /// <param name="savePath">切割圖保存路徑</param>
        /// <param name="x">切割起始位置的座標X</param>
        /// <param name="y">切割起始位置的座標Y</param>
        /// <param name="w">切割寬度</param>
        /// <param name="h">切割高度</param>
        public static void pic_cut(string template, string savePath, int x, int y, int w, int h)
        {
            Image image = Image.FromFile(template);
            Bitmap b = new Bitmap(image, image.Width, image.Height);
            Bitmap bmpOut = new Bitmap(w, h, PixelFormat.Format24bppRgb);
            Graphics g = Graphics.FromImage(bmpOut);
            g.DrawImage(b, new Rectangle(0, 0, w, h), new Rectangle(x, y, w, h), GraphicsUnit.Pixel);
            g.Dispose();
            string extension = Path.GetExtension(savePath);
            if (extension == ".jpg")
            {
                bmpOut.Save(savePath, ImageFormat.Jpeg);
            }
            else
            {
                bmpOut.Save(savePath, ImageFormat.Png);
            }
        }

    }
}

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *