我正在尝试实现一个简单的Box Blur,但遇到了问题。也就是说,它似乎将每个像素转换为红色、绿色、蓝色或黑色,而不是模糊图像。不确定到底发生了什么。任何帮助都将不胜感激。
请注意,这段代码只是让它工作的第一步,我并不担心速度……目前还没有。
- (CGImageRef)blur:(CGImageRef)base radius:(int)radius {
CGContextRef ctx;
CGImageRef imageRef = base;
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width *4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
char red = 0;
char green = 0;
char blue = 0;
for (int widthIndex = radius; widthIndex < width - radius; widthIndex++) {
for (int heightIndex = radius; heightIndex < height - radius; heightIndex++) {
red = 0;
green = 0;
blue = 0;
for (int radiusY = -radius; radiusY <= radius; ++radiusY) {
for (int radiusX = -radius; radiusX <= radius; ++radiusX) {
int xIndex = widthIndex + radiusX;
int yIndex = heightIndex + radiusY;
int index = ((yIndex * width) + xIndex) * 4;
red += rawData[index];
green += rawData[index + 1];
blue += rawData[index + 2];
}
}
int currentIndex = ((heightIndex * width) + widthIndex) * 4;
int divisor = (radius * 2) + 1;
divisor *= divisor;
int finalRed = red / divisor;
int finalGreen = green / divisor;
int finalBlue = blue / divisor;
rawData[currentIndex] = (char)finalRed;
rawData[currentIndex + 1] = (char)finalGreen;
rawData[currentIndex + 2] = (char)finalBlue;
}
}
ctx = CGBitmapContextCreate(rawData,
CGImageGetWidth( imageRef ),
CGImageGetHeight( imageRef ),
8,
CGImageGetBytesPerRow( imageRef ),
CGImageGetColorSpace( imageRef ),
kCGImageAlphaPremultipliedLast );
imageRef = CGBitmapContextCreateImage (ctx);
CGContextRelease(ctx);
free(rawData);
[(id)imageRef autorelease];
return imageRef;
}发布于 2011-02-09 04:07:48
字符颜色应该声明为int。
int red = 0;
int green = 0;
int blue = 0;发布于 2012-03-27 20:40:32
我只有一个评论。我使用了这个脚本,它真的工作得又好又快。唯一的事情是,它离开的框架与半径的宽度是不模糊的。所以我对它做了一些修改,以便它在边缘附近使用镜像技术模糊整个区域。
对于这个,需要放入以下几行:
// Mirroring the part between edge and blur raduis
if (xIndex<0) xIndex=-xIndex-1; else if (xIndex>width-1) xIndex=2*width-xIndex-1;
if (yIndex<0) yIndex=-yIndex-1; else if (yIndex>height-1) yIndex=2*height-yIndex-1;在这些行之后:
int xIndex = widthIndex + radiusX;
int yIndex = heightIndex + radiusY;然后替换for循环的头部:
for (int widthIndex = radius; widthIndex < width - radius; widthIndex++) {
for (int heightIndex = radius; heightIndex < height - radius; heightIndex++) {使用这些标头:
for (int widthIndex = 0; widthIndex < width; widthIndex++) {
for (int heightIndex = 0; heightIndex < height; heightIndex++) {https://stackoverflow.com/questions/4934687
复制相似问题