您的位置:首页 > 移动开发 > IOS开发

iOS学习----------图片的简单处理(2)

2016-02-17 23:38 393 查看
接第一部分内容

//图片的大小

CGSize ghostSize =
CGSizeMake(targetGhostWidth, targetGhostWidth / ghostImageAspectRatio);

//图片的位置

CGPoint ghostOrigin =
CGPointMake(inputWidth * 0.5, inputHeight *
0.2);

// 2.2 Scale & Get pixels of the ghost

NSUInteger ghostBytesPerRow = bytesPerPixel * ghostSize.width;

UInt32 * ghostPixels = (UInt32 *)calloc(ghostSize.width * ghostSize.height,
sizeof(UInt32));

CGContextRef ghostContext =
CGBitmapContextCreate(ghostPixels, ghostSize.width, ghostSize.height,
bitsPerComponent, ghostBytesPerRow, colorSpace,

kCGImageAlphaPremultipliedLast |
kCGBitmapByteOrder32Big);

CGContextDrawImage(ghostContext,
CGRectMake(0,
0, ghostSize.width, ghostSize.height),ghostCGImage);

// 2.3 Blend each pixel

NSUInteger offsetPixelCountForInput = ghostOrigin.y * inputWidth + ghostOrigin.x;

for (NSUInteger j =
0; j < ghostSize.height; j++) {

for (NSUInteger i =
0; i < ghostSize.width; i++) {

UInt32 * inputPixel = inputPixels + j * inputWidth + i + offsetPixelCountForInput;

UInt32 inputColor = *inputPixel;

UInt32 * ghostPixel = ghostPixels + j * (int)ghostSize.width + i;

UInt32 ghostColor = *ghostPixel;

// Blend the ghost with 50% alpha

CGFloat ghostAlpha =
0.5f * (A(ghostColor) /
255.0);

UInt32 newR = R(inputColor) * (1 - ghostAlpha) +
R(ghostColor) * ghostAlpha;

UInt32 newG = G(inputColor) * (1 - ghostAlpha) +
G(ghostColor) * ghostAlpha;

UInt32 newB = B(inputColor) * (1 - ghostAlpha) +
B(ghostColor) * ghostAlpha;

//Clamp, not really useful here :p
newR =
MAX(0,MIN(255, newR));
newG =
MAX(0,MIN(255, newG));
newB =
MAX(0,MIN(255, newB));

*inputPixel =
RGBAMake(newR, newG, newB,
A(inputColor));
}
}

// 3. Convert the image to Black & White

for (NSUInteger j =
0; j < inputHeight; j++) {

for (NSUInteger i =
0; i < inputWidth; i++) {

UInt32 * currentPixel = inputPixels + (j * inputWidth) + i;

UInt32 color = *currentPixel;

// Average of RGB = greyscale

UInt32 averageColor = (R(color) +
G(color) + B(color)) /
3.0;

*currentPixel =
RGBAMake(averageColor, averageColor, averageColor,
A(color));
}
}

// 4. Create a new UIImage

//将context中画好的图片
转化为CGImage

CGImageRef newCGImage =
CGBitmapContextCreateImage(context);

UIImage * processedImage = [UIImage
imageWithCGImage:newCGImage];

// 5. Cleanup!

CGColorSpaceRelease(colorSpace);

CGContextRelease(context);

CGContextRelease(ghostContext);

free(inputPixels);

free(ghostPixels);

return processedImage;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: