首页 > 编程语言 >C# byte[]与Bitmap互转

C# byte[]与Bitmap互转

时间:2023-08-09 11:36:11浏览次数:43  
标签:C# System Bitmap PixelFormat 互转 new byte bitmap

首先先观察一下本地bmp图像结构(参考:https://blog.csdn.net/qq_37872392/article/details/124710600):

 可以看到bmp图像结构除了纯图像像素点位信息,还有一块未用空间(OffSet)。

  • 所以如果需要得到图像所有数据进行转换,则可以使用网上提供的大部分方式:

bitmap转byte[]:

public byte[] BitmapToByte(System.Drawing.Bitmap bitmap)
{
      System.IO.MemoryStream ms = new System.IO.MemoryStream();
      bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
      ms.Seek(0, System.IO.SeekOrigin.Begin);
      byte[] bytes = new byte[ms.Length];
      ms.Read(bytes, 0, bytes.Length);
      ms.Dispose();
      return bytes;
}

byte[]转bitmap:

public Bitmap ByteToBitmap(byte[] ImageByte)
{
    Bitmap bitmap = null;using (MemoryStream stream = new MemoryStream(ImageByte))        
{ bitmap = new Bitmap((Image)new Bitmap(stream)); }return bitmap; }
  • 如果只需要得到纯图像像素点位信息,则可以使用以下方式:

Bitmap转byte[]:

    /// <summary>Bitmap转byte[]</summary>
    /// <param name="bitmap"></param>
    /// <returns></returns>
    private byte[] BitmapToByteArray(Bitmap bitmap)
    {
      PixelFormat pixelFormat1 = this.PixelFormat;
      System.Drawing.Imaging.PixelFormat pixelFormat2;
      if (pixelFormat1 != PixelFormat.Bgra32)
      {
        if (pixelFormat1 != PixelFormat.Bgr24)
          throw new ArgumentOutOfRangeException("PixelFormat", (object) this.PixelFormat, (string) null);
        pixelFormat2 = System.Drawing.Imaging.PixelFormat.Format24bppRgb;
      }
      else
        pixelFormat2 = System.Drawing.Imaging.PixelFormat.Format32bppArgb;
      System.Drawing.Imaging.PixelFormat format = pixelFormat2;
      Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
      BitmapData bitmapdata = bitmap.LockBits(rect, ImageLockMode.ReadOnly, format);
      int length = Math.Abs(bitmapdata.Stride) * bitmap.Height;
      byte[] destination = new byte[length];
      Marshal.Copy(bitmapdata.Scan0, destination, 0, length);
      bitmap.UnlockBits(bitmapdata);
      return destination;
    }

byte[]转Bitmap:

        private Bitmap ConvertFromRGBA(byte[] rgbaData, int width, int height)
        {
            var pixelFormat = PixelFormat.Format32bppRgb;
            Bitmap bitmap = new Bitmap(width, height, pixelFormat);

            BitmapData bitmapData = bitmap.LockBits(
                new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.WriteOnly,
                pixelFormat);

            IntPtr intPtr = bitmapData.Scan0;
            System.Runtime.InteropServices.Marshal.Copy(rgbaData, 0, intPtr, rgbaData.Length);
            bitmap.UnlockBits(bitmapData);

            return bitmap;
        }

其中注意pixelFormat两次转换必须一致。

标签:C#,System,Bitmap,PixelFormat,互转,new,byte,bitmap
From: https://www.cnblogs.com/log9527blog/p/17616377.html

相关文章

  • .NET CORE Worker Service服务访问服务器共享目录提示无权限
    问题:.NETCOREWorkerService中访问服务器共享目录,代码运行时不报错,发布出来后访问共享目录创建文件夹或者文件等所有操作都提示无权限解决方案:先对共享目录进行连接,然后再进行文件夹或文件创建等操作boolstate=connectState(共享目录路径,用户名,密码);......
  • java XSSFWorkbook excel 公式计算
    excel公式计算//创建一个工作薄XSSFWorkbookworkbook=newXSSFWorkbook();//如果是最后一列添加一个求和计算,将结果放到同一列最后一个。dataLists数据列表XSSFSheetsheet=workbook.getSheet(replaceSpecStr(sheetNames.get(0)));Rowrow......
  • MuMu模拟器运行一段时间后Device.Present耗时突然上升
    1)MuMu模拟器运行一段时间后Device.Present耗时突然上升2)​如何在运行过程中获得温度信息3)InputSystem鼠标更换主按键的Bug4)如何禁止Unity向https://config.uca.cloud.unity3d.com发送设备信息这是第347篇UWA技术知识分享的推送,精选了UWA社区的热门话题,涵盖了UWA问答、社区帖子......
  • 微前端框架哪个好?QianKun还是MicroApp
    在当前云原生微服务、业务中台、低代码平台等IT架构下,不再是传统的烟囱式应用系统建设,而是打破企业业务部门竖井,建立企业级的信息化平台(数据中台、业务中台),那么对业务开发的解耦和聚合将成为关键技术,目前对于系统后端已有成熟的微服务架构,基于SpringBoot开发微服务,通过SpringCloud......
  • docker部署php7.3+nginx
    1.拉取php+nginx镜像dockerpullphp:7.3.24-fpm-stretchdockerpullnginx:latest 2.启动PHP:dockerrun-d-v/var/www/test:/var/www/html-p9000:9000--namexy_phpfpmphp:7.3.24-fpm-stretch 参数说明-d让容器在后台运行-p添加主机到容器的端口映射-......
  • Bert Pytorch 源码分析:五、模型架构简图 REV1
    注意力FFNTF块整体架构......
  • C# picturebox画矩形、圆
    usingSystem;usingSystem.Collections.Generic;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespace自定义画矩形{///<summary>///类型:1、画矩形2、画圆///绘制按钮:drawState=t......
  • 关于CH32F系列以及CH32V系列 SysTick的使用
    1、关于SysTickCH32F103/203:CH32F103/203SysTick和STM32F103一样为Cortex-M3内核,是一个24位的向下递减计数器,计数器每计数一次的时间为1/SYSCLK(系统主频)。当SysTick重装载数寄存器的值递减到0的时候,产生一次中断。CH32F系列MCUSysTick由4个寄存器控制,具体如下图。具体介绍可......
  • c++中template的用法是什么?
    下文由ChatGPT生成在C++中,template是一种通用编程工具,用于创建通用的函数或类。通过使用模板,可以编写可以应用于不同数据类型的函数或类,从而实现代码的重用性和灵活性。template的使用方法如下:1.函数模板(FunctionTemplates)函数模板允许定义一个通用的函数,可以在不同数据类......
  • C# 使用FFmpeg.Autogen对byte[]进行编解码
    C#使用FFmpeg.Autogen对byte[]进行编解码,参考:https://github.com/vanjoge/CSharpVideoDemo入口调用类:usingSystem;usingSystem.IO;usingSystem.Drawing;usingSystem.Runtime.InteropServices;usingFFmpeg.AutoGen;namespaceFFmpegAnalyzer{publicclassFFm......