C# 对Bitmap 的一些处理方法,裁剪,压缩,旋转等

C#实现Bitmap旋转

Rotate180FlipNone 指定不进行翻转的 180 度旋转。

Rotate180FlipX 指定后接水平翻转的 180 度旋转。

Rotate180FlipXY 指定后接水平翻转和垂直翻转的 180 度旋转。

Rotate180FlipY 指定后接垂直翻转的 180 度旋转。

Rotate270FlipNone 指定不进行翻转的 270 度旋转。

Rotate270FlipX 指定后接水平翻转的 270 度旋转。

Rotate270FlipXY 指定后接水平翻转和垂直翻转的 270 度旋转。

Rotate270FlipY 指定后接垂直翻转的 270 度旋转。

Rotate90FlipNone 指定不进行翻转的 90 度旋转。

Rotate90FlipX 指定后接水平翻转的 90 度旋转。

Rotate90FlipXY 指定后接水平翻转和垂直翻转的 90 度旋转。

Rotate90FlipY 指定后接垂直翻转的 90 度旋转。

RotateNoneFlipNone 指定不进行旋转和翻转。

RotateNoneFlipX 指定没有后跟水平翻转的旋转。

RotateNoneFlipXY 指定没有后跟水平和垂直翻转的旋转。

RotateNoneFlipY 指定没有后跟垂直翻转的旋转。

如以下是实现Bitmap的逆时针旋转90度

cs 复制代码
bmp.RotateFlip(RotateFlipType.Rotate270FlipNone);

1.byte[] 转Bitmap

cs 复制代码
  public static Bitmap DataTo24bppBitmap(byte[] buffer, int width, int height, bool isFlip)
        {
            Bitmap bitmap = null;

            if (buffer != null && buffer.Length > 0 && width > 0 && height > 0)
            {
                // ImageLockMode.ReadWrite,System.Drawing.Imaging.PixelFormat.Format24bppRgb
                bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                BitmapData dstData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                int stride = dstData.Stride;
                IntPtr ptr = dstData.Scan0;

                if (isFlip)
                {
                    byte[] flipedBuffer = new byte[stride * height];
                    int length = flipedBuffer.Length;

                    for (int y = 0, destinationIndex = length - stride; destinationIndex >= 0; y += stride, destinationIndex -= stride)
                    {
                        Array.Copy(buffer, y, flipedBuffer, destinationIndex, stride);
                    }

                    Marshal.Copy(flipedBuffer, 0, ptr, stride * height);
                }
                else
                {
                    Marshal.Copy(buffer, 0, ptr, stride * height);
                }

                bitmap.UnlockBits(dstData);
            }

            return bitmap;
        }

2.Bitmap 转byte[]

cs 复制代码
  public static byte[] Bitmap2Byte(Bitmap bitmap)
        {
            #region 原版
            //using (MemoryStream stream = new MemoryStream())
            //{
            //    MemoryStream ms = new MemoryStream();
            //    Bitmap bbb = new Bitmap(bitmap);

            //    bbb.Save(ms, ImageFormat.Bmp);
            //    byte[] bytes = ms.GetBuffer();
            //    //byte[]   bytes=   ms.ToArray(); //这两句都可以,至于区别么,下面有解释
            //    ms.Close();
            //    return bytes;
            //}
            #endregion

            #region MyRegion
            using (MemoryStream stream = new MemoryStream())
            {
                try
                {
                    bitmap.Save(stream, ImageFormat.Bmp);
                    byte[] data = new byte[stream.Length];
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.Read(data, 0, Convert.ToInt32(stream.Length));
                    return data;
                }
                catch
                {

                }
                return new byte[2560];
            }
            #endregion
        }

3.yuv 转rgb

cs 复制代码
    /// <summary>
        /// yuv转rgb
        /// 使用byte[]
        /// </summary>
        /// <param name="yuvByte"></param>
        /// <param name="Width"></param>
        /// <param name="Height"></param>
        /// <param name="rgbFrame"></param>
        public static void ByteForYuvToRgb(byte[] yuvByte,int Width,int Height,bool IsUVChange, ref byte[] rgbFrame)
        {
            unsafe
            {
                AVPicture pFrameYUV, pFrameRGB;
                fixed (byte* ptr = &yuvByte[0], ptr1 = &rgbFrame[0])
                {
                    ffmpeg.avpicture_fill(&pFrameYUV, ptr, AVPixelFormat.AV_PIX_FMT_YUV420P, Width, Height);

                    if (IsUVChange)
                    {
                        //U,V互换
                        byte* ptmp = pFrameYUV.data[1];
                        pFrameYUV.data[1] = pFrameYUV.data[2];
                        pFrameYUV.data[2] = ptmp;
                    }
                    ffmpeg.avpicture_fill(&pFrameRGB, ptr1, AVPixelFormat.AV_PIX_FMT_RGB24, Width, Height);

                    (*ptr) = 0x00;
                    (*ptr1) = 0x00;
                }
                SwsContext* imgCtx;
                imgCtx = ffmpeg.sws_getContext(Width, Height, AVPixelFormat.AV_PIX_FMT_YUV420P,
                    Width, Height, AVPixelFormat.AV_PIX_FMT_RGB24, ffmpeg.SWS_FAST_BILINEAR, null, null,
                    null);            
                if (imgCtx != null)
                {
                    ffmpeg.sws_scale(imgCtx, pFrameYUV.data, pFrameYUV.linesize, 0, Height, pFrameRGB.data,
                        pFrameRGB.linesize);

                    ffmpeg.sws_freeContext(imgCtx);
                    imgCtx = null;
                }
                else
                {
                    ffmpeg.sws_freeContext(imgCtx);
                    imgCtx = null;
                }

            }
        }

4.图像裁剪

cs 复制代码
  #region 裁剪
        ///
        /// 剪裁 -- 用GDI+
        ///
        /// 原始Bitmap
        /// 开始坐标X
        /// 开始坐标Y
        /// 宽度
        /// 高度
        /// 剪裁后的Bitmap
        public static Bitmap KiCut(Bitmap b, int StartX, int StartY, int iWidth, int iHeight)
        {
            if (b == null)
            {
                return null;
            }

            int w = b.Width;
            int h = b.Height;

            if (StartX >= w || StartY >= h)
            {
                return null;
            }

            if (StartX + iWidth > w)
            {
                iWidth = w - StartX;
            }

            if (StartY + iHeight > h)
            {
                iHeight = h - StartY;
            }

            try
            {
                Bitmap bmpOut = new Bitmap(iWidth, iHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                Graphics g = Graphics.FromImage(bmpOut);
                g.DrawImage(b, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(StartX, StartY, iWidth, iHeight), GraphicsUnit.Pixel);
                g.Dispose();

                return bmpOut;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>  
        /// Resize图片  
        /// </summary>  
        /// <param name="bmp">原始Bitmap</param>  
        /// <param name="newW">新的宽度</param>  
        /// <param name="newH">新的高度</param>  
        /// <returns>处理以后的Bitmap</returns>  
        public static Bitmap KiResizeImage(Bitmap bmp, int newW, int newH)
        {
            try
            {
                Bitmap b = new Bitmap(newW, newH);
                Graphics g = Graphics.FromImage(b);

                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
                g.Dispose();

                return b;
            }
            catch
            {
                return null;
            }
        }
        #endregion

5.图像压缩

cs 复制代码
    #region 压缩

        //等比例缩放图片
        /// <summary>
        /// 等比例缩放图片
        /// </summary>
        /// <param name="bitmap"></param>
        /// <param name="destHeight"></param>
        /// <param name="destWidth"></param>
        /// <returns></returns>
        public  static Bitmap ZoomImage(Bitmap bitmap, int destHeight, int destWidth)
        {
            try
            {
                System.Drawing.Image sourImage = bitmap;
                int width = 0, height = 0;
                //按比例缩放           
                int sourWidth = sourImage.Width;
                int sourHeight = sourImage.Height;
                if (sourHeight > destHeight || sourWidth > destWidth)
                {
                    if ((sourWidth * destHeight) > (sourHeight * destWidth))
                    {
                        width = destWidth;
                        height = (destWidth * sourHeight) / sourWidth;
                    }
                    else
                    {
                        height = destHeight;
                        width = (sourWidth * destHeight) / sourHeight;
                    }
                }
                else
                {
                    width = sourWidth;
                    height = sourHeight;
                }
                Bitmap destBitmap = new Bitmap(destWidth, destHeight);
                Graphics g = Graphics.FromImage(destBitmap);
                g.Clear(Color.Transparent);
                //设置画布的描绘质量         
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(sourImage, new Rectangle((destWidth - width) / 2, (destHeight - height) / 2, width, height), 0, 0, sourImage.Width, sourImage.Height, GraphicsUnit.Pixel);
                g.Dispose();
                //设置压缩质量     
                System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
                long[] quality = new long[1];
                quality[0] = 100;
                System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                encoderParams.Param[0] = encoderParam;
                sourImage.Dispose();
                return destBitmap;
            }
            catch
            {
                return bitmap;
            }
        }

        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="mg"></param>
        /// <param name="newSize"></param>
        /// <returns></returns>
        public static Bitmap GetImageThumb(Bitmap mg, Size newSize)
        {
            double ratio = 0d;
            double myThumbWidth = 0d;
            double myThumbHeight = 0d;
            int x = 0;
            int y = 0;

            Bitmap bp;

            if ((mg.Width / Convert.ToDouble(newSize.Width)) > (mg.Height /
                                                                Convert.ToDouble(newSize.Height)))
                ratio = Convert.ToDouble(mg.Width) / Convert.ToDouble(newSize.Width);
            else
                ratio = Convert.ToDouble(mg.Height) / Convert.ToDouble(newSize.Height);
            myThumbHeight = Math.Ceiling(mg.Height / ratio);
            myThumbWidth = Math.Ceiling(mg.Width / ratio);

            Size thumbSize = new Size((int)newSize.Width, (int)newSize.Height);
            bp = new Bitmap(newSize.Width, newSize.Height);
            x = (newSize.Width - thumbSize.Width) / 2;
            y = (newSize.Height - thumbSize.Height);
            System.Drawing.Graphics g = Graphics.FromImage(bp);
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            Rectangle rect = new Rectangle(x, y, thumbSize.Width, thumbSize.Height);
            g.DrawImage(mg, rect, 0, 0, mg.Width, mg.Height, GraphicsUnit.Pixel);

            return bp;
        }

        /// <summary>  
        /// 生成缩略图  
        /// </summary>  
        /// <param name="sourceFile">原始图片文件</param>  
        /// <param name="quality">质量压缩比</param>  
        /// <param name="multiple">收缩倍数</param>  
        /// <param name="outputFile">输出文件名</param>  
        /// <returns>成功返回true,失败则返回false</returns>  
        public static Bitmap getThumImage(Bitmap bitmap, long quality, int multiple)
        {
            try
            {
                long imageQuality = quality;
                Bitmap sourceImage = new Bitmap(bitmap);
                ImageCodecInfo myImageCodecInfo = GetEncoder(ImageFormat.Jpeg);
                System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                EncoderParameters myEncoderParameters = new EncoderParameters(1);
                EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, imageQuality);
                myEncoderParameters.Param[0] = myEncoderParameter;
                float xWidth = sourceImage.Width;
                float yWidth = sourceImage.Height;
                Bitmap newImage = new Bitmap((int)(xWidth / multiple), (int)(yWidth / multiple));
                Graphics g = Graphics.FromImage(newImage);

                g.DrawImage(sourceImage, 0, 0, xWidth / multiple, yWidth / multiple);
                g.Dispose();
                MemoryStream memory = new MemoryStream();
                newImage.Save(memory, myImageCodecInfo, myEncoderParameters);

                return new Bitmap((Image)new Bitmap(memory));
            }
            catch
            {
                return bitmap;
            }
        }

        /// <summary>
        /// 壓縮圖片 /// </summary>
        /// <param name="fileStream">圖片流</param>
        /// <param name="quality">壓縮質量0-100之間 數值越大質量越高</param>
        /// <returns></returns>
        private byte[] CompressionImage(Stream fileStream, long quality)
        {
            using (System.Drawing.Image img = System.Drawing.Image.FromStream(fileStream))
            {
                using (Bitmap bitmap = new Bitmap(img))
                {
                    ImageCodecInfo CodecInfo = GetEncoder(img.RawFormat);
                    System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                    EncoderParameters myEncoderParameters = new EncoderParameters(1);
                    EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, quality);
                    myEncoderParameters.Param[0] = myEncoderParameter;
                    using (MemoryStream ms = new MemoryStream())
                    {
                        bitmap.Save(ms, CodecInfo, myEncoderParameters);
                        myEncoderParameters.Dispose();
                        myEncoderParameter.Dispose();
                        return ms.ToArray();
                    }
                }
            }
        }

        /// <summary>
        /// 壓縮圖片 /// </summary>
        /// <param name="fileStream">圖片流</param>
        /// <param name="quality">壓縮質量0-100之間 數值越大質量越高</param>
        /// <returns></returns>
        public static Bitmap CompressionImage(Bitmap b, long quality)
        {
            using (Bitmap bitmap = new Bitmap(b))
            {
                ImageCodecInfo CodecInfo = GetEncoder(ImageFormat.Jpeg);
                System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                EncoderParameters myEncoderParameters = new EncoderParameters(1);
                EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, quality);
                myEncoderParameters.Param[0] = myEncoderParameter;
                using (MemoryStream ms = new MemoryStream())
                {
                    bitmap.Save(ms, CodecInfo, myEncoderParameters);
                    myEncoderParameters.Dispose();
                    myEncoderParameter.Dispose();
                    return new Bitmap((Image)new Bitmap(ms));
                }
            }
        }

        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                { return codec; }
            }
            return null;
        }

        public static Bitmap BytesToBitmap(byte[] Bytes)
        {
            MemoryStream stream = null;
            try
            {
                stream = new MemoryStream(Bytes);
                return new Bitmap((Image)new Bitmap(stream));
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        }

        /// <summary>
        /// GDI压缩图片
        /// </summary>
        /// <param name="bmp">传入参数Bitmap</param>
        /// <returns></returns>
        public byte[] ImageGdi(Bitmap bmp)
        {
            Bitmap xbmp = new Bitmap(bmp);
            MemoryStream ms = new MemoryStream();
            xbmp.Save(ms, ImageFormat.Jpeg);
            byte[] buffer;
            ms.Flush();
            if (ms.Length > 95000)
            {
                //buffer = ms.GetBuffer();
                double new_width = 0;
                double new_height = 0;

                Image m_src_image = Image.FromStream(ms);
                if (m_src_image.Width >= m_src_image.Height)
                {
                    new_width = 1024;
                    new_height = new_width * m_src_image.Height / (double)m_src_image.Width;
                }
                else if (m_src_image.Height >= m_src_image.Width)
                {
                    new_height = 768;
                    new_width = new_height * m_src_image.Width / (double)m_src_image.Height;
                }

                Bitmap bbmp = new Bitmap((int)new_width, (int)new_height, m_src_image.PixelFormat);
                Graphics m_graphics = Graphics.FromImage(bbmp);
                m_graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                m_graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                m_graphics.DrawImage(m_src_image, 0, 0, bbmp.Width, bbmp.Height);

                ms = new MemoryStream();

                bbmp.Save(ms, ImageFormat.Jpeg);
                buffer = ms.GetBuffer();
                ms.Close();

                return buffer;
            }
            else
            {
                buffer = ms.GetBuffer();
                ms.Close();
                return buffer;
            }
        }



        #endregion
相关推荐
kylezhao201943 分钟前
C#序列化与反序列化详细讲解与应用
c#
JQLvopkk1 小时前
C# 实践AI :Visual Studio + VSCode 组合方案
人工智能·c#·visual studio
故事不长丨1 小时前
C#线程同步:lock、Monitor、Mutex原理+用法+实战全解析
开发语言·算法·c#
kingwebo'sZone1 小时前
C#使用Aspose.Words把 word转成图片
前端·c#·word
杜子不疼.2 小时前
CANN计算机视觉算子库ops-cv的图像处理与特征提取优化实践
图像处理·人工智能·计算机视觉
大空大地20262 小时前
表达式与运算符
c#
向上的车轮2 小时前
为什么.NET(C#)转 Java 开发时常常在“吐槽”Java:checked exception
java·c#·.net
心疼你的一切4 小时前
Unity异步编程神器:Unitask库深度解析(功能+实战案例+API全指南)
深度学习·unity·c#·游戏引擎·unitask
.房东的猫14 小时前
ERP(金蝶云星空)开发【安装篇】
c#
北京青翼科技1 天前
【PCIe732】青翼PCIe采集卡-优质光纤卡- PCIe接口-万兆光纤卡
图像处理·人工智能·fpga开发·智能硬件·嵌入式实时数据库