-1

我的图像大小是 2x2,所以计数像素 = 4

1 个像素 - 4 个字节

所以我有一个 16 字节的数组 - mas[16] - width * height * 4 = 16

我想制作相同的图像,但尺寸更多是 2 的因数,这意味着不是 1 而是四个像素

新数组的大小为 64 字节 - newMas[16] - width*2 * height*2 * 4

问题,我无法将像素正确复制到 newMas,使用不同大小的图像正确复制像素 在此处输入图像描述

此代码将像素复制到 mas[16]

    size_t width = CGImageGetWidth(imgRef);
    size_t height = CGImageGetHeight(imgRef);
    const size_t bytesPerRow = width * 4;
    const size_t bitmapByteCount = bytesPerRow * height;
    size_t mas[bitmapByteCount];
    UInt8* data = (UInt8*)CGBitmapContextGetData(bmContext);

      for (size_t i = 0; i < bitmapByteCount; i +=4)
        {
            UInt8 a = data[i];
            UInt8 r = data[i + 1];
            UInt8 g = data[i + 2];
            UInt8 b = data[i + 3];

            mas[i]   = a;
            mas[i+1] = r;
            mas[i+2] = g;
            mas[i+3] = b;        

        }
4

1 回答 1

0

一般来说,使用内置的图像绘制 API 比编写自己的图像处理代码更快,更不容易出错。上述代码中至少存在三个潜在错误:

  • 它假定行尾没有填充(iOS 似乎填充了 16 个字节的倍数);您需要使用 CGImageGetBytesPerRow()。
  • 它采用固定的像素格式。
  • 它从 CGImage 获取宽度/高度,但从 CGBitmapContext 获取数据。

假设你有一个 UIImage,

CGRect r = {{0,0},img.size};
r.size.width *= 2;
r.size.height *= 2;
UIGraphicsBeginImageContext(r.size);
// This turns off interpolation in order to do pixel-doubling.
CGContextSetInterpolationQuality(UIGraphicsGetCurrentContext(), kCGInterpolationNone);
[img drawRect:r];
UIImage * bigImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
于 2012-11-09T21:04:37.110 回答