当前位置: 首页 > news >正文

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度

bmp.RotateFlip(RotateFlipType.Rotate270FlipNone);

1.byte[] 转Bitmap 

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.Format24bppRgbbitmap = 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[]

  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 MyRegionusing (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

    /// <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.图像裁剪

  #region 裁剪////// 剪裁 -- 用GDI+////// 原始Bitmap/// 开始坐标X/// 开始坐标Y/// 宽度/// 高度/// 剪裁后的Bitmappublic 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.图像压缩

    #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);elseratio = 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

http://www.dtcms.com/a/427373.html

相关文章:

  • Labview多个子VI加密码和去密码
  • LabVIEW声音压力与响度实时监测
  • 网站毕业设计选题本溪网站建设兼职
  • Python利用ffmpeg实现rtmp视频拉流和推流
  • 佛山电商网站建设软件开发流程流程图
  • 嵌入式软件开发工程师待遇seo管理员
  • cuda编程笔记(25)-- 如何像函数对象一样使用核函数
  • K230基础-摄像头基本原理
  • 数学笔记①
  • 企业为什么要网站建设seo推广哪家服务好
  • 详细解说基于mysql分布式锁的三种实现方式
  • 外贸网站设计注意事项网站繁体和中文这么做
  • AdGuard解锁订阅版高级版 安卓广告拦截器APP v4.11.63 / 4.13.7 Nightly MOD
  • 网站建设免费书江宁网站制作
  • claude code + claude code router 接入魔搭、openrouter等
  • 图观 流渲染场景服务器
  • Android Studio 代码混淆核心解释
  • 雨晨WIN11PE网络版VIP资源国庆限时开放
  • 网站改版Excel怎么做泰安抖音seo
  • Websocket+Redis实现微服务消息实时同步
  • 仪器仪表第四节课学习笔记
  • Java 黑马程序员学习笔记(进阶篇15)
  • 【开题答辩过程】以《基于SpringBoot+Vue+uni-app的智慧校园服务系统的设计与实现》为例,不会开题答辩的可以进来看看
  • 做二手电脑的网站宣城网站建设 有限公司
  • 没有服务器 怎么做网站建设企业高端网站
  • 极简时钟APP(手机全能计时工具) 极简版
  • 华为光模块命名规则
  • 做企业网站用什么cms好易语言怎么做网页网站
  • 域名做网站北京 网站 公司
  • 深入浅出 Redis:从核心原理到运维实战指南一