C 中的位打包

发布于 2024-07-17 21:13:05 字数 114 浏览 3 评论 0原文

我正在尝试将 RGB 图像转换为 ARGB 图像,基本上只是为 alpha 通道添加 255。 我想知道是否有任何包方法可以在不迭代的情况下执行此操作? 因此,要迭代 RGB 数据并将 255 附加到每个像素。

I'm trying to convert an RGB image to an ARGB image, basically just adding 255 in for the alpha channel. I was wondering if there is any pack method to do this without iteration? So to iterate over my RGB data and append the 255 to each pixel.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

悲念泪 2024-07-24 21:13:05

C 没有“方法”……不,这听起来不像标准库中的例程。 我认为你需要自己编码,使用如下内容:

void setAlpha(unsigned char *rgba, int width, int height, int alpha)
{
  int x, y;

  for(y = 0; y < height; y++)
  {
    for(x = 0; x < width; x++, rgba += 4)
    {
      rgba[3] = (unsigned char) alpha;
    }
  }
}

基本假设:

  • 内存中的打包顺序是 RGBA,即从像素开始到 alpha 字节的偏移量是 3。
  • 图像以左上角像素位于初始地址的方式存储,按照从右到左、从上到下的顺序。
  • 没有填充或任何东西

还要注意循环的顺序; 由于缓存,这会对现实世界的性能产生巨大的影响。 这段代码按顺序接触内存中接近的像素,这很好地称为“良好的局部性”。

将指针更改为指向下一个像素而不是声明地址 (rgba[4 * y * width + 4 * x + 3]) 也是一种优化,并且(对我来说)很容易理解。

C doesn't have "methods" ... And no, this doesn't sound like anything there's a routine for in the standard library. I think you need to code it yourself, using something like this:

void setAlpha(unsigned char *rgba, int width, int height, int alpha)
{
  int x, y;

  for(y = 0; y < height; y++)
  {
    for(x = 0; x < width; x++, rgba += 4)
    {
      rgba[3] = (unsigned char) alpha;
    }
  }
}

Basic assumptions:

  • Packing order is RGBA in memory, i.e. the offset is 3 to the alpha byte, from the start of the pixel.
  • Image is stored with the top-left pixel at the initial address, in right-to-left, top-to-bottom order.
  • There is no padding or anything

Also note order of loops; this can make a huge difference to real-world performance due to caching. This code touches pixels that are close in memory in sequence, which is good called "good locality".

Changing the pointer to point at the next pixel rather than stating the address (rgba[4 * y * width + 4 * x + 3]) is also an optimization, and (to me) easy enough to understand.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文