2009-10-15 49 views
4

有没有可以帮助我缩小图像的任何代码或库?如果您使用iPhone拍摄照片,则其像2000x1000像素,这不是非常网络友好的。我想把它缩小到480x320。任何提示?任何缩小UIImage的代码/库?

+0

你为什么想缩放它?仅用于显示还是上传? – 2009-10-16 08:55:27

回答

8

这就是我正在使用的。效果很好。我一定会看这个问题,看看有没有人有更好/更快的事情。我只是将以下内容添加到UIimage的类别中。

+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize { 
    UIGraphicsBeginImageContext(newSize); 
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)]; 
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    return newImage; 
} 
+0

那么如果比例不同,会发生什么? DrawInRect会做什么?说原件是2000x1000,我通过了480x480 – erotsppa 2009-10-15 17:56:37

+0

从UIImage上的开发人员文档 - “在指定的矩形中绘制整个图像,根据需要缩放它以适应。” – mmc 2009-10-15 19:25:22

+0

此方法需要长时间运行,有时超过一分钟。我将iPhone 3GS相机拍摄的照片缩小到500x500。我为什么想知道? – erotsppa 2009-10-16 14:43:36

0

请注意,这不是我的代码。我做了一点挖掘,发现它here。我想你不得不放入CoreGraphics层,但不太清楚具体细节。这应该工作。只是要小心管理你的记忆。

// ============================================================== 
// resizedImage 
// ============================================================== 
// Return a scaled down copy of the image. 

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; 
} 
+0

这是一个答案?它工作吗?我应该upvote它吗? – 2012-02-04 06:54:52

0

请参阅我发布到this question的解决方案。这个问题涉及将图像旋转90度而不是缩放,但前提是相同的(只是矩阵变换不同)。