gpt4 book ai didi

iphone - 为什么我在编辑图像时会得到这些奇怪的结果?

转载 作者:行者123 更新时间:2023-11-28 23:15:52 26 4
gpt4 key购买 nike

我正在尝试做一些非常简单的事情:

1) 将 UIImage 绘制到 CG 位图上下文中

2) 获取图像数据的指针

3) 遍历所有像素并将所有 R G B 分量设置为 0 并将 alpha 设置为 255。结果应该显示为纯黑色。


这是我使用的原始图像。 200 x 40 像素,PNG-24 ARGB 预乘 alpha(所有 alpha 值 == 255):

original


这是我未修改像素时的结果(来自模拟器的屏幕截图)。看起来不错:

unmodified result


这是我修改后的结果!看起来好像修改不完整。 但是 for 循环遍历了每个像素。计数器证明了这一点:控制台报告 modifiedPixels = 8000,正好是 200 x 40 像素。它看起来总是完全一样。

modified result

注意:我使用的 PNG 图像没有 alpha < 255。因此没有透明像素。


这就是我创建上下文的方式。没什么特别的……

int bitmapBytesPerRow = (width * 4);
int bitmapByteCount = (bitmapBytesPerRow * imageHeight);

colorSpace = CGColorSpaceCreateDeviceRGB();

bitmapData = malloc(bitmapByteCount);
bitmapContext = CGBitmapContextCreate(bitmapData,
width,
height,
8, // bits per component
bitmapBytesPerRow,
colorSpace,
CGImageAlphaPremultipliedFirst);

接下来,我将图像绘制到 bitmapContext 中,并像这样获取数据:

void *data = CGBitmapContextGetData(bitmapContext);

这是遍历像素以修改它们的代码:

size_t bytesPerRow = CGImageGetBytesPerRow(img);

NSInteger modifiedPixels = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
long int offset = bytesPerRow * y + 4 * x;

// ARGB
unsigned char alpha = data[offset];
unsigned char red = data[offset+1];
unsigned char green = data[offset+2];
unsigned char blue = data[offset+3];

data[offset] = 255;
data[offset+1] = 0;
data[offset+2] = 0;
data[offset+3] = 0;

modifiedPixels++;
}
}

完成后,我从位图上下文中获取一个新的 UIImage 并将其显示在 UIImageView 中,以查看结果:

CGImageRef imageRef = CGBitmapContextCreateImage(bitmapContext);
UIImage *img = [[UIImage alloc] initWithCGImage:imageRef];

问题:

我做错了什么?

发生这种情况是因为我在迭代数据时修改了数据吗?我必须复制它吗?

最佳答案

使用 CGBitmapContextGetBytesPerRow(bitmapContext) 获取 bytesPerRow 而不是从图像获取(如果图像没有 alpha 信息,则每个像素只有 3 个字节)

关于iphone - 为什么我在编辑图像时会得到这些奇怪的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6396579/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com