CoreGraphics在调整图片大小(CoreGraphics Image resize)

2019-06-25 10:17发布

此代码是从苹果的WWDC 2011届318 - iOS设备性能的深度和使用CoreGraphics中创建一个从服务器托管的图片的缩略图。

CGImageSourceRef src = CGImageSourceCreateWithURL(url);
NSDictionary *options = (CFDictionaryRef)[NSDictionary 
dictionaryWithObject:[NSNumber numberWithInt:1024
forKey:(id)kCGImageSourceThumbnailMaxPixelSize];

CGImageRef thumbnail = CGImageSourceCreateThumbnailAtIndex(src,0,options);
UIImage *image = [UIImage imageWithCGImage:thumbnail];
CGImageRelease(thumbnail);
CGImageSourceRelease(src); 

但它不工作和文档不真正的帮助。 在iOS的文档CGImageSource CGImageSourceRef CGImageSourceCreateThumbnailAtIndex可用

在Mac OS X v10.4或更高版本

我怎样才能得到这个工作?

编辑

这是我收到的编译器错误:

  • 未声明的标识符的使用“CGImageSourceRef”
  • 未声明的标识符的使用“kCGImageSourceThumbnailMaxPixelSize”
  • 未声明的标识符“src”中的应用
  • 功能“CGImageSourceCreateThumbnailAtIndex”隐式声明是无效的C99
  • 功能“CGImageSourceRelease”隐式声明是无效的C99
  • 功能“CGImageSourceCreateWithURL”隐式声明是无效的C99

Answer 1:

学校的男孩错误。

没有添加#import <ImageIO/ImageIO.h>



Answer 2:

尝试图像尺寸:

-(UIImage*) resizedImage:(UIImage *)inImage:(CGRect) thumbRect
{
    CGImageRef          imageRef = [inImage CGImage];
    CGImageAlphaInfo    alphaInfo = CGImageGetAlphaInfo(imageRef);

    // There's a wierdness with kCGImageAlphaNone and CGBitmapContextCreate
    // see Supported Pixel Formats in the Quartz 2D Programming Guide
    // Creating a Bitmap Graphics Context section
    // only RGB 8 bit images with alpha of kCGImageAlphaNoneSkipFirst, kCGImageAlphaNoneSkipLast, kCGImageAlphaPremultipliedFirst,
    // and kCGImageAlphaPremultipliedLast, with a few other oddball image kinds are supported
    // The images on input here are likely to be png or jpeg files
    if (alphaInfo == kCGImageAlphaNone)
        alphaInfo = kCGImageAlphaNoneSkipLast;

    // Build a bitmap context that's the size of the thumbRect
    CGContextRef bitmap = CGBitmapContextCreate(
                                                NULL,
                                                thumbRect.size.width,       // width
                                                thumbRect.size.height,      // height
                                                CGImageGetBitsPerComponent(imageRef),   // really needs to always be 8
                                                4 * thumbRect.size.width,   // rowbytes
                                                CGImageGetColorSpace(imageRef),
                                                alphaInfo
                                                );

    // Draw into the context, this scales the image
    CGContextDrawImage(bitmap, thumbRect, imageRef);

    // Get an image from the context and a UIImage
    CGImageRef  ref = CGBitmapContextCreateImage(bitmap);
    UIImage*    result = [UIImage imageWithCGImage:ref];

    CGContextRelease(bitmap);   // ok if NULL
    CGImageRelease(ref);

    return result;
}

我用它在我的代码一段时间,但我不记得它的源

试试这个还调整一个UIImage无需加载它完全到内存?



文章来源: CoreGraphics Image resize