2009-10-15 55 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度而不是縮放,但前提是相同的(只是矩陣變換不同)。