ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

在Windows窗体中使用alpha通道保存一种颜色位图会保存另一种(错误的)颜色

2019-11-01 23:17:29  阅读:180  来源: 互联网

标签:alpha-transparency system-drawing bitmap c winforms


在C#、. NET 2.0,Windows窗体,Visual Studio Express 2010中,我保存的是相同颜色的图像:

  Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
  using (Graphics graphics = Graphics.FromImage(bitmap))
  {
      Brush brush = new SolidBrush(color);
      graphics.FillRectangle(brush, 0, 0, width, height);
      brush.Dispose();
  }

  bitmap.Save("test.png");
  bitmap.Save("test.bmp");

例如,如果我正在使用

颜色[A = 153,R = 193,G = 204,B = 17]或#C1CC11

保存图像并在外部查看器(例如Paint.NET,IrfanView,XNView等)中打开它后,会被告知图像的颜色实际上是:

颜色[A = 153,R = 193,G = 203,B = 16]或#C1CB10

所以它是相似的颜色,但是不一样!

我尝试了保存PNG和BMP.

当涉及透明度(alpha)时,.NET将保存不同的颜色!
当Alpha为255(无透明度)时,它会保存相应的颜色.

解决方法:

谢谢Joe和Hans Passant的评论.

是的,正如乔所说,问题就在网上:

graphics.FillRectangle(brush, 0, 0, width, height);

在这里,GDI会用类似的颜色修改颜色,但不是精确的颜色.

看来解决方案是使用Bitmap.LockBits和Marshal.Copy直接在像素中写入颜色值:

        Bitmap bitmap = new Bitmap(this.currentSampleWidth, this.currentSampleHeight, PixelFormat.Format32bppArgb);

        // Lock the bitmap's bits.  
        Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
        BitmapData bmpData = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat);

        // Get the address of the first line.
        IntPtr ptr = bmpData.Scan0;

        // Declare an array to hold the bytes of the bitmap (32 bits per pixel)
        int pixelsCount = bitmap.Width * bitmap.Height;
        int[] argbValues = new int[pixelsCount];

        // Copy the RGB values into the array.
        System.Runtime.InteropServices.Marshal.Copy(ptr, argbValues, 0, pixelsCount);

        // Set the color value for each pixel.
        for (int counter = 0; counter < argbValues.Length; counter++)
            argbValues[counter] = color.ToArgb();

        // Copy the RGB values back to the bitmap
        System.Runtime.InteropServices.Marshal.Copy(argbValues, 0, ptr, pixelsCount);

        // Unlock the bits.
        bitmap.UnlockBits(bmpData);

        return bitmap;

标签:alpha-transparency,system-drawing,bitmap,c,winforms
来源: https://codeday.me/bug/20191101/1987215.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有