[ Remember to release the return CGImageRef with CGImageRelease() manually! ]
1) scale image with scale rate.
+(CGImageRef)scaleCGImage: (CGImageRef) image withScale: (float) scale
{
// Create the bitmap context
CGContextRef context = NULL;
void * bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
// Get image width, height. We'll use the entire image.
int width = CGImageGetWidth(image) * scale;
int height = CGImageGetHeight(image) * scale;
// Declare the number of bytes per row. Each pixel in the bitmap in this
// example is represented by 4 bytes; 8 bits each of red, green, blue, and
// alpha.
bitmapBytesPerRow = (width * 4);
bitmapByteCount = (bitmapBytesPerRow * height);
// Allocate memory for image data. This is the destination in memory
// where any drawing to the bitmap context will be rendered.
bitmapData = malloc( bitmapByteCount );
if (bitmapData == NULL)
{
return nil;
}
// Create the bitmap context. We want pre-multiplied ARGB, 8-bits
// per component. Regardless of what the source image format is
// (CMYK, Grayscale, and so on) it will be converted over to the format
// specified here by CGBitmapContextCreate.
CGColorSpaceRef colorspace = CGImageGetColorSpace(image);
context = CGBitmapContextCreate (bitmapData,width,height,8,bitmapBytesPerRow,
colorspace,kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorspace);
if (context == NULL)
// error creating context
return nil;
// Draw the image to the bitmap context. Once we draw, the memory
// allocated for the context for rendering will then contain the
// raw image data in the specified color space.
CGContextDrawImage(context, CGRectMake(0,0,width, height), image);
CGImageRef imgRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
free(bitmapData);
return imgRef;
}
2) Scale image with size and rotation
+(CGImageRef)scaleCGImage: (CGImageRef) image withPrefix: (CGSize) size withRotation: (float) rotation
{
CGContextRef context = NULL;
void * bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
int width = size.width;
int height = size.height;
bitmapBytesPerRow = (width * 4);
bitmapByteCount = (bitmapBytesPerRow * height);
bitmapData = malloc( bitmapByteCount );
if (bitmapData == NULL)
{
return nil;
}
memset(bitmapData, 0, bitmapByteCount);
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
context = CGBitmapContextCreate (bitmapData,width,height,8,bitmapBytesPerRow,
colorspace,kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorspace);
if (context == NULL)
return nil;
if(rotation != 0){
CGAffineTransform tran = CGAffineTransformIdentity;
tran = CGAffineTransformMakeRotation(rotation);
CGContextConcatCTM(context, tran);
CGContextDrawImage(context, CGRectMake(10, 10, width - 20, height - 20), image);
}else{
CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
}
CGImageRef imgRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
free(bitmapData);
return imgRef;
}
Recent Comments